Introduction to Docker Compose
When developing modern applications, you rarely rely on a single service. A typical web application requires a frontend, a backend API, a database, and perhaps a caching layer like Redis. Managing all these containers manually with individual docker run commands becomes tedious and error-prone. This is where Docker Compose comes in.
What is Docker Compose?
Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file (usually named docker-compose.yml) to configure your application's services, networks, and volumes. Then, with a single command, you create and start all the services from your configuration.
Anatomy of a docker-compose.yml File
Let's look at a practical example. Imagine we are building a Node.js API that connects to a PostgreSQL database. Here is what our Compose file would look like:
version: '3.8'
services:
api:
build: ./api
ports:
- "3000:3000"
environment:
- DB_HOST=db
- DB_USER=postgres
- DB_PASSWORD=secret
depends_on:
- db
db:
image: postgres:14
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=secret
- POSTGRES_DB=myapp
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
volumes:
pgdata:
Key Concepts Explained
Services
The services block defines the containers that will make up your application. In the example above, we have two services: api and db. The api service is built from a local Dockerfile, while the db service uses an official PostgreSQL image from Docker Hub.
Environment Variables
The environment section allows you to pass variables into the container. Notice how the api service uses DB_HOST=db. Docker Compose automatically sets up a default network where services can communicate with each other using their service names as hostnames.
Volumes
Containers are ephemeral by default. If the db container crashes or is removed, all your database data is lost. We solve this by defining a named volume (pgdata) and mounting it to the PostgreSQL data directory inside the container. This ensures data persistence across container restarts.
Useful Docker Compose Commands
docker-compose up -d: Starts all services in the background (detached mode).docker-compose down: Stops and removes all containers, networks, and anonymous volumes.docker-compose logs -f: Tails the logs of all running services, which is incredibly useful for debugging.docker-compose exec [service_name] bash: Opens a shell inside a running service container.
Mastering Docker Compose will dramatically improve your local development workflow, ensuring consistency between your local machine and your team's environments.
Written by A.M. Rinas