Docker Tutorial

24. Docker Compose | Manage Multi-Container Applications

Docker – Compose

Docker Compose is a tool for defining and managing multi-container Docker applications. Using a single docker-compose.yml file, you can configure services, networks, and volumes for your application stack.

Why Use Docker Compose?

  • Simplifies multi-container management.
  • Defines container configuration in a single file.
  • Supports networking and volume configuration automatically.
  • Easy to start, stop, and scale services.
  • Improves reproducibility and collaboration.

Basic Docker Compose Example


version: '3'
services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword

Running Docker Compose


# Start all services
docker-compose up -d

# Stop all services
docker-compose down

# View logs for services
docker-compose logs

# Scale a service
docker-compose up -d --scale web=3

Using Volumes and Networks

Docker Compose allows you to define volumes for persistent data and networks for service communication:


version: '3'
services:
  web:
    image: nginx
    ports:
      - "8080:80"
    volumes:
      - web-data:/usr/share/nginx/html
    networks:
      - webnet
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
    volumes:
      - db-data:/var/lib/mysql
    networks:
      - webnet

volumes:
  web-data:
  db-data:

networks:
  webnet:

Best Practices for Docker Compose

  • Use version 3 or above for better features and compatibility.
  • Keep services isolated using custom networks.
  • Use named volumes for persistent data.
  • Keep docker-compose.yml organized and documented.
  • Use environment variables for configuration settings.

Conclusion

Docker Compose simplifies the orchestration of multi-container applications. By defining services, networks, and volumes in a single file, you can easily deploy, scale, and manage complex Docker applications efficiently.

Leave a Reply

Your email address will not be published. Required fields are marked *