Introduction to Docker Compose
Docker Compose is a tool designed for defining and running multi-container Docker applications. It uses YAML configuration files to specify services, making it suitable for various environments including production, staging, development, testing, and CI workflows.
Building a Simple Application
This example demonstrates a basic Python web service using Flask with Redis for caching.
Project Setup
Create a project directory and add the following files:
app.py - Main application entry point:
import time
import redis
from flask import Flask
app = Flask(__name__)
db = redis.Redis(host='redis', port=6379)
def increment_counter():
attempts = 5
while True:
try:
return db.incr('visits')
except redis.exceptions.ConnectionError as exc:
if attempts == 0:
raise exc
attempts -= 1
time.sleep(0.5)
@app.route('/')
def home():
visits = increment_counter()
return f'Hello! This page has been loaded {visits} times.\n'
requirements.txt - Python dependencies:
flask
redis
Dockerfile
Define the container image for the application:
# syntax=docker/dockerfile:1
FROM python:3.7-alpine
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN <<eof .="" add="" apk="" cmd="" copy="" eof="" expose="" gcc="" https:="" install="" linux-headers="" musl-dev="" pip="" requirements.txt="" run="" sed="" set="" workdir=""></eof>
Docker Compose Configuraton
Create a docker-compose.yml file that defines the web service and Redis container:
version: "3.9"
services:
web:
build: .
ports:
- "8000:5000"
volumes:
- .:/code
environment:
FLASK_DEBUG: "true"
redis:
image: "redis:alpine"
Configuration details:
- ports - Maps host port 8000 to container port 5000
- volumes - Mounts current directory to
/codeinside the container - environment - Sets environment variables; FLASK_DEBUG enables development mode with automatic code reloading
Start the application using docker compose up.
Docker Compose Commands
Common Commands
- docker compose up - Builds and starts services defined in the compose file
- Add
-dflag to run containers in detached mode, similar todocker run -d
- Add
- docker compose ps - Lists running services
- docker compose run - Executes a one-time command against a service
- docker compose stop - Stops running services without removing containers
- docker compose down - Stops and removes containers, networks, and volumes
- Add
--volumesflag to also remove named volumes
- Add
Run docker compose --help for a complete list of available commands.
Environment Variables
Environment File (.env)
Create a .env file in the project root (same directory as docker-compose.yml) to store environment variables:
- Place the file in the project root alongside the compose file
- Use
--env-fileoption to specify a different location - Reference environment files using the
env_fileattribute in compose files
Inline Environment Variables
Define variables directly in docker-compose.yml using the environment attribute:
web:
environment:
- DEBUG=1
Variable Substitution Syntax
Environment variables support multiple substitution formats:
- Basic:
${VARIABLE} - Default value:
${VARIABLE:-default}- uses "default" if VARIABLE is unset or empty - Required value:
${VARIABLE:?error}- exits with error if VARIABLE is unset or empty - Replacement:
${VARIABLE:+replacement}- uses "replacement" if VARIABLE is set and non-empty
Variable Resolution Order
When multiple sources define the same variable, priority from highest to lowest:
- Command-line flag (
-eoption) - Shell environment variables
environmentattribute in compose file--env-filecommand-line optionenv_fileattribute in compose file.envfile in the same directory as compose fileENVinstructions in Dockerfile