Module 3 Lesson 3: Networking and Volumes in Compose
·DevOps

Module 3 Lesson 3: Networking and Volumes in Compose

Connecting the dots automatically. Learn how Docker Compose handles networking and persistent storage, making complex configurations simple.

Module 5 Lesson 3: Networking and Volumes in Compose

In Modules 4 and 5, we learned how to manually create networks and volumes. Docker Compose automates this "Setup Work" so you can focus on your code.

1. Automatic Networking

When you run docker-compose up, Compose automatically creates a internal network (the "Default Network").

  • Every service in the file is automatically added to this network.
  • Discovery: The services can talk to each other using their service name as the hostname.
services:
  web:
    image: my-app
  db:
    image: postgres

Inside the web container, you can simply connect to postgres://db:5432. No IP addresses needed!


2. Persistent Storage (Volumes)

To save data in Compose, you must define the volumes at the Top Level and then "Mount" them to specific services.

version: "3.8"

services:
  database:
    image: postgres
    volumes:
      - db-data:/var/lib/postgresql/data  # Mount the volume

volumes:
  db-data:   # Define the named volume here

Why define at the bottom?

By defining db-data in the volumes section, you are telling Docker: "This volume might be shared by multiple services, and it should persist even if the containers are destroyed."


3. Bind Mounts in Compose

For development, you can still use bind mounts to link your local code.

services:
  api:
    build: .
    volumes:
      - .:/app   # Map current directory to /app inside container

4. Multiple Networks

Sometimes you want to isolate your database from the internet-facing web server.

services:
  proxy:
    image: nginx
    networks:
      - frontend

  api:
    image: my-api
    networks:
      - frontend
      - backend

  db:
    image: postgres
    networks:
      - backend

networks:
  frontend:
  backend:

In this example, the proxy can talk to the api, but the proxy cannot talk directly to the db. This is a core security best practice.


Exercise: The Secured Stack

  1. Create a docker-compose.yml with two networks: public and private.
  2. Add a web service to the public network.
  3. Add a db service to the private network.
  4. Launch the stack.
  5. Use docker exec to enter the web container. Try to ping db. It should fail!
  6. How would you change the configuration so that web can talk to db?

Summary

Docker Compose makes "Best Practices" easy. By automatically setting up DNS and providing a clean syntax for volumes and networks, it removes the "Ops complexity" from your local development.

Next Lesson: Controlling the chaos: Docker Compose CLI (up, down, logs).

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn