Validate your docker-compose.yml files for syntax errors and best practices.
Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application's services, networks, and volumes. Then, with a single command, you create and start all the services from your configuration.
A docker-compose.yml file consists of several top-level sections:
Specifies the Compose file format version. Common versions:
version: '3.8' - Latest version 3 (recommended)version: '3.7' - Good compatibilityversion: '2.4' - Legacy applicationsversion: '3.8'
Defines the containers that make up your application. Each service can specify:
image - Docker image to usebuild - Build configurationports - Port mappings (host:container)volumes - Volume mountsenvironment - Environment variablesdepends_on - Service dependenciesservices:
web:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html
Defines named volumes that can be used by services. Volumes persist data across container restarts.
volumes:
db_data:
driver: local
Defines custom networks for service communication. By default, Compose creates a single network for your app.
networks:
frontend:
backend:
driver: bridge
services:
web:
port: "80:80" # Wrong!
services:
web:
ports: # Correct!
- "80:80"
services:
web:
volume: "./data:/data" # Wrong!
services:
web:
volumes: # Correct!
- "./data:/data"
nginx:1.21 instead of nginx:latest.env files (add to .gitignore)version: '3.8'
services:
web:
image: nginx:1.21
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./html:/usr/share/nginx/html:ro
depends_on:
- api
networks:
- frontend
api:
build: ./api
environment:
DATABASE_URL: postgres://user:pass@db:5432/mydb
depends_on:
- db
networks:
- frontend
- backend
db:
image: postgres:13
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
volumes:
- db_data:/var/lib/postgresql/data
networks:
- backend
volumes:
db_data:
networks:
frontend:
backend:
Start services:
docker-compose up -d
Stop services:
docker-compose down
View logs:
docker-compose logs -f
Rebuild and restart:
docker-compose up -d --build
Validate config:
docker-compose config
List running services:
docker-compose ps
key: value- item