In this lesson, you will learn how to restrict communication between containers to ensure that a compromise in one service does not lead to a total system breach.
The Problem: Open Communication
By default, when you run containers on the same Docker bridge network, they can talk to each other freely using their container names. While convenient for development, this "flat" network model is a security risk. If an attacker gains control of a public-facing web server, they could use that access to scan and attack your internal database container sitting on the same network. This is known as lateral movement.
The Solution: Network Isolation
To prevent lateral movement, we use Network Segmentation. Instead of putting all your containers on one big, default network, you create separate virtual networks for different parts of your application architecture.
Think of this like building security walls in a building: you wouldn't give the person delivering mail access to the high-security server room. By segregating your containers into specific networks, you ensure that a container can only communicate with the services it absolutely requires to function.
Implementing Segmentation
In Docker, you can create a private network for your backend services and a separate one for your frontend. A container can only communicate with another if they are attached to the same network.
# Create a dedicated network for backend services
docker network create backend_net
# Run the database only on the backend network
docker run -d --name my-db --network backend_net postgres
# Run the app on both the frontend and backend networks
docker run -d --name my-app --network frontend_net --network backend_net my-app-image
In this setup, my-app can reach my-db because they share backend_net. However, another container on frontend_net cannot reach the database because it is not connected to backend_net. By grouping containers into logically isolated segments, you enforce the Principle of Least Privilege at the network level. If your frontend container is ever compromised, the attacker remains trapped in a network segment that does not contain your sensitive database.
Key Takeaway: By placing containers into separate, restricted virtual networks, you physically prevent unauthorized traffic flows and contain potential security breaches to the smallest possible blast radius.