Overview of Docker Compose
Docker Compose is an orchestration tool provided by Docker for managing multi-container applications. It uses a YAML file to define services, networks, and volumes, allowing developers to launch and manage complex environments with a single command. This is especially useful in development, testing, and staging environments.
Step 1: Create a Dockerfile
Begin by defining a Docker image using a Dockerfile in your application's root directory. Below is an example of a Dockerfile for a Python application:
# Use a lightweight Python image
FROM python:3.9-alpine
# Set the working directory inside the container
WORKDIR /opt/app
# Copy local files into the container
COPY . .
# Install dependencies from requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Expose port 5000 for the application
EXPOSE 5000
# Set an environment variable
ENV GREETING Hello
# Start the application
CMD ["python", "main.py"]
Step 2: Define Services in docker-compose.yml
Create a docker-compose.yml file in the root directory to define your services. Here's an example:
version: '3.8'
services:
app:
build: .
ports:
- "5000:5000"
volumes:
- .:/opt/app
environment:
- GREETING=Hi
cache:
image: redis:latest
ports:
- "6379"
In this configuration, two services are defined: app and cache. The app service is built from the Dockerfile in the current directory, and it maps port 5000. The cache service uses the official Redis image.
Step 3: Launch and Manage Services
Run the following command in the directory containing the docker-compose.yml file to start all services:
docker-compose up
To run in detached mode, add the -d flag:
docker-compose up -d
If you make changes to your configuration or application, rebuild the images using:
docker-compose up --build
Step 4: Control Service Lifecycle
Use the following commands to manage running services:
- Stop services:
docker-compose stop - Stop and remove containers:
docker-compose down - View logs:
docker-compose logs - List running services:
docker-compose ps
Step 5: Scale Services
You can scale a service to run multiple instances using the --scale option. For example, to start three instances of the app service:
docker-compose up --scale app=3
Debugging and Log Inspection
To inspect logs for a specific service:
docker-compose logs app
Replace app with the name of any service defined in your YAML file, such as cache.