| |

Docker 44 🐳 Docker Compose Profiles, Overrides (docker-compose.override.yml), and Inheritance

⏱️ Estimated read: 16 min | |

The Compose file is not a single static document. It is a base configuration, and it can be layered with override files, scoped with profiles, and merged into a final model that Compose resolves before starting any container. This layering is what allows a single repository to serve development, testing, and production without duplicating the service definitions. The base file contains the common configuration, the override files contain the environment-specific differences, and the profiles control which services are active.

The profile mechanism controls which services are active. A service with no profiles attribute is always enabled. A service with a profiles attribute is only enabled when the profile is activated, either with the --profile flag or the COMPOSE_PROFILES environment variable . This is the mechanism for optional services: a database admin tool, a debugging sidecar, or a monitoring stack that should not start by default. The profile does not change the service’s configuration; it only controls whether the service is included in the model .

The override mechanism controls the configuration of the services that are active. By default, Compose reads compose.yaml and, if it exists, compose.override.yaml. The override file is merged on top of the base, and the merge rules determine what happens when a key appears in both files . Single-value keys like image or command are replaced by the override. Multi-value keys like ports and volumes are appended. Mapping keys like environment are merged, with the override’s value winning for a given key . The !reset and !override tags give explicit control when the default merge rules are not what is wanted .

This chapter covers three areas. First, why profiles and overrides exist — the environment-difference problem and the layered-model solution. Second, how profiles work — the profiles attribute, the activation methods, the dependency rules, and the auto-start behavior for explicitly targeted services. Third, how overrides and multiple files work — the automatic compose.override.yaml, the explicit -f flags, the merge rules for different data types, and the !reset and !override tags. The chapter ends with a complete example session, a quick reference, best practices, common pitfalls, real-world examples, and diagrams showing the layering and the merge rules.

Key point: Profiles control which services are active; overrides control the configuration of the active services. A service with a profiles attribute starts only when its profile is enabled, unless it is explicitly targeted. The compose.override.yaml file is merged automatically; additional files are merged with -f flags in order. The merge rules differ by data type: scalars are replaced, lists are appended, and mappings are merged.


Why profiles and overrides exist

The environment-difference problem. A service that runs in development and production has different requirements. In development, the source code is bind-mounted for hot reload, the debugger port is exposed, and the build context is used instead of a published image. In production, the image is fixed, the ports are closed, and the restart policy is unless-stopped. Putting both configurations in one file with conditional environment variables is unmaintainable. The override mechanism separates the common configuration from the environment-specific differences.

The optional-service problem. Not every service is needed in every environment. A database admin tool like Adminer or pgAdmin is useful in development but should not run in production. A monitoring stack is useful in staging but not in a local test. A seed script runs once and exits. The profile mechanism makes these services optional: they are defined in the file, but they start only when their profile is enabled. The core services are always enabled, and the optional services are activated on demand.

The layering problem. The Compose model is built by layering files. The base file is the first layer, and each override file is a subsequent layer. The layers are merged in order, and the result is the final model. The layering is what allows a single repository to define a stack that works in multiple environments: the base file is committed, the override files are environment-specific, and the profiles select the optional services.

The merge-rule problem. The merge rules are the source of most confusion with override files. A developer expects a ports list in the override to replace the base list, but the rule is to append. The result is that both sets of ports are exposed, which is often not the intent. The !reset and !override tags are the escape hatch: !reset removes the inherited value, and !override replaces the list entirely . Understanding the rules and the tags is the difference between a merged model that works and one that has unexpected ports and volumes.

The path-resolution problem. When multiple files are merged, the relative paths are resolved from the base file, not the override file. This is a deliberate decision: the override file need not be a valid Compose file, and it can contain only fragments. Tracking which path is relative to which file is difficult, so the specification resolves all paths from the base file . The --project-directory flag can override the base path, and docker compose config shows the resolved model.

The trade-off. The layering adds complexity. A developer must know which files are merged, what the merge rules are, and which profiles are active. The docker compose config command shows the resolved model, and it is the tool for verifying the result. The alternative — a single file per environment — duplicates the common configuration and creates the maintenance problem that the layering is designed to solve. The trade-off is between the complexity of the layering and the duplication of the alternatives.


a. Profiles

A profile is a named group of services. A service is assigned to one or more profiles with the profiles attribute. The attribute takes an array of profile names, and the names must match the format [a-zA-Z0-9][a-zA-Z0-9_.-]+ .

services:
  db:
    image: postgres:16-alpine

  backend:
    image: myapi

  frontend:
    image: myfrontend
    profiles: [frontend]

  phpmyadmin:
    image: phpmyadmin
    depends_on: [db]
    profiles: [debug]

The db and backend services have no profiles attribute, so they are always enabled. The frontend service is assigned to the frontend profile, and the phpmyadmin service is assigned to the debug profile. A docker compose up starts only db and backend. A docker compose --profile debug up starts db, backend, and phpmyadmin .

Activation. A profile is activated with the --profile flag or the COMPOSE_PROFILES environment variable. Multiple profiles can be activated at once, either with multiple --profile flags or a comma-separated list in COMPOSE_PROFILES. The --profile "*" form activates all profiles .

docker compose --profile debug up
docker compose --profile frontend --profile debug up
COMPOSE_PROFILES=frontend,debug docker compose up
docker compose --profile "*" up

Dependency resolution. A service that is explicitly targeted on the command line is started even if its profile is not active. The service’s profile is added to the active set automatically. Its dependencies are also started, but a dependency that is gated behind a different profile must be in the same profile, started separately, or always enabled. Otherwise, Compose reports an error .

services:
  backend:
    image: myapi
    depends_on:
      - db
    profiles: [tools]

  db:
    image: postgres:16-alpine

The backend service is in the tools profile, and it depends on db. The db service has no profile, so it is always enabled. A docker compose run backend starts the backend service (its profile is auto-enabled) and the db service (its dependency) . If the db service were also in the tools profile, the dependency would be satisfied. If it were in a different profile, the model would be invalid.

The core-service rule. The core services of the application should not be assigned to profiles. They should be always enabled, so that a docker compose up starts the application without any flags. The profiles are for optional tools: a debugger, a database admin, a seed script, a monitoring stack .


b. Overrides and multiple files

The override mechanism layers files on top of the base file. By default, Compose reads compose.yaml and, if it exists, compose.override.yaml. The override file is merged automatically, with no flags required .

# compose.yaml (base)
services:
  web:
    image: myapp:latest
    environment:
      APP_ENV: production
    ports:
      - "8080:80"
    restart: unless-stopped
# compose.override.yaml (development)
services:
  web:
    build: .
    volumes:
      - .:/app
    environment:
      APP_ENV: development
      DEBUG: "true"
    ports:
      - "5678:5678"
    restart: "no"

The merged model has the build key from the override (which takes precedence over the image key), the volumes from the override (appended to the base’s volumes, which are none), the environment merged with APP_ENV set to development and DEBUG added, the ports appended (8080:80 and 5678:5678), and the restart replaced with no .

Explicit files with -f. When the override file has a different name or when multiple files are needed, the -f flag specifies the files. The files are merged in the order they appear on the command line, with later files overriding earlier ones .

docker compose -f compose.yaml -f compose.prod.yaml up -d
docker compose -f compose.yaml -f compose.staging.yaml -f compose.monitoring.yaml up -d

The merge rules. The rules differ by data type :

Data typeMerge behaviorExample
Scalars (image, command, mem_limit)The override replaces the baseimage: a → image: b
Sequences (ports, expose, dns)The override appends to the base["80:80"] → ["80:80", "443:443"]
Mappings (environment, labels)Merged; the override’s value wins for a given keyFOO=original + BAR=local → both
Unique sequences (volumes, secrets, configs)Merged by unique key (the target)./original:/foo + ./local:/bar → both

Shell commands. The command, entrypoint, and healthcheck:test attributes are exceptions: they are overridden by the latest file, not appended .

The !reset and !override tags. The !reset tag removes an inherited value, and the !override tag replaces a list entirely, bypassing the append rule .

# compose.override.yaml
services:
  web:
    ports: !reset []
    environment: !override
      - APP_ENV=development

The !reset [] removes the base’s ports, and the !override replaces the base’s environment entirely, rather than merging it.

Path resolution. All relative paths in the merged model are resolved from the base file (the first file specified with -f). The override file’s paths are not the base for resolution. The --project-directory flag overrides the base path .


Complete Example Session

# ============================================
# PART 1: THE BASE FILE
# ============================================

# compose.yaml
name: myapp

services:
  web:
    image: myapp:latest
    ports:
      - "8080:80"
    environment:
      APP_ENV: production
      LOG_LEVEL: info
    restart: unless-stopped
    networks:
      - frontend

  api:
    image: myapi:latest
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb
    depends_on:
      db:
        condition: service_healthy
    networks:
      - frontend
      - backend

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD:?required}
      POSTGRES_DB: appdb
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
      retries: 5
      start_period: 10s
    networks:
      - backend

networks:
  frontend:
  backend:
    internal: true

volumes:
  db-data:
# ============================================
# PART 2: THE OVERRIDE FILE
# ============================================

# compose.override.yaml (development)
services:
  web:
    build: .
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - "5678:5678"
    environment:
      APP_ENV: development
      DEBUG: "true"
    restart: "no"

  db:
    ports:
      - "5432:5432"
# ============================================
# PART 3: THE PRODUCTION FILE
# ============================================

# compose.prod.yaml
services:
  web:
    image: ghcr.io/org/myapp:${TAG:?required}
    ports: !override
      - "443:443"
    restart: always
    deploy:
      resources:
        limits:
          memory: 512M
# ============================================
# PART 4: THE PROFILES
# ============================================

# compose.yaml (profiles section)
services:
  # ... base services ...

  adminer:
    image: adminer
    depends_on:
      - db
    profiles: [tools]
    networks:
      - backend

  seed:
    image: myapi:latest
    command: ["npm", "run", "seed"]
    depends_on:
      db:
        condition: service_healthy
    profiles: [seed]
    networks:
      - backend
# ============================================
# PART 5: THE DEVELOPMENT WORKFLOW
# ============================================

# Development: base + override + adminer
docker compose --profile tools up -d

# The merged model:
#   web: build from ., source mounted, debug port, APP_ENV=development
#   api: from base
#   db: from base, port 5432 exposed
#   adminer: from the tools profile
# ============================================
# PART 6: THE PRODUCTION WORKFLOW
# ============================================

# Production: base + prod, no override
docker compose -f compose.yaml -f compose.prod.yaml up -d

# The merged model:
#   web: image from ghcr.io, port 443, restart always, memory limit
#   api: from base
#   db: from base
#   No adminer, no seed
# ============================================
# PART 7: THE SEED WORKFLOW
# ============================================

# Run the seed service explicitly
docker compose run --rm seed

# The seed profile is auto-enabled.
# The db service is pulled in as a dependency.
# The seed container runs and exits.
# ============================================
# PART 8: VERIFYING THE MERGED MODEL
# ============================================

# Show the merged configuration
docker compose -f compose.yaml -f compose.prod.yaml config

# The output shows the resolved model:
#   web:
#     image: ghcr.io/org/myapp:1.2.3
#     ports: ["443:443"]
#     restart: always
#     memory: 512M
# ============================================
# PART 9: THE COMPLETE FILE STRUCTURE
# ============================================

# myapp/
# ├── compose.yaml              (base, committed)
# ├── compose.override.yaml     (dev, gitignored)
# ├── compose.prod.yaml         (prod, committed)
# ├── .env                      (secrets, gitignored)
# └── .env.example              (template, committed)
# ============================================
# PART 10: THE ENV FILE
# ============================================

# .env
DB_PASSWORD=secretpassword
TAG=1.2.3

The ten parts show the base file, the override file, the production file, the profiles, the development workflow, the production workflow, the seed workflow, verifying the merged model, the file structure, and the .env file.


Quick Reference

Profiles

ConceptBehavior
No profiles attributeAlways enabled
profiles: [name]Enabled when the profile is active
--profile nameActivate a profile
COMPOSE_PROFILES=nameActivate via environment
--profile "*"Activate all profiles
Explicitly targeted serviceProfile auto-enabled
Dependency in a different profileError unless explicitly enabled

Multiple Files

CommandEffect
No -fReads compose.yaml + compose.override.yaml
-f a.yaml -f b.yamlMerges a then b
COMPOSE_FILESets the file list
--project-directoryOverrides the base path
docker compose configShows the merged model

Merge Rules

Data typeBehavior
ScalarsReplaced
Sequences (ports, dns)Appended
Mappings (environment, labels)Merged; override wins
Unique sequences (volumes, secrets)Merged by target
command, entrypoint, healthcheck:testReplaced

Merge Tags

TagEffect
!resetRemoves the inherited value
!overrideReplaces the list entirely

Best Practices

✅ Do This:

# Keep core services unprofiled
backend:
  image: myapi
  # no profiles                                                    # ✅
# Use profiles for optional tools
adminer:
  profiles: [tools]                                                # ✅
# Use compose.override.yaml for local development
# gitignore the override file                                     # ✅
# Use -f for production with an explicit file
docker compose -f compose.yaml -f compose.prod.yaml up -d          # ✅
# Use !reset for inherited lists that should be empty
ports: !reset []                                                   # ✅
# Verify the merged model
docker compose config                                              # ✅

❌ Don’t Do This:

# Don't profile core services
backend:
  profiles: [backend]  # won't start by default                     # ❌
# Don't expect ports to replace
# ports: ["443:443"] in the override appends to the base           # ❌
# Don't use an empty override file
# docker errors on an empty compose file                          # ❌
# Don't rely on override paths being relative to the override file
# paths are relative to the base file                             # ❌
# Don't forget the dependency must be in the same profile
debug_lib:
  depends_on: [test_lib]  # test_lib is in a different profile     # ❌

Common Pitfalls

PitfallWhy It HappensFix
Service does not startProfiled but not activatedUse --profile
Dependency errorDependency in a different profilePut both in the same profile
Ports duplicatedOverride appends to baseUse !override or !reset
Path not foundPaths relative to the override filePaths are relative to the base
image and build both setMerge keeps bothThe override’s build wins
Empty override file errorCompose rejects empty filesRemove the file or add content
Profile name invalidWrong formatUse [a-zA-Z0-9][a-zA-Z0-9_.-]+

Real-World Examples

1. Profile for Debug Tools

adminer:
  profiles: [tools]

2. Activate a Profile

docker compose --profile tools up -d

3. COMPOSE_PROFILES

COMPOSE_PROFILES=tools,seed docker compose up

4. Override File

# compose.override.yaml
volumes:
  - .:/app

5. Production File

# compose.prod.yaml
image: ghcr.io/org/myapp:${TAG}

6. Explicit Merge

docker compose -f compose.yaml -f compose.prod.yaml up -d

7. !reset

ports: !reset []

8. !override

ports: !override
  - "443:443"

9. Verify

docker compose config

10. Complete Layering

docker compose -f compose.yaml -f compose.override.yaml --profile tools up

Visual

The Layered Model

┌──────────────────────────────────────────────────────────────┐
│  THE LAYERED MODEL                                           │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  compose.yaml (base)                                 │    │
│  │  - core services                                     │    │
│  │  - common configuration                              │    │
│  │  - committed to git                                  │    │
│  └──────────────────────────────────────────────────────┘    │
│    │                                                         │
│    │  merged with                                            │
│    ▼                                                         │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  compose.override.yaml (dev)                         │    │
│  │  - local development differences                     │    │
│  │  - gitignored                                        │    │
│  └──────────────────────────────────────────────────────┘    │
│    │                                                         │
│    │  optionally merged with                                 │
│    ▼                                                         │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  compose.prod.yaml (prod)                            │    │
│  │  - production differences                            │    │
│  │  - committed to git                                  │    │
│  └──────────────────────────────────────────────────────┘    │
│    │                                                         │
│    ▼                                                         │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Final merged model                                  │    │
│  │  - resolved by Compose                               │    │
│  │  - shown by docker compose config                    │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Profiles

┌──────────────────────────────────────────────────────────────┐
│  PROFILES                                                    │
│                                                              │
│  services:                                                   │
│    db:            (no profile)  → always enabled             │
│    backend:       (no profile)  → always enabled             │
│    frontend:      profiles: [frontend]                       │
│    phpmyadmin:    profiles: [debug]                          │
│    seed:          profiles: [seed]                           │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  docker compose up                                   │    │
│  │    → db, backend                                     │    │
│  │                                                       │    │
│  │  docker compose --profile debug up                   │    │
│  │    → db, backend, phpmyadmin                         │    │
│  │                                                       │    │
│  │  docker compose --profile "*" up                     │    │
│  │    → db, backend, frontend, phpmyadmin, seed         │    │
│  │                                                       │    │
│  │  docker compose run seed                             │    │
│  │    → seed (profile auto-enabled), db (dependency)    │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Merge Rules

┌──────────────────────────────────────────────────────────────┐
│  MERGE RULES                                                 │
│                                                              │
│  SCALARS:                                                    │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  base:      image: a                                 │    │
│  │  override:  image: b                                 │    │
│  │  result:    image: b                                 │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  SEQUENCES:                                                  │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  base:      ports: ["80:80"]                         │    │
│  │  override:  ports: ["443:443"]                       │    │
│  │  result:    ports: ["80:80", "443:443"]              │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  MAPPINGS:                                                   │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  base:      environment: { A: 1 }                    │    │
│  │  override:  environment: { B: 2 }                    │    │
│  │  result:    environment: { A: 1, B: 2 }              │    │
│  │                                                       │    │
│  │  base:      environment: { A: original }             │    │
│  │  override:  environment: { A: override }             │    │
│  │  result:    environment: { A: override }             │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  !reset:  removes the inherited value                        │
│  !override: replaces the list entirely                       │
│                                                              │
└──────────────────────────────────────────────────────────────┘

The Complete Workflow

┌──────────────────────────────────────────────────────────────┐
│  THE COMPLETE WORKFLOW                                       │
│                                                              │
│  DEVELOPMENT:                                                │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  docker compose --profile tools up                   │    │
│  │                                                       │    │
│  │  compose.yaml                                        │    │
│  │    + compose.override.yaml                           │    │
│  │    + adminer (tools profile)                         │    │
│  │                                                       │    │
│  │  Result: source mounted, debug port, APP_ENV=dev     │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  PRODUCTION:                                                 │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  docker compose -f compose.yaml -f compose.prod.yaml │    │
│  │                                                       │    │
│  │  compose.yaml                                        │    │
│  │    + compose.prod.yaml                               │    │
│  │    (no override, no tools)                           │    │
│  │                                                       │    │
│  │  Result: image from registry, port 443, no debug     │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  SEED:                                                       │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  docker compose run --rm seed                        │    │
│  │                                                       │    │
│  │  seed (seed profile auto-enabled)                    │    │
│  │    + db (dependency)                                 │    │
│  │                                                       │    │
│  │  Result: migration runs, container exits             │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
ProfileA named group of services
No profiles attributeAlways enabled
--profileActivates a profile
COMPOSE_PROFILESActivates via environment
--profile "*"Activates all profiles
Explicitly targeted serviceProfile auto-enabled
compose.override.yamlMerged automatically
-f flagSpecifies additional files
Merge orderLater files win
ScalarsReplaced
SequencesAppended
MappingsMerged; override wins
!resetRemoves an inherited value
!overrideReplaces a list

Key takeaways:

  • Profiles control which services are active. A service with a profiles attribute starts only when the profile is enabled. The --profile flag and the COMPOSE_PROFILES environment variable activate profiles. The core services should not be profiled, so they are always enabled .
  • An explicitly targeted service auto-enables its profile. A docker compose run seed command starts the seed service even if its profile is not active. The service’s dependencies are also started, but a dependency in a different profile must be in the same profile, started separately, or always enabled .
  • The compose.override.yaml file is merged automatically. No flags are required. The override file contains the environment-specific differences: the build context, the source mount, the debug port, the development environment variables .
  • Additional files are merged with -f in order. A production deployment uses -f compose.yaml -f compose.prod.yaml to merge the base with the production overrides. The later files win on conflicting keys .
  • The merge rules differ by data type. Scalars are replaced, sequences are appended, and mappings are merged with the override’s value winning. The ports, volumes, and environment keys are the ones that most often surprise developers .
  • The !reset and !override tags give explicit control. !reset removes an inherited value, and !override replaces a list entirely. They are the escape hatch when the default merge rules are not what is wanted .
  • Paths are resolved from the base file. The relative paths in all the merged files are resolved from the first file specified with -f. The --project-directory flag overrides the base path .
  • docker compose config shows the merged model. The command is the tool for verifying the result of the merge and for debugging path and merge issues.

Remember: Profiles control which services are active, and overrides control the configuration of the active services. The compose.override.yaml file is merged automatically, and additional files are merged with -f in order. The merge rules differ by data type: scalars are replaced, sequences are appended, and mappings are merged. The !reset and !override tags give explicit control when the default rules are not what is wanted. The core services should not be profiled, the optional tools should be, and the merged model should be verified with docker compose config. The result is a single repository that serves development, testing, and production without duplicating the service definitions.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!