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
- Start with
version: "3.9"or higher. - Define each service under the
serviceskey. - Specify
imageorbuildfor the container source. - Map ports, volumes, and environment variables.
- 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_onto control startup order, but note it does not wait for readiness. - Use
.envfiles to keep secrets out of the Compose file. - Split overrides into
docker-compose.override.ymlfor local development.
Common issues
- YAML indentation errors are the most common cause of parse failures.
buildandimagecan be combined; Compose tags the built image with the specified name.- Environment variables in the shell override values defined in the Compose file.