CodeBlanks Logo Icon CodeBlanks

Volume and network

Add volume and network definitions to the compose file.

Volumes and networks

By default Compose puts all services on a single proje_default network. To separate tiers, custom networks are defined: only the API is on both the outer and inner networks; the database stays on a network unreachable from outside:

services:
  web:
    image: nginx:alpine
    networks: [on]
  api:
    build: .
    networks: [on, arka]
  db:
    image: postgres:16
    networks: [arka]

networks:
  on:
  arka:
    internal: true      # no outbound access either

Bind mounts and read-only config

To mount configuration files into services, a relative path is used in the short syntax; the path is relative to the compose file's folder:

  web:
    image: nginx:alpine
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - statik:/usr/share/nginx/html

volumes:
  statik:

docker compose down doesn't delete volumes; down -v deletes them too (data loss!).

Practice Tiered networks

Write a compose.yaml: the api service is built with build: . and is on the on and arka networks; the db service uses the postgres:16 image and is only on the arka network. Under a top-level networks:, define the on: network and the arka: network with internal: true.

Starter code

terminal
# compose.yaml
# buraya yaz

Sample solution

terminal
# compose.yaml
services:
  api:
    build: .
    networks:
      - on
      - arka
  db:
    image: postgres:16
    networks:
      - arka

networks:
  on:
  arka:
    internal: true

Expected output

[+] Running 4/4
 ✔ Network proje_on  Created
 ✔ Network proje_arka  Created
 ✔ Container proje-db-1  Started
 ✔ Container proje-api-1  Started

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In the file above, can the web service reach the db service?

  • Yes, always
  • Only if the port is published
  • Only by IP
  • No, they share no network Correct answer

Explanation: Containers talk only over the networks they share.

2 Close the network to the outside world.

Question
networks:
  arka:
    ____: true
Answer
networks:
  arka:
    internal: true

Explanation: Containers on an internal network can't reach the outside.

3 Match.

Term Meaning
proje_default Default network
internal: true Network closed to the outside
./nginx.conf:...:ro Read-only config
down -v Also deletes volumes

All lessons in Beginner