docker compose

Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you define a multi-container application in a single file, then spin up your application with a single command. Here's a comprehensive reference for Docker Compose:

Docker Compose Basics:

1. Compose File Format:

  • Docker Compose files are written in YAML. The default file name is docker-compose.yml, but you can use a different filename with the -f option.

2. Service Definitions:

  • Each service in a Compose file is defined under the services key. A service typically corresponds to a container.

services:
  web:
    image: nginx:latest

3. Build Configuration:

  • You can specify build configurations for services, allowing you to build an image from a Dockerfile.

services:
  web:
    build:
      context: ./path/to/build-context
      dockerfile: Dockerfile.dev

4. Container Naming:

  • By default, Docker Compose generates container names based on the project name and service name. You can customize container names using the container_name field.

5. Environment Variables:

  • Use the environment key to set environment variables for a service.

6. Volumes:

  • Define volumes under the volumes key to persist data.

7. Ports:

  • Use the ports key to map ports from the container to the host.

8. Networks:

  • Create custom networks for your services.

9. Depends On:

  • Specify dependencies between services.

10. Command Override:

  • Override the default command for a service.

11. Links:

  • Define links between services. Note: The use of links is discouraged in favor of user-defined networks.

12. Logging:

  • Control logging options.

13. Scale Services:

  • Use the scale command to create multiple instances of a service.

Example Docker Compose File:

Docker Compose Commands:

1. docker-compose up:

  • Build and start services defined in the Compose file.

2. docker-compose down:

  • Stop and remove containers, networks, and volumes.

3. docker-compose build:

  • Build services defined in the Compose file.

4. docker-compose ps:

  • List running containers.

5. docker-compose logs:

  • View output from containers.

6. docker-compose exec:

  • Execute commands in a running container.

7. docker-compose config:

  • Validate and view the Compose file configuration.

8. docker-compose pause/unpause:

  • Pause or unpause services.

These are the fundamental concepts and commands for using Docker Compose. Docker Compose simplifies the management of multi-container Docker applications and is especially useful for development, testing, and staging environments.