Manual steps (reference)
- Create a network:
- Start Redis and Postgres:
- Build the application images locally:
- Run the application containers and publish ports:
docker ps will show no entries.
Now we’ll convert those manual steps into a Docker Compose file so the entire stack can be started with a single command.
Compose file: reference configuration
Create a Compose file (for examplesimple.yaml) in your project directory. The first version uses pre-built images (mirrors the manual docker run approach):
voteandresultneed port mappings to expose their web UIs:8080:80and8081:80.redisisredis:alpineand does not need a published port for internal service-to-service networking.- The Postgres service defines environment variables and a named volume
db-datato persist database data.
up:
- Creates a default network (project_name_default) unless you define one explicitly.
- Creates and starts containers for each service.
- If run in attached mode (default), logs for all services stream to your terminal with a service-name prefix.
- Vote app: http://localhost:8080
- Result app: http://localhost:8081
Docker Compose automatically creates a project network (derived from the directory name) if you don’t explicitly define one. You don’t need to manually create
voting-app unless you have a specific reason to reuse a pre-existing network.Build images with Compose (build from local Dockerfiles)
You don’t need to build images manually before using Compose. Replaceimage: with build: to instruct Compose to build images from local Dockerfiles. Example:
- Build the
vote,result, andworkerimages from the specified directories. - Start the entire stack once images are built.
If you add
-v to docker compose down -v, it will remove named volumes like db-data and delete persisted database data. Use with caution if you need to retain Postgres state between runs.Quick reference — services, ports, and persistence
Troubleshooting tips
- Duplicate-key DB errors: If you see Postgres duplicate-key errors, it’s usually because the database wasn’t cleaned between runs and a worker retried an insert for an ID that already exists.
- Hostname resolution: Compose services resolve each other by service name. If a service cannot reach Redis or Postgres, ensure the hostnames used in your code match the Compose service names (e.g.,
redis,db). - Follow logs for a specific service:
- Rebuild a specific service without restarting others:
Summary
Using Docker Compose:- Simplifies launching multi-container applications with a single YAML definition.
- Supports both using pre-built images (
image:) and building from local Dockerfiles (build:). - Handles networking, service orchestration, and volume management for you.
- Docker Compose documentation: https://docs.docker.com/compose/
- Docker CLI reference: https://docs.docker.com/engine/reference/commandline/cli/
- PostgreSQL Docker image docs: https://hub.docker.com/_/postgres