How to write a docker-compose.yml file?

· Category: Docker

Short answer

A docker-compose.yml file defines services, networks, and volumes using YAML syntax. Essential keys include version, services, image or build, ports, volumes, and environment.

Steps

  1. Start with version: "3.9" or higher.
  2. Define each service under the services key.
  3. Specify image or build for the container source.
  4. Map ports, volumes, and environment variables.
  5. Define named volumes and networks if needed.

Example

version: "3.9"
services:
  app:
    build:
      context: ./app
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
    volumes:
      - appdata:/app/data
    depends_on:
      - db
  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: secret
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  appdata:
  pgdata:

Tips

  • Use depends_on to control startup order, but note it does not wait for readiness.
  • Use .env files to keep secrets out of the Compose file.
  • Split overrides into docker-compose.override.yml for local development.

Common issues

  • YAML indentation errors are the most common cause of parse failures.
  • build and image can be combined; Compose tags the built image with the specified name.
  • Environment variables in the shell override values defined in the Compose file.