BudiBadu Logo
Samplebadu

Docker Compose by Example: Network Segmentation

Compose Specification v2

Isolating services with custom networks through this sample code demonstrating network definition with bridge driver, service network assignment, internal network isolation, and implementing least privilege networking.

Code

services:
  frontend:
    image: node:18-alpine
    # Connect to the public network
    networks:
      - public-net
      
  backend:
    image: python:3.9
    # Connect to both networks
    networks:
      - public-net
      - private-net
      
  database:
    image: postgres:15
    # Isolated in the private network
    networks:
      - private-net

# Define the networks
networks:
  public-net:
    driver: bridge
  private-net:
    driver: bridge
    internal: true

Explanation

While Docker Compose creates a default network for all services, custom networks enable application segmentation for security and architectural purposes. Defining networks in the top-level networks block and assigning services to them controls which containers can communicate, implementing network-layer isolation and the principle of least privilege.

This example creates a public network for frontend and backend services, and a private network for backend and database services. The frontend cannot access the database directly as they share no common network, preventing unauthorized data access. The bridge driver is the default for standalone containers, providing isolated network namespaces with virtual network interfaces.

Setting internal: true on a network creates complete isolation with no external internet access, perfect for securing sensitive data stores. Containers on internal networks can communicate with each other but cannot reach outside networks or the internet. This network segmentation architecture mirrors traditional network security practices, creating DMZs and protected zones within containerized environments.

Code Breakdown

5
networks: under service lists networks that service joins for communication.
22
Top-level networks: block defines available networks for the project.
24
driver: bridge creates isolated network namespace with virtual interfaces.
27
internal: true restricts external access, containers communicate internally only.