Youssef Samir

Get in touch

Docker compose

A practical guide to Docker Compose commands and configuration tips for managing multi-container applications.

Basic Commands

  • docker compose
    • options
      • --project-name [project name] or -p [project name]
    • build: Build the images
    • start: Start the containers
    • stop: Stop the containers
    • up: Build and start
      • -d: Detached mode
    • ps: List running Docker Compose containers
    • rm: Remove containers from memory
    • down: Stop and remove containers
    • logs: View container logs
    • exec [container name] bash: Execute a bash shell in a container
    • cp [container id]:[src path] [destination path]: Copy files from the container
    • cp [src path] [container id]:[destination path]: Copy files to the container

Example docker-compose.yml

version: '3.8'

services:
  web:
    build: ./web # Build context for the web service
    image: my-web-app:latest # Image name
    restart: always
    command: ["python", "app.py"] # Override default command
    environment:
      DATABASE_URL: postgres://user:password@db:5432/mydatabase # Database URL
      CACHE_REDIS_URL: redis://cache:6379/0 # Redis cache URL
    ports:
      - "5000:5000" # Map port 5000 of the container to port 5000 on the host
    volumes:
      - ./web/app:/app # Mount app directory for live reloading
    depends_on:
      - db
      - cache
    networks:
      - app-network

  db:
    image: postgres:13-alpine # Official PostgreSQL image
    restart: always
    environment:
      POSTGRES_DB: mydatabase # Database name
      POSTGRES_USER: user # Database user
      POSTGRES_PASSWORD: password # Database password
    volumes:
      - db-data:/var/lib/postgresql/data # Persist database data
    networks:
      - app-network

  cache:
    image: redis:6-alpine # Official Redis image
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  db-data: