TExcelTAD
Home › Docker Compose › A Development Workflow

A Development Workflow

The previous lessons gave you the pieces: override files, profiles, watch, healthchecks. This lesson puts them together into a day-to-day workflow for a team: one command to get a working environment, fast feedback while coding, one-off tasks without installing anything locally, and a debugger that attaches to code running in a container.

The example app is a Python API with PostgreSQL and Redis, but the shape works for any stack.

Goals

  1. git clone + one command gives a new team member a running app with sample data.
  2. Edit → see the result in about a second, without rebuilds.
  3. No local toolchain needed: tests, migrations, linters, shells all run in containers.
  4. The same base file is used in CI and production; dev-only settings live elsewhere.

The files

text
compose.yaml            what every environment shares
compose.override.yaml   development: watch, debug port, verbose logs, dev tools (loaded automatically)
.env.example            documented defaults; copied to .env (git-ignored) on first setup
Makefile                short names for the common commands

The base file defines the services, healthchecks and dependencies. The override adds the development layer. Here is what a developer gets when they run plain docker compose up:

compose · try it yourself
# $ docker compose config --services
# $ docker compose config --no-path-resolution
services:
  api:
    build:
      context: .
      target: runtime
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD:?set DB_PASSWORD in .env}@db:5432/app
      REDIS_URL: redis://redis:6379/0
    depends_on:
      db: {condition: service_healthy}
      redis: {condition: service_started}
  db:
    image: postgres:17
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 2s
      retries: 15
    volumes: [pgdata:/var/lib/postgresql/data]
  redis:
    image: redis:8
volumes:
  pgdata:

# --- compose.override.yaml
services:
  api:
    build:
      target: dev
    command: ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "-m", "flask", "run", "--debug", "--host", "0.0.0.0"]
    ports:
      - "127.0.0.1:5000:5000"
      - "127.0.0.1:5678:5678"
    environment:
      LOG_LEVEL: debug
    develop:
      watch:
        - {action: sync, path: ./src, target: /app/src}
        - {action: rebuild, path: ./requirements.txt}
  db:
    ports: ["127.0.0.1:5432:5432"]
  adminer:
    image: adminer:5
    profiles: [tools]
    ports: ["127.0.0.1:8080:8080"]

# --- .env
DB_PASSWORD=dev-only-password
$ docker compose config --services
api
db
redis
$ docker compose config --no-path-resolution
name: demo
services:
  api:
    develop:
      watch:
        - path: ./src
          action: sync
          target: /app/src
        - path: ./requirements.txt
          action: rebuild
    command:
      - python
      - -m
      - debugpy
      - --listen
      - 0.0.0.0:5678
      - -m
      - flask
      - run
      - --debug
      - --host
      - 0.0.0.0
    environment:
      DATABASE_URL: postgres://app:dev-only-password@db:5432/app
      LOG_LEVEL: debug
      REDIS_URL: redis://redis:6379/0
    networks:
      default: null
    build:
      context: .
      dockerfile: Dockerfile
      target: dev
    depends_on:
      db:
        condition: service_healthy
        required: true
      redis:
        condition: service_started
        required: true
    ports:
      - mode: ingress
        host_ip: 127.0.0.1
        target: 5000
        published: "5000"
        protocol: tcp
      - mode: ingress
        host_ip: 127.0.0.1
        target: 5678
        published: "5678"
        protocol: tcp
  db:
    environment:
      POSTGRES_PASSWORD: dev-only-password
      POSTGRES_USER: app
    image: postgres:17
    networks:
      default: null
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
        volume: {}
    healthcheck:
      test:
        - CMD-SHELL
        - pg_isready -U app
      interval: 2s
      retries: 15
    ports:
      - mode: ingress
        host_ip: 127.0.0.1
        target: 5432
        published: "5432"
        protocol: tcp
  redis:
    image: redis:8
    networks:
      default: null
networks:
  default:
    name: demo_default
volumes:
  pgdata:
    name: demo_pgdata

Points worth copying:

  • build.target switches the multi-stage Dockerfile to a dev stage (with debugpy, test tools) in development and runtime elsewhere. See Building Images.
  • 127.0.0.1: on every published port. The dev database with a trivial password isn't reachable from the café Wi-Fi.
  • ${DB_PASSWORD:?…} fails with a clear message if someone forgets to create .env, instead of starting Postgres with an empty password.
  • adminer behind a profile: there when you want it (docker compose --profile tools up -d), absent otherwise.

First-time setup

Without .env, the required variable stops everything before a single container is created:

compose · try it yourself
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env (cp .env.example .env)}
error while interpolating services.db.environment.POSTGRES_PASSWORD: required variable DB_PASSWORD is missing a value: set DB_PASSWORD in .env (cp .env.example .env)

That message is the onboarding documentation. A typical make setup target copies the example file and starts the stack:

make
setup:            ## first run: create .env, build, start, migrate, seed
	test -f .env || cp .env.example .env
	docker compose up -d --build --wait
	docker compose run --rm api flask db upgrade
	docker compose run --rm api flask seed

up --wait returns only when every service is running and healthy (or fails with a non-zero exit code), which makes scripts like this reliable.

The inner loop

bash
$ docker compose up --watch        # terminal 1: everything running, file changes synced
$ docker compose logs -f api       # terminal 2 (optional): just the API's logs

Save src/routes.py: watch syncs the file, Flask's reloader restarts the worker, the next request uses the new code. Edit requirements.txt: watch rebuilds the image and recreates api. No manual docker compose build.

One-off commands: run vs exec

Task Command Why
shell in the running API docker compose exec api bash joins the existing container
database console docker compose exec db psql -U app same
run the tests docker compose run --rm api pytest -q fresh container, same image/env/networks, removed after
migrations docker compose run --rm api flask db upgrade doesn't disturb the running server
a quick Python REPL with the app's deps docker compose run --rm --no-deps api python --no-deps: don't start db/redis
reset all data docker compose down -v && make setup deletes the volumes

run honours depends_on (it starts db first if needed), so tests can rely on the database being there. A small model of what run --rm vs exec touch:

python · try it yourself
running = {"api": "demo-api-1", "db": "demo-db-1"}
deps = {"api": ["db", "redis"], "db": [], "redis": []}

def exec_(service, cmd):
    if service not in running:
        return f"exec {service}: error, service \"{service}\" is not running"
    return f"exec {service}: runs `{cmd}` inside {running[service]} (no new container)"

def run(service, cmd, no_deps=False):
    steps = []
    if not no_deps:
        for d in deps[service]:
            steps.append(f"start {d}" if d not in running else f"{d} already running")
    steps.append(f"create demo-{service}-run-1a2b3c, run `{cmd}`, remove it (--rm)")
    return f"run {service}: " + "; ".join(steps)

print(exec_("api", "bash"))
print(exec_("redis", "redis-cli"))
print(run("api", "pytest -q"))
print(run("api", "python", no_deps=True))
exec api: runs `bash` inside demo-api-1 (no new container)
exec redis: error, service "redis" is not running
run api: db already running; start redis; create demo-api-run-1a2b3c, run `pytest -q`, remove it (--rm)
run api: create demo-api-run-1a2b3c, run `python`, remove it (--rm)

Debugging inside the container

The override starts the API under debugpy, listening on port 5678 (published only to localhost). In VS Code, an "attach" configuration connects to it and maps the container path back to your workspace:

json
{
  "name": "Attach to api (Compose)",
  "type": "debugpy",
  "request": "attach",
  "connect": { "host": "localhost", "port": 5678 },
  "pathMappings": [{ "localRoot": "${workspaceFolder}/src", "remoteRoot": "/app/src" }]
}

Breakpoints, stepping and variable inspection then work as if the code ran locally. Node (--inspect=0.0.0.0:9229), Java (-agentlib:jdwp=…address=*:5005) and Go (dlv --listen=:2345) follow the same pattern: a debug port in the override, a path mapping in the IDE.

Keeping it fast

python · try it yourself
# rough timings for one change, in seconds
steps = {
    "rebuild image + recreate":      {"build": 35, "start": 4, "reload": 0},
    "bind mount + reloader":         {"build": 0,  "start": 0, "reload": 1.5},
    "watch sync + reloader":         {"build": 0,  "start": 0, "reload": 1.0},
    "watch rebuild (deps changed)":  {"build": 12, "start": 3, "reload": 0},
}
for name, s in steps.items():
    total = sum(s.values())
    print(f"{name:<30} {total:>5.1f}s  {'#' * round(total)}")
rebuild image + recreate        39.0s  #######################################
bind mount + reloader            1.5s  ##
watch sync + reloader            1.0s  #
watch rebuild (deps changed)    15.0s  ###############

The numbers are illustrative, but the shape is real: avoid rebuilds in the inner loop, and when you must rebuild, a well-ordered Dockerfile with BuildKit cache mounts keeps it short. Other speed-ups: --wait instead of sleep, healthcheck intervals of 1–2 s in development, and docker compose up -d --no-deps api to restart just one service.

Learn more: Logs & Debugging · develop & watch · Compose in CI

Test yourself

What is the difference between docker compose exec api pytest and docker compose run --rm api pytest?

  1. None
  2. exec runs in the existing api container; run creates a new one-off container from the service definition
  3. run is faster
  4. exec starts dependencies

Why publish dev ports as 127.0.0.1:5432:5432?

  1. It's faster
  2. So only the local machine can connect, not other hosts on the network
  3. Compose requires an IP
  4. To avoid DNS

What does docker compose up -d --wait do?

  1. Waits 10 seconds
  2. Returns once all services are running/healthy, or fails
  3. Waits for a key press
  4. Waits for the build cache