Skip to Content
DockerDocker Compose Overview

Docker Compose Overview

Docker compose files are used to define and run multi-container applications in one configuration file.
The standard name for this file is docker-compose.yml.

Here is an example of a docker-compose.yml file with the official Hello World image:

docker-compose.yml
version: '3.8' services: hello-world: image: hello-world container_name: hello-world restart: unless-stopped

Overview

version: '3.9' # General Docker Compose Example # Project or stack name name: MyProject services: # Web server service (e.g., NGINX) web: image: nginx:latest # Use latest official NGINX image container_name: web-server # Custom container name restart: always # Always restart container on failure ports: - "8080:80" # Map host port 8080 to container port 80 volumes: - ./nginx/conf:/etc/nginx/conf.d:ro # Mount local config folder as read-only networks: - my-network # Attach to custom network # Backend API service (Node.js example) api: build: context: ./api # Directory with Dockerfile dockerfile: Dockerfile container_name: api-service # Custom container name working_dir: /app # Set working directory command: node server.js # Command to start the service restart: always expose: - 3000 # Expose internal port to other containers volumes: - ./api:/app # Mount local code for live updates networks: - my-network # depends_on: # - db # Optional dependency on database, db has to be running first to start the service # Database service (e.g., PostgreSQL) db: image: postgres:15 # Official PostgreSQL image container_name: postgres-db restart: always environment: POSTGRES_USER: user POSTGRES_PASSWORD: password POSTGRES_DB: mydb ports: - "5432:5432" volumes: - db-data:/var/lib/postgresql/data networks: - my-network # Define custom network networks: my-network: # Define named volumes volumes: db-data:

Start commands

Start all services defined in docker-compose.yml

Terminal
docker-compose up -d

Stop commands

Stop all running services

Terminal
docker-compose stop

Stop and remove all containers, networks, and volumes defined in the Compose file

Terminal
docker-compose down

Rebuild images and restart all services

Terminal
docker-compose up -d --build

Log commands

View logs for all services

Terminal
docker-compose logs -f

View logs for a specific service

Terminal
docker-compose logs -f api

Restart a specific service

Terminal
docker-compose restart api

Include a .env file

Sometimes you may want to include a .env file in your project to store secrets like in the db-service.
This can be done by adding a .env file to the root directory of your project.

To start the docker-compose.yml with your .env file use this command:

Terminal
docker compose --env-file .env up -d