In this lesson, you will learn how to restrict communication between containers to ensure that only authorized services can access your sensitive backend components.
The Principle of Least Privilege
When you deploy containers on a shared Docker bridge network, they can typically "see" and communicate with every other container on that same network by default. While this makes development easy, it poses a security risk: if a compromised public-facing web server is on the same network as your database, that web server could potentially reach the database even if it shouldn't.
To prevent this, we move beyond simple connectivity and start enforcing Network Policies. By default, Docker bridge networks allow all traffic; however, we can tighten this by creating isolated networks or using firewall rules.
Implementing Isolation via Custom Networks
Instead of placing all containers on a single default network, we group them into functional tiers. Imagine a three-tier app: frontend, api, and db.
- Frontend network: Connects the web server to the API.
- Backend network: Connects the API to the database.
By keeping the database on a network that the frontend container is not joined to, you physically prevent the frontend from even routing packets to the database. Even if an attacker gains control of the frontend, they cannot reach the database because there is no network path between them.
# Example architecture using Docker Compose network isolation
services:
web:
networks:
- frontend-net
api:
networks:
- frontend-net
- backend-net
db:
networks:
- backend-net
networks:
frontend-net:
backend-net:
Why This Matters
In this setup, the api service acts as the gatekeeper. It is the only service connected to both networks, allowing it to bridge the gap while keeping the web and db services completely isolated from each other. This "tiered" approach is a fundamental practice in securing containerized environments, ensuring that if one layer is breached, the blast radius is strictly limited to that specific network segment.
Key Takeaway: Use isolated bridge networks to create physical traffic boundaries, ensuring that sensitive services remain unreachable to any container that does not explicitly require a connection.