Docker Compose for local stacks
Run the app with a database and cache using one compose file.
By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.
In short
Docker Compose describes a multi-container app in one YAML file. One command starts the API, database and cache together, wired up with networking, volumes and health checks.
Explained simply
Most apps need more than one container: the API, a database, maybe a cache. Starting each with a long docker run command is tiring and easy to get wrong. Docker Compose lets you write all of them in one file and start them together.
The file is called compose.yaml. Under services, you list each container: which image to use or which folder to build, which ports to open, which environment variables to set and which volumes to attach.
Compose creates a private network for the project. Every service can reach the others by service name, so the API connects to the database at db:5432. You do not need to know any IP addresses.
One command, docker compose up, builds what is needed and starts everything. docker compose down stops and removes the containers and the network, but keeps your named volumes and the data in them.
Health checks tell Compose when a service is actually ready, not just started. With them, the API can wait until Postgres accepts connections before it starts, which avoids errors in the first seconds.
Press Play on a diagram to walk through it one step at a time.
- services: api
- build: .
- ports 8000:8000
- env DATABASE_URL
- depends_on db healthy
- services: db
- image postgres:16
- volume pgdata
- healthcheck pg_isready
- services: cache
- image redis:7
- volumes
- pgdata
- docker compose stop: stop, keep containers
- docker compose down: remove containers and network
- Named volumes survive both
- up --build: rebuild images first
- up --force-recreate: new containers
- down -v: also delete volumes and data
In depth
How Compose names and connects things
Compose groups everything under a project name, by default the name of the folder holding compose.yaml (override it with -p or the top-level name key). Containers are named project-service-1, the network is project_default and named volumes become project_pgdata. This is how two copies of the same stack can run side by side without clashing.
On the project network, each service name is a DNS name. If you scale a service with --scale worker=3, the name resolves to all its containers. Remember the port rule: containers talk to each other on the container port (db:5432), and ports: only matters for reaching a service from your host. You can drop ports: entirely for the database if only the API needs it, which is also safer.
The old version: key at the top of the file is obsolete and ignored by Docker Compose v2. The command is docker compose with a space; the old docker-compose Python tool is retired.
- 1Project myapp
Named after the folder unless set with -p
- 2Network myapp_default
DNS: api, db and cache resolve by name
- 3Containers
myapp-api-1, myapp-db-1, myapp-cache-1
- 4Volumes
myapp_pgdata keeps the database files
Environment variables: three different mechanisms
Beginners often mix these up. First, environment: sets variables inside a container, written directly in the file. Second, env_file: loads variables into a container from a file such as api.env. Third, a file named .env next to compose.yaml is read by Compose itself to fill in ${VARIABLES} written in compose.yaml; those values are not passed into containers unless you reference them.
So POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD} reads DB_PASSWORD from your shell or .env and fails with a clear message if it is missing. ${TAG:-dev} uses dev as a default.
Run docker compose config to print the final file with every variable filled in. It is the fastest way to see what Compose will actually do. Keep .env out of Git, and commit a .env.example that lists the names with dummy values.
- environment: values written in compose.yaml
- env_file: load a file into one container
- .env: fills ${VAR} in compose.yaml itself
- docker compose config shows the final result
Start order, health checks and restarts
depends_on alone only controls start order: Compose starts db before api, but does not wait until Postgres is ready. Postgres takes a few seconds to initialise, so the API can crash with connection refused. Add a healthcheck to the database and use depends_on with condition: service_healthy. Other conditions are service_started (the default) and service_completed_successfully, useful for a one-off migrate service that must finish before the API starts.
A healthcheck has test (the command), interval, timeout, retries and start_period, a grace time during which failures do not count. For Postgres use pg_isready -U app; for Redis, redis-cli ping.
Apps should still retry their database connection on start, because the database can restart later too. restart: unless-stopped brings a crashed container back up, which is handy on a small server, but in development it can hide crashes, so watch docker compose ps for restarting.
- Compose to db: Start db1Start db
- Compose to db: Run pg_isready every 5 s2Run pg_isready every 5 s
- db to Compose: Healthy3Healthy
- Compose to migrate: Start migrate (alembic upgrade head)4Start migrate (alembic upgrade head)
- migrate to Compose: Exited with code 05Exited with code 0
- Compose to api: Start api6Start api
Development workflow: overrides, live reload and debugging
Compose automatically merges compose.override.yaml on top of compose.yaml. A common setup keeps production-like settings in compose.yaml and puts development extras in the override: a bind mount of your source code, uvicorn --reload, and published database ports for your SQL client. You can also pick files explicitly with -f compose.yaml -f compose.prod.yaml.
profiles let you mark optional services, such as an admin tool, that start only with --profile tools. docker compose watch can sync or rebuild services when files change, as an alternative to bind mounts.
For debugging: docker compose ps shows state and health, logs -f api follows one service, exec api sh opens a shell, and run --rm api pytest starts a one-off container with the same settings. After changing a Dockerfile, use up --build, because up alone reuses the old image. down -v also deletes named volumes, so use it only when you really want a fresh database.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Define app, Postgres and Redis services~45m
- 2Wire services with networks and env vars~45m
- 3Add volumes and health checks~45m
- 4Start and debug the stack with compose up~45m
Key points
- Services reach each other by service name, like db:5432, on the default network.
- Named volumes keep database data across docker compose down and up.
- depends_on with condition: service_healthy waits for the database to be ready.
- docker compose logs -f api and exec are the main debugging tools.
Key terms
Tap a card to flip it. 0/4 known
Examples
services:
api:
build: .
ports: ["8000:8000"]
environment:
DATABASE_URL: postgresql://app:dev@db:5432/app
depends_on: { db: { condition: service_healthy } }
db:
image: postgres:16
environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: dev }
volumes: ["pgdata:/var/lib/postgresql/data"]
healthcheck: { test: ["CMD", "pg_isready", "-U", "app"], interval: 5s }
cache: { image: "redis:7" }
volumes: { pgdata: {} }API, Postgres and Redis started with docker compose up.
A complete dev stack: API, Postgres, Redis and a migration step
Step 1: db has a health check and no published port. Step 2: migrate uses the API image to run Alembic once and waits for a healthy db. Step 3: api waits for migrate to finish successfully and for Redis to start. Step 4: the password comes from .env through ${DB_PASSWORD}, and Compose stops with an error if it is missing. Step 5: run docker compose up -d --build, then docker compose ps to see every service and its health.
services:
db:
image: postgres:16
environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: "${DB_PASSWORD:?set DB_PASSWORD}" }
volumes: ["pgdata:/var/lib/postgresql/data"]
healthcheck: { test: ["CMD", "pg_isready", "-U", "app"], interval: 5s, retries: 10 }
cache: { image: "redis:7" }
migrate:
build: .
command: ["alembic", "upgrade", "head"]
environment: { DATABASE_URL: "postgresql://app:${DB_PASSWORD}@db:5432/app" }
depends_on: { db: { condition: service_healthy } }
api:
build: .
ports: ["8000:8000"]
environment: { DATABASE_URL: "postgresql://app:${DB_PASSWORD}@db:5432/app", REDIS_URL: "redis://cache:6379/0" }
depends_on: { migrate: { condition: service_completed_successfully }, cache: { condition: service_started } }
volumes: { pgdata: {} }Debug an API that cannot connect to the database
The api container keeps restarting. Step 1: docker compose ps shows api restarting and db healthy. Step 2: docker compose logs api shows connection refused to localhost:5432. Step 3: docker compose config shows DATABASE_URL uses localhost, which inside the api container means the api itself. Step 4: change the host to db. Step 5: test from inside the container with exec, then recreate only the api service.
docker compose ps
docker compose logs --tail 20 api
docker compose config | grep DATABASE_URL # ...@localhost:5432 is wrong
# fix compose.yaml: postgresql://app:...@db:5432/app
docker compose up -d api # recreates only api
docker compose exec api python -c "import socket; print(socket.gethostbyname('db'))"
docker compose logs -f apiQuick reference
- docker compose up -d --build rebuilds images and starts everything in the background
- docker compose config prints the merged file with all ${VARS} filled in
- docker compose run --rm api pytest runs a one-off command with the service's settings
- Services talk on container ports (db:5432); ports: is only for access from the host
- depends_on condition: service_healthy waits for the health check, not just the start
- compose.override.yaml is merged automatically; use it for dev-only bind mounts and --reload
- docker compose down keeps volumes; down -v deletes them and your database data
- .env fills variables in compose.yaml; env_file loads variables into a container
Common mistakes
- Using localhost to reach the database from the api container; use the service name.
- Running docker compose down -v and wiping the database volume by accident.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a compose.yaml with Redis only, start it, and ping it from inside the container.
- Exercise 2medium
Add a health check to a Postgres service and make a second service wait for it. Show the health status in docker compose ps.
- Exercise 3hard
Create a compose.override.yaml that, in development only, bind mounts your code, runs uvicorn with --reload and publishes Postgres on 5432.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between docker-compose and docker compose?
- docker-compose was the original standalone Python tool (v1), now retired. docker compose is Compose v2, a Docker CLI plugin, and it is the one to use.
- Should my file be named docker-compose.yml or compose.yaml?
- compose.yaml is the preferred name today, but Compose still finds docker-compose.yml and docker-compose.yaml.
- Can I use Docker Compose in production?
- For a single server with a small app, yes, many teams do. For many servers, rolling updates and self-healing across machines, use an orchestrator such as Kubernetes or ECS.
- How do I reset my database in Compose?
- Run docker compose down -v to delete the named volumes, then docker compose up. This deletes all data in those volumes, so be sure first.