Docker Compose — Networks — Practice Exercises

1 minute read

Test your understanding of Docker Compose networking.


Exercise 1: Default Network Discovery

Start this stack and verify that web can reach api by service name.

services:
  web:
    image: alpine
    command: sleep 3600
  api:
    image: alpine
    command: sleep 3600
Solution
docker compose up -d
docker compose exec web ping -c 2 api

Output:

PING api (172.20.0.3): 56 data bytes
64 bytes from 172.20.0.3: seq=0 ttl=64 time=0.098 ms

Exercise 2: Network Isolation

Create two networks (front and back). Put web on front, db on back, and api on both. Verify web cannot reach db.

Solution
services:
  web:
    image: alpine
    command: sleep 3600
    networks: [front]
  api:
    image: alpine
    command: sleep 3600
    networks: [front, back]
  db:
    image: alpine
    command: sleep 3600
    networks: [back]

networks:
  front:
  back:
docker compose up -d
docker compose exec web ping -c 1 db    # Fails — different networks
docker compose exec api ping -c 1 db    # Succeeds — shared network

Exercise 3: Network Alias

Give the api service an alias of backend-service and verify you can ping it using the alias.

Solution
services:
  api:
    image: alpine
    command: sleep 3600
    networks:
      app:
        aliases:
          - backend-service
  web:
    image: alpine
    command: sleep 3600
    networks:
      - app

networks:
  app:
docker compose up -d
docker compose exec web ping -c 1 backend-service

Exercise 4: Internal Network

Create an internal network (no internet) and verify a container on it cannot reach the outside.

Solution
services:
  isolated:
    image: alpine
    command: sleep 3600
    networks:
      - internal

networks:
  internal:
    internal: true
docker compose up -d
docker compose exec isolated ping -c 1 google.com   # Fails — no internet

Exercise 5: Cross-Project Networking

Create two separate Compose projects that share an external network and verify inter-project communication.

Solution
docker network create shared-net

project-a/compose.yml:

services:
  svc-a:
    image: alpine
    command: sleep 3600
    networks: [shared]
networks:
  shared:
    external: true
    name: shared-net

project-b/compose.yml:

services:
  svc-b:
    image: alpine
    command: sleep 3600
    networks: [shared]
networks:
  shared:
    external: true
    name: shared-net
cd project-a && docker compose up -d
cd ../project-b && docker compose up -d
docker compose exec svc-b ping -c 1 svc-a