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
- Create a
docker-compose.ymlwith two networks:publicandprivate. - Add a
webservice to thepublicnetwork. - Add a
dbservice to theprivatenetwork. - Launch the stack.
- Use
docker execto enter thewebcontainer. Try toping db. It should fail! - How would you change the configuration so that
webcan talk todb?
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).