How-To Guide

Migrating docker run Flags to Compose Profiles

Convert brittle docker run shell scripts into declarative compose.yaml services with healthcheck readiness dependencies, named volumes, and profiles.

On this page

  1. Why Imperative docker run Scripts Drift
  2. Mapping docker run Flags to Compose v2 Syntax
  3. Using Profiles for Lean Defaults and On-Demand Tools
  4. Networking, Logging, and Shutdown Hygiene
  5. Migration Traps: Networking, Secrets, and Volume Ownership
  6. Validating the Converted Topology

Why Imperative docker run Scripts Drift

Every engineering team starts with a start-dev.sh script stuffed with long docker run -d --name postgres-dev -p 5432:5432 -e POSTGRES_PASSWORD=dev ... commands. Within weeks, that script turns brittle: running it a second time crashes because the container name already exists, forgetting --network app-net silently breaks inter-container DNS resolution, and teammates append custom flags locally without committing them. Worse, orchestrating startup order between databases, migrations, and auxiliary debugging dashboards in raw Bash leads to flaky sleep 5 hacks that fail randomly on slower CI runners.

Migrating to Docker Compose v2 (compose.yaml) turns ephemeral CLI flags into a single version-controlled, idempotent topology. Instead of juggling three separate docker-compose.override.yml files to toggle optional containers like pgAdmin, Mailpit, or OTEL collectors, Compose profiles let every teammate run the slim core stack by default and opt into specialized helper tools cleanly on demand.

If you have existing docker run commands sitting in READMEs or shell scripts, paste them directly into the Interactive Docker Run to Compose Converter to translate flags, ports, volumes, and environment mappings into valid compose.yaml syntax immediately.

Mapping docker run Flags to Compose v2 Syntax

Consider converting three imperative shell invocations—PostgreSQL, a Node API, and an optional pgAdmin web inspector—into one clean specification. Notice how --rm, -d, --network, -v, -e, and --restart map deterministically:

# Legacy imperative script (fragile, order-dependent)
docker network create app-net || true
docker run -d --name app-db --network app-net -p 127.0.0.1:5432:5432 \
  -e POSTGRES_USER=app -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=orders \
  -v app_pgdata:/var/lib/postgresql/data --restart unless-stopped postgres:16-alpine

docker run -d --name app-api --network app-net -p 3000:3000 \
  -e DATABASE_URL=postgres://app:secret@app-db:5432/orders \
  --restart unless-stopped myorg/orders-api:latest

docker run -d --name app-pgadmin --network app-net -p 127.0.0.1:5050:80 \
  -e [email protected] -e PGADMIN_DEFAULT_PASSWORD=admin \
  dpage/pgadmin4:8

Notice two security and reliability improvements we apply while translating to compose.yaml: binding database and admin ports strictly to 127.0.0.1 so local laptops on public Wi-Fi never expose dev databases externally, and gating the API startup on PostgreSQL passing pg_isready:

services:
  db:
    image: postgres:16-alpine
    restart: unless-stopped
    ports:
      - "127.0.0.1:5432:5432"
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-app}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-secret}
      POSTGRES_DB: ${POSTGRES_DB:-orders}
    volumes:
      - app_pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-app} -d $${POSTGRES_DB:-orders}"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 10s

  migrate:
    image: myorg/orders-api:latest
    command: ["npm", "run", "db:migrate"]
    environment:
      DATABASE_URL: postgres://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-secret}@db:5432/${POSTGRES_DB:-orders}
    depends_on:
      db:
        condition: service_healthy
    profiles: ["migrate", "full"]

  api:
    image: myorg/orders-api:latest
    restart: unless-stopped
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-secret}@db:5432/${POSTGRES_DB:-orders}
    depends_on:
      db:
        condition: service_healthy

  pgadmin:
    image: dpage/pgadmin4:8
    ports:
      - "127.0.0.1:5050:80"
    environment:
      PGADMIN_DEFAULT_EMAIL: [email protected]
      PGADMIN_DEFAULT_PASSWORD: admin
    depends_on:
      db:
        condition: service_healthy
    profiles: ["debug", "full"]

volumes:
  app_pgdata:

Look closely at $${POSTGRES_USER:-app} inside the healthcheck.test string. Compose performs ${VAR} substitution across the entire YAML file before sending commands to the container. Escaping with $$ passes literal $POSTGRES_USER into the container’s /bin/sh, whereas single $ would expand using the host shell’s .env file instead.

Using Profiles for Lean Defaults and On-Demand Tools

Compose services without a profiles key always start on docker compose up. Services declaring profiles: ["debug"] remain dormant until requested explicitly, giving every engineer fast default startup times while keeping optional tools discoverable inside the same repository file:

# Default stack: launches only db + api
docker compose up -d

# Spin up pgAdmin alongside core services for database inspection
docker compose --profile debug up -d

# Run one-off schema migration cleanly after db passes healthcheck
docker compose run --rm migrate

Notice also why migrate belongs in a profile rather than always running during docker compose up: running schema migrations as an always-on service triggers restarts when restart: unless-stopped is active, or leaves exited containers cluttering docker compose ps. Placing one-shot tasks in a migrate profile and executing them via docker compose run --rm migrate keeps lifecycle semantics crystal clear.

Beyond database consoles and migrations, profiles organize three additional local workflows cleanly without inflating baseline RAM usage on developer laptops:

  • Synthetic observability stacks (observability): Keep Prometheus, Grafana, and OpenTelemetry Collector containers tucked under profiles: ["observability"] so everyday feature work consumes minimal CPU while trace debugging remains one CLI flag away.
  • Seed data generators (seed): Run deterministic fixture loaders on demand against fresh local volumes without accidentally wiping or re-seeding an engineer’s existing local workspace on every docker compose up.
  • Integration test runners (ci): Package Playwright or Pact verification runners inside a ci profile sharing the exact internal Compose DNS network (http://api:3000) used by production-like containers, guaranteeing identical test execution locally and on CI runners.

Networking, Logging, and Shutdown Hygiene

Converting flags is only half of migration; you also want deterministic container shutdowns and bounded host disk usage. Under raw docker run, default json-file logging has zero size rotation, allowing a runaway crash loop to fill /var/lib/docker silently. In compose.yaml, attach a YAML anchor (x-logging) setting max-size: "10m" and max-file: "3" across services. Similarly, confirm Node.js and Python entrypoints use exec form (command: ["node", "dist/server.js"]) rather than shell-string form so Docker delivers SIGTERM straight to your server instead of hanging for 10 seconds until SIGKILL.

Migration Traps: Networking, Secrets, and Volume Ownership

Watch out for five common pitfalls when moving legacy docker run setups to Compose:

  • Hardcoded container_name breaking scaling and parallel runs: Setting container_name: app-db prevents running docker compose up --scale worker=3 or spinning up two isolated Git worktrees side by side. Let Compose generate project-scoped names and communicate via the logical service name (db) on Compose’s automatic default bridge network.
  • Exposing 0.0.0.0:5432 unintentionally: Writing "5432:5432" binds all host network interfaces (0.0.0.0), bypassing ufw iptables input rules on Linux because Docker writes directly to DOCKER-USER NAT chains! Always prefix local-only dev ports with 127.0.0.1:.
  • Committing plain production passwords inside compose.yaml: Use .env (gitignored) or Compose secrets: mounted under /run/secrets/ rather than committing credentials in plain environment: blocks.
  • Unquoted numeric values or booleans in environment: Writing PORT: 3000 or DEBUG: true without quotes in YAML dictionary syntax can cause parsers or strict tools to misinterpret types unless quoted or verified via docker compose config.
  • Bind-mounting node_modules from macOS/Linux hosts: Mounting ./:/app overwrites container-compiled native binaries (bcrypt, sharp, esbuild) unless you add an anonymous volume - /app/node_modules (or better yet, build cleanly inside Compose Watch develop.watch).

Validating the Converted Topology

After translating your flags with the Interactive Docker Run to Compose Converter and adding healthchecks and profiles, verify three properties before committing:

  1. Run docker compose config to inspect the resolved YAML, verify ${VAR} defaults and $$ escapes expanded accurately, and confirm zero schema deprecation warnings appear.
  2. Run docker compose down -v && docker compose up -d from a completely cold volume state to prove service_healthy blocks api cleanly until PostgreSQL accepts connections without retry-crash loops.
  3. Run docker compose --profile debug config --services to verify default vs profiled service lists match your onboarding documentation.

FAQ

Do I still need version: '3.8' at the top of compose.yaml?
No. Modern Docker Compose (v2 Compose Specification) deprecated the top-level version field and emits warnings when present. Omit version completely unless supporting legacy v1 tools.
Why does depends_on without condition: service_healthy still cause connection refused errors?
Plain depends_on only waits until the container process starts, not until PostgreSQL finishes recovery or binds port 5432. Pairing healthcheck with condition: service_healthy blocks dependent services until probes succeed.
How do Compose profiles differ from separate override YAML files?
Profiles live inside a single compose.yaml file so optional services like Adminer, Mailpit, or database seeders stay inactive by default and launch cleanly with --profile debug when needed.

Related Examples

Interactive Tools for This Topic