Getting Started with Docker Compose

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 /code inside 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 -d flag to run containers in detached mode, similar to docker run -d
  • 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 --volumes flag to also remove named volumes

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-file option to specify a different location
  • Reference environment files using the env_file attribute 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:

  1. Command-line flag (-e option)
  2. Shell environment variables
  3. environment attribute in compose file
  4. --env-file command-line option
  5. env_file attribute in compose file
  6. .env file in the same directory as compose file
  7. ENV instructions in Dockerfile

Tags: docker docker-compose containerization YAML Flask

Posted on Sun, 07 Jun 2026 16:38:10 +0000 by aquaslayer