Table of Contents
Docker Compose
Docker Compose is a powerful tool that streamlines the process of defining and managing multi-container Docker applications. It allows you to use a YAML file to configure your application's services, networks, and volumes. With a single command, you can create and start all the services from your configuration, making it ideal for development, testing, and staging environments.
Key Features
- **Declarative Configuration:** Docker Compose uses a YAML file (`docker-compose.yml`) to define the services, networks, and volumes that make up your application. This declarative approach makes it easy to version control your application's configuration and share it with others.
- **Single Command Management:** With a single `docker-compose up` command, you can create and start all the services defined in your `docker-compose.yml` file. Similarly, `docker-compose down` stops and removes the containers.
- **Isolated Environments:** Docker Compose creates isolated environments for each application, ensuring that services don't interfere with each other.
- **Port Mapping:** Docker Compose automatically maps ports from the containers to the host machine, making your services accessible from outside the containers.
- **Volume Management:** It allows you to define and manage volumes, providing persistent storage for your application data.
Benefits
- **Simplified Multi-Container Applications:** Docker Compose makes it easy to define and manage complex applications with multiple containers.
- **Portability:** The declarative configuration file makes your application portable across different environments.
- **Reproducibility:** Docker Compose ensures that your application's environment is consistent across different machines and deployments.
- **Improved Developer Workflow:** It streamlines the development and testing process by allowing you to quickly spin up and tear down your application's environment.
Code Examples
1. **Simple Web Application with Database:**
```yaml version: '3' services:
web: build: . ports: - "5000:5000" depends_on: - db db: image: postgres:latest environment: POSTGRES_PASSWORD: mysecretpassword```
This `docker-compose.yml` file defines two services: a `web` service that builds from the current directory and exposes port 5000, and a `db` service that uses the latest PostgreSQL image.
2. **Scaling a Service:**
```bash docker-compose up -d –scale web=3 ```
This command starts the application in detached mode and scales the `web` service to 3 replicas.
3. **Viewing Logs:**
```bash docker-compose logs -f web ```
This command follows the logs of the `web` service in real-time.
Additional Resources
- **Docker Compose Official Documentation:** s://docs.docker.com/compose/(https://docs.docker.com/compose/)
- **Docker Compose GitHub Repository:** s://github.com/docker/compose(https://github.com/docker/compose)