Docker Compose

Docker Compose

Docker Compose Command Handbook:

1. Docker Compose Installation & Configuration

# Check Docker version
docker --version

# Check Docker Compose version
docker compose version

# Display Docker system information
docker info

# Check Docker Compose help
docker compose --help

# Check available Compose commands
docker compose config --help
docker compose up --help

# Check Docker installation
docker run hello-world

# Display Docker context
docker context ls

# Display active Docker context
docker context show

# Switch Docker context
docker context use default

2. Docker Compose File & Configuration

# Validate Compose configuration
docker compose config

# Display resolved Compose configuration
docker compose config --no-interpolate

# Display configuration with resolved variables
docker compose config --environment

# Display only service names
docker compose config --services

# Display configured volumes
docker compose config --volumes

# Display configuration in JSON format
docker compose config --format json

# Validate a specific Compose file
docker compose -f docker-compose.yml config

# Use multiple Compose files
docker compose -f compose.yml -f compose.override.yml config

# Use a custom environment file
docker compose --env-file .env.dev config

Important Compose configuration files

File Purpose
`compose.yaml` Main Compose configuration
`compose.yml` Alternative Compose configuration
`docker-compose.yml` Legacy-compatible filename
`compose.override.yaml` Default local override configuration
`.env` Variable substitution values
`.env.dev` Development environment variables
`docker-compose.prod.yml` Production-specific configuration

3. Starting & Stopping Services

# Start all services
docker compose up

# Start services in detached mode
docker compose up -d

# Start a specific service
docker compose up app

# Start multiple services
docker compose up app db redis

# Build images before starting
docker compose up --build

# Force recreate containers
docker compose up --force-recreate

# Recreate containers without rebuilding images
docker compose up --no-build --force-recreate

# Start services without starting dependencies
docker compose up --no-deps app

# Start services and remove orphan containers
docker compose up -d --remove-orphans

# Stop all services
docker compose stop

# Stop a specific service
docker compose stop app

# Start stopped services
docker compose start

# Restart all services
docker compose restart

# Restart a specific service
docker compose restart app

# Stop and remove containers and networks
docker compose down

# Stop and remove containers, networks and orphans
docker compose down --remove-orphans

# Stop and remove everything, including named volumes
docker compose down -v

Common lifecycle commands

Command Purpose
`up` Create and start services
`up -d` Start services in background
`start` Start existing stopped containers
`stop` Stop containers without removing them
`restart` Restart services
`down` Stop and remove containers and networks
`down -v` Also remove Compose-managed named volumes
`pause` Suspend running containers
`unpause` Resume paused containers

4. Service Management & Inspection

# List services and their status
docker compose ps

# List all containers, including stopped ones
docker compose ps -a

# List service names
docker compose config --services

# Display running services
docker compose ps --status running

# Display container IDs
docker compose ps -q

# Display service processes
docker compose top

# Display service processes for a specific service
docker compose top app

# Display detailed container information
docker inspect $(docker compose ps -q app)

# Display container resource usage
docker stats

# Display Compose project name
docker compose ls

# Display all Compose projects
docker compose ls -a

# Display service events
docker compose events

5. Logs & Troubleshooting

# Display logs from all services
docker compose logs

# Follow logs in real time
docker compose logs -f

# Display logs from a specific service
docker compose logs app

# Follow logs from a specific service
docker compose logs -f app

# Display the last 100 log lines
docker compose logs --tail=100

# Display timestamps in logs
docker compose logs -t

# Display logs since a specific time
docker compose logs --since=30m

# Display logs until a specific time
docker compose logs --until=2026-11-20T18:00:00

# Display logs from multiple services
docker compose logs app db redis

# Display logs without color
docker compose logs --no-color

# Display container events
docker events

# Inspect a container
docker inspect <container_id>

# Display container resource usage
docker stats <container_id>

Useful troubleshooting commands

Command Purpose
`docker compose logs -f` Follow service logs
`docker compose ps -a` Inspect service status
`docker compose top` Inspect running processes
`docker compose events` Monitor Compose events
`docker compose config` Validate resolved configuration
`docker inspect` Inspect container configuration
`docker stats` Monitor CPU and memory usage

6. Building & Managing Images

# Build all services
docker compose build

# Build a specific service
docker compose build app

# Build without cache
docker compose build --no-cache

# Pull images before building
docker compose build --pull

# Build with a specific build argument
docker compose build --build-arg APP_ENV=dev

# Build a specific service without dependencies
docker compose build --no-deps app

# Build and start services
docker compose up --build

# Pull all service images
docker compose pull

# Pull a specific service image
docker compose pull app

# Pull images quietly
docker compose pull -q

# Push service images to a registry
docker compose push

# Push a specific service image
docker compose push app

# List Docker images
docker images

# Remove unused images
docker image prune

# Remove unused images, including unreferenced tagged images
docker image prune -a

Useful image commands

Command Purpose
`build` Build service images
`build –no-cache` Build without cached layers
`build –pull` Attempt to pull newer base images
`pull` Download service images
`push` Upload service images
`images` List local images
`image prune` Remove unused images

7. Executing Commands Inside Containers

# Execute a command in a running service
docker compose exec app ls

# Open a shell inside a running container
docker compose exec app sh

# Open Bash shell
docker compose exec app bash

# Execute command as root
docker compose exec -u root app sh

# Execute command in a specific working directory
docker compose exec -w /app app pwd

# Execute command without allocating a TTY
docker compose exec -T app ls

# Execute a command with environment variables
docker compose exec -e DEBUG=true app printenv

# Execute a one-off command
docker compose run app echo "Hello Docker"

# Run a one-off command without starting dependencies
docker compose run --no-deps app echo "Hello"

# Run a one-off container and remove it afterward
docker compose run --rm app npm test

# Run database migrations
docker compose exec app ./migrate.sh

# Execute a PostgreSQL command
docker compose exec db psql -U app -d app

# Execute Redis CLI
docker compose exec redis redis-cli

Difference between `exec` and `run`

Command Behavior
`docker compose exec` Runs a command inside an existing running container
`docker compose run` Creates a new one-off container for a command
`docker compose run –rm` Removes the one-off container after execution

8. Networks & Service Communication

# List Docker networks
docker network ls

# Inspect a network
docker network inspect <network_name>

# Display Compose networks
docker compose config

# Create a Docker network
docker network create app-network

# Connect a container to a network
docker network connect app-network <container_id>

# Disconnect a container from a network
docker network disconnect app-network <container_id>

# Remove a Docker network
docker network rm app-network

# Remove unused networks
docker network prune

# Inspect a service container
docker inspect $(docker compose ps -q app)

# Test connectivity between services
docker compose exec app ping db

# Test DNS resolution
docker compose exec app nslookup db

# Test HTTP connectivity
docker compose exec app curl http://db:5432

Important networking concepts

Concept Description
Default network Automatically created for a Compose project
Service discovery Services can communicate using service names
`ports` Publishes container ports to the host
`expose` Documents internal service ports
`networks` Connects services to specified networks
`networkmode` Controls container network mode
`aliases` Defines alternative network DNS names

9. Volumes & Persistent Storage

# List Docker volumes
docker volume ls

# Inspect a volume
docker volume inspect <volume_name>

# Create a Docker volume
docker volume create app-data

# Remove a Docker volume
docker volume rm app-data

# Remove unused volumes
docker volume prune

# Display volumes used by a service
docker inspect $(docker compose ps -q db)

# Display Compose project volumes
docker compose config --volumes

# Stop services without removing volumes
docker compose down

# Remove services and named volumes
docker compose down -v

# Copy files from container to host
docker compose cp app:/app/logs ./logs

# Copy files from host to container
docker compose cp ./config app:/app/config

# Backup a named volume using a temporary container
docker run --rm \
  -v app-data:/data \
  -v "$PWD":/backup \
  alpine \
  tar czf /backup/app-data.tar.gz -C /data .

Volume types

Type Purpose
Named volume Docker-managed persistent storage
Anonymous volume Automatically generated volume
Bind mount Maps a host filesystem path into a container
tmpfs Temporary in-memory filesystem

Warning: `docker compose down -v` deletes Compose-managed named volumes. Always back up important data before running it.

10. Environment Variables & Profiles

# Use the default .env file
docker compose up -d

# Use a custom environment file
docker compose --env-file .env.dev up -d

# Use a production environment file
docker compose --env-file .env.prod up -d

# Set a variable for a single command
APP_ENV=dev docker compose up -d

# Set multiple environment variables
APP_ENV=dev DB_PORT=5432 docker compose up -d

# Display resolved environment variables
docker compose config --environment

# Start services with a specific profile
docker compose --profile debug up -d

# Start services with multiple profiles
docker compose --profile debug --profile monitoring up -d

# Enable all profiles
docker compose --profile "*" up -d

# Start services without activating optional profiles
docker compose up -d

# List configured profiles through resolved configuration
docker compose config

Variable substitution examples

services:
  app:
    image: my-app:${APP_VERSION:-latest}
    environment:
      APP_ENV: ${APP_ENV:-development}
      DB_HOST: ${DB_HOST:-db}
      DB_PORT: ${DB_PORT:-5432}

Syntax Meaning
`${VAR}` Substitute variable
`${VAR:-default}` Use default if variable is unset or empty
`${VAR-default}` Use default if variable is unset
`${VAR:?error}` Fail if variable is unset or empty
`${VAR?error}` Fail if variable is unset
`${VAR:+value}` Use value if variable is set and non-empty

11. Multiple Compose Files & Project Management

# Use the default Compose file
docker compose up -d

# Specify a Compose file
docker compose -f compose.yml up -d

# Combine base and development files
docker compose -f compose.yml -f compose.dev.yml up -d

# Combine base and production files
docker compose -f compose.yml -f compose.prod.yml up -d

# Validate merged configuration
docker compose -f compose.yml -f compose.dev.yml config

# Build using multiple Compose files
docker compose -f compose.yml -f compose.dev.yml build

# Stop a stack using multiple files
docker compose -f compose.yml -f compose.dev.yml down

# Specify a project name
docker compose -p my-project up -d

# Stop a specific project
docker compose -p my-project down

# Display Compose projects
docker compose ls

# Display project containers
docker compose -p my-project ps

# Set project name through environment variable
COMPOSE_PROJECT_NAME=my-project docker compose up -d

# Specify project directory
docker compose --project-directory ./deployment up -d

Compose file merge rules

Rule Behavior
First file Defines the base configuration
Later files Override or extend previous configuration
`-f` Specifies Compose files
`-p` Specifies project name
`–project-directory` Sets project working directory
`–profile` Enables optional service profiles

12. Scaling & Resource Management

# Scale application service to three instances
docker compose up -d --scale app=3

# Scale multiple services
docker compose up -d --scale app=3 --scale worker=2

# Display service instances
docker compose ps

# Monitor container resources
docker stats

# Display processes in a service
docker compose top app

# Pause a service
docker compose pause app

# Resume a service
docker compose unpause app

# Stop a service with a timeout
docker compose stop -t 30 app

# Display container resource limits
docker inspect $(docker compose ps -q app)

Resource configuration example

services:
  app:
    image: my-app:1.0
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 512M
        reservations:
          cpus: "0.5"
          memory: 256M

Note: Scaling a service requires avoiding fixed `containername` values. Services that publish the same fixed host port also need an appropriate port allocation strategy.

13. Health Checks & Dependency Management

# Display service status
docker compose ps

# Inspect container health status
docker inspect \
  --format='{{.State.Health.Status}}' \
  $(docker compose ps -q app)

# Display health check details
docker inspect \
  --format='{{json .State.Health}}' \
  $(docker compose ps -q app)

# Display service logs
docker compose logs -f app

# Restart an unhealthy service manually
docker compose restart app

# Display service dependencies
docker compose config

Health check configuration

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: app
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s

  app:
    image: my-app:1.0
    depends_on:
      db:
        condition: service_healthy

Health check parameters

Parameter Purpose
`test` Command used to check service health
`interval` Time between checks
`timeout` Maximum time for a check
`retries` Consecutive failures before unhealthy status
`startperiod` Startup grace period

Important: `dependson` with `servicehealthy` helps coordinate startup, but applications should still implement connection retries and recovery logic.

14. Cleanup & Maintenance

# Stop and remove Compose containers
docker compose down

# Remove orphan containers
docker compose down --remove-orphans

# Remove stopped service containers
docker compose rm

# Force remove stopped service containers
docker compose rm -f

# Remove containers and named volumes
docker compose down -v

# Remove unused containers
docker container prune

# Remove unused images
docker image prune

# Remove unused volumes
docker volume prune

# Remove unused networks
docker network prune

# Remove unused Docker resources
docker system prune

# Remove all unused resources, including unused images
docker system prune -a

# Display Docker disk usage
docker system df

# Display detailed Docker disk usage
docker system df -v

# Display Docker system information
docker info

Cleanup command differences

Command What it removes
`docker compose down` Project containers and networks
`docker compose down -v` Also removes Compose-managed named volumes
`docker compose rm` Stopped service containers
`docker container prune` All stopped containers
`docker image prune` Unused images
`docker volume prune` Unused volumes
`docker network prune` Unused networks
`docker system prune` Unused containers, networks, build cache and dangling images

15. Docker Compose Debugging & CI/CD

# Validate Compose configuration
docker compose config

# Validate configuration quietly
docker compose config -q

# Start services and rebuild images
docker compose up -d --build

# Wait for services to become running or healthy
docker compose up -d --wait

# Set a maximum startup wait time
docker compose up -d --wait --wait-timeout 120

# Display service status
docker compose ps

# Follow service logs
docker compose logs -f --tail=200

# Execute tests inside a service
docker compose exec app ./run-tests.sh

# Run integration tests in a one-off container
docker compose run --rm app ./run-integration-tests.sh

# Display Docker events
docker compose events

# Stop services after CI execution
docker compose down --remove-orphans

# Stop services and remove test volumes
docker compose down -v --remove-orphans

Example CI/CD workflow

# 1. Validate configuration
docker compose config -q

# 2. Build application and dependencies
docker compose build

# 3. Start services
docker compose up -d --wait

# 4. Run integration tests
docker compose run --rm app ./run-tests.sh

# 5. Display logs if troubleshooting is needed
docker compose logs --tail=200

# 6. Stop and clean up
docker compose down -v --remove-orphans

Important: In CI pipelines, use unique project names for parallel executions to avoid container, network, volume, and port conflicts.

16. Quick Docker Compose Cheat Sheet

Goal Command
Check Compose version `docker compose version`
Validate configuration `docker compose config`
Start services `docker compose up`
Start in background `docker compose up -d`
Build and start `docker compose up –build -d`
Stop services `docker compose stop`
Restart services `docker compose restart`
Remove stack `docker compose down`
List containers `docker compose ps`
Follow logs `docker compose logs -f`
Open container shell `docker compose exec app sh`
Run one-off command `docker compose run –rm app command`
Build images `docker compose build`
Pull images `docker compose pull`
Push images `docker compose push`
List services `docker compose config –services`
List volumes `docker volume ls`
List networks `docker network ls`
Scale service `docker compose up -d –scale app=3`
Enable profile `docker compose –profile debug up -d`
Use custom file `docker compose -f compose.prod.yml up -d`
Use custom project `docker compose -p my-project up -d`
Remove orphans `docker compose down –remove-orphans`
Remove volumes `docker compose down -v`
Check disk usage `docker system df`

Best Practices

  • Prefer the modern `docker compose` command over the legacy `docker-compose` syntax.
  • Keep Compose configuration in version control.
  • Pin image versions instead of relying on mutable `latest` tags.
  • Use `.env` files for configuration and keep sensitive values out of Git.
  • Use Docker secrets or an external secret manager for sensitive credentials.
  • Add health checks for stateful services and critical dependencies.
  • Use named volumes for persistent application data.
  • Use separate Compose override files or profiles for development, testing, and production.
  • Avoid fixed `containername` values when scaling services.
  • Use `docker compose config` before deploying changes.
  • Use `docker compose down -v` only when deleting persistent data is intentional.
  • Use unique project names in CI/CD pipelines.
  • Implement application-level retries for database and service connections.
  • Configure resource limits and logging rotation where appropriate.
  • Keep containers running with non-root users and least-privilege permissions.

Note: These examples use the modern Docker Compose V2 CLI (`docker compose`). Some options and behaviors depend on the installed Docker Compose version and runtime.


Beginner

Q1: What is Docker Compose?

Docker Compose is a tool for defining and running multi-container Docker applications.

Q2: Why use Docker Compose?

It lets you manage multiple services declaratively in one YAML file.

Q3: What file does Compose use by default?

docker-compose.yml (and Compose specification-compatible file names).

Q4: What is a service in Compose?

A containerized application component defined in Compose config.

Q5: What is a project in Compose?

A group of services/networks/volumes created from one Compose configuration.

Q6: How do you start services with Compose?

Use docker compose up.

Q7: How do you stop and remove Compose services?

Use docker compose down.

Q8: Difference between stop and down?

stop halts containers; down removes containers/networks (and optionally volumes).

Q9: What does docker compose up -d do?

Starts services in detached (background) mode.

Q10: How view running Compose services?

Use docker compose ps.

Q11: How view logs for services?

Use docker compose logs.

Q12: How follow logs in real time?

Use docker compose logs -f.

Q13: How rebuild images before startup?

Use docker compose up --build.

Q14: What is build: in Compose?

Instructions for building image from local Dockerfile/context.

Q15: What is image: in Compose?

Specifies prebuilt image to run for a service.

Q16: Can a service use both build and image?

Yes, commonly for tagging built result.

Q17: What is ports: in Compose?

Maps host ports to container ports.

Q18: What is expose: in Compose?

Documents/internally exposes ports to linked services without host publishing.

Q19: What is environment: in Compose?

Sets environment variables in service containers.

Q20: What is env_file:?

Loads environment variables from external file(s).

Q21: What is .env file in Compose?

File for variable substitution and/or env defaults in Compose context.

Q22: What is variable substitution syntax?

Like ${VAR} or ${VAR:-default}.

Q23: What is a Compose network?

Virtual network enabling service-to-service communication.

Q24: Default networking behavior in Compose?

Creates project-scoped default network; services can reach each other by service name.

Q25: What is a Compose volume?

Persistent storage managed by Docker and attachable to services.

Q26: Why use volumes in Compose?

Persist data across container restarts/recreation.

Q27: Bind mount vs volume in Compose?

Bind mount uses host path; volume is Docker-managed storage.

Q28: What is depends_on?

Defines startup dependency order between services.

Q29: Does dependson guarantee app readiness?

No, it does not guarantee dependency is fully ready.

Q30: How run one-off command in a service?

Use docker compose run.

Q31: What is difference between run and exec?

run starts new container; exec runs command in existing container.

Q32: How execute shell inside running service?

Use docker compose exec <service> sh (or bash if available).

Q33: How scale a service quickly?

Use docker compose up --scale service=n (where applicable).

Q34: What is containername in Compose?

Custom fixed container name (often avoided in scalable setups).

Q35: Why avoid fixed containername often?

Can cause naming collisions and reduce flexibility.

Q36: What is restart policy in Compose?

Controls automatic restart behavior (no, always, on-failure, unless-stopped).

Q37: What is healthcheck in Compose?

Command-based liveness/readiness signal for container health.

Q38: Why healthchecks matter in local stacks?

Improve reliability and dependency coordination.

Q39: What is command override in Compose?

Override Dockerfile CMD per environment/service need.

Q40: What is entrypoint override?

Replace image entrypoint command.

Q41: What is tty: true used for?

Allocates TTY for interactive/debug workflows.

Q42: What is stdinopen: true?

Keeps STDIN open for interactive containers.

Q43: What is profiles in Compose?

Feature to enable optional service groups (e.g., debug, monitoring).

Q44: How start only selected profiles?

Use --profile flag.

Q45: What is pull policy behavior concept?

Controls when images are pulled vs reused locally.

Q46: What is beginner Compose anti-pattern?

Putting secrets directly in compose YAML committed to git.

Q47: Another beginner anti-pattern?

Using latest tags everywhere without version pinning.

Q48: Beginner security baseline?

Use minimal images, non-root users, and keep secrets outside source.

Q49: Beginner performance baseline?

Use build cache and avoid oversized bind mounts.

Q50: Beginner reliability baseline?

Healthchecks + restart policies + persistent data volumes.

Q51: What command validates Compose config?

docker compose config.

Q52: Why use docker compose config?

Shows merged, resolved final configuration for debugging.

Q53: How remove stopped containers only?

Use docker compose rm.

Q54: How remove volumes with stack?

Use docker compose down -v carefully.

Q55: Beginner best practice?

Keep compose files clear, versioned, and environment-specific via overrides/profiles.

Intermediate

Q56: What is multiple Compose file merge?

Combining base and override files via multiple -f flags.

Q57: Why use override files?

Separate common config from dev/test/ci-specific settings.

Q58: Merge order rule?

Later files override/extend earlier ones.

Q59: What is extension fields pattern (x-*)?

Reusable YAML fragments for DRY configuration.

Q60: What is YAML anchor/alias use in Compose?

Reuse repeated config blocks safely.

Q61: What is project name control?

Use -p flag or environment variable to isolate stacks.

Q62: Why customize project name?

Avoid collisions across branches/teams on shared hosts.

Q63: What is internal-only network?

Network not exposed externally; limits service reachability.

Q64: How connect service to multiple networks?

Declare multiple networks under service.

Q65: Why use multiple networks?

Segment traffic (frontend/backend/data-plane) for security/isolation.

Q66: What is network alias?

Alternative DNS name for service on specific network.

Q67: What is extrahosts in Compose?

Adds custom host-to-IP mappings inside container.

Q68: What is DNS config in Compose?

Customize resolvers/search domains/options for containers.

Q69: What is init: true?

Runs tiny init process for signal forwarding/zombie reaping.

Q70: Why init is useful?

Improves process lifecycle behavior in containers.

Q71: What is stopgraceperiod?

Time allowed for graceful shutdown before force kill.

Q72: Why tune stopgraceperiod?

Stateful services may need extra flush/cleanup time.

Q73: What is ulimits in Compose?

Sets process resource limits (nofile, nproc, etc.).

Q74: Why configure ulimits?

Prevent runtime failures under high load.

Q75: What is sysctls in Compose?

Kernel parameter tweaks at container runtime (where supported).

Q76: What is capadd/capdrop?

Add/remove Linux capabilities for least-privilege tuning.

Q77: Why drop capabilities?

Reduce attack surface for compromised containers.

Q78: What is readonly: true?

Mounts container root filesystem read-only.

Q79: How write data with read-only root?

Use writable volumes/tmpfs for specific paths.

Q80: What is tmpfs in Compose?

In-memory filesystem mount for ephemeral data.

Q81: What is secrets support in Compose (concept)?

Inject secret material without hardcoding in image/environment.

Q82: Configs vs secrets conceptually?

Both inject data; secrets intended for sensitive values with stricter handling.

Q83: What is develop/watch workflow concept?

Auto-sync/rebuild behavior for local development iterations.

Q84: Why bind mounts can be slow on some platforms?

Host<->VM filesystem bridging overhead (especially desktop virtualization setups).

Q85: Mitigation for slow bind mounts?

Use cached/delegated options (where supported), smaller mounts, sync tools.

Q86: What is platform field in Compose?

Specifies target architecture/OS for image run.

Q87: Why set platform explicitly?

Consistency across mixed-architecture developer machines.

Q88: What is build target in Compose?

Select specific Dockerfile multi-stage target.

Q89: Why use build target?

Different images for dev/test/prod from one Dockerfile.

Q90: What is cachefrom/cacheto concept?

Leverage external build caches to speed CI builds.

Q91: What is no-cache build?

Forces rebuild without using cached layers.

Q92: When use no-cache?

Dependency freshness debugging or cache corruption suspicion.

Q93: What is dependson condition support concept?

Can coordinate based on servicestarted/servicehealthy semantics (spec/runtime dependent).

Q94: Why still use app-level retries?

Infra ordering is insufficient for real readiness guarantees.

Q95: What is wait-for script pattern?

Entry command waits for dependency port/health before app start.

Q96: What is one-shot init service pattern?

Dedicated service runs migrations/setup before app services.

Q97: How share artifacts between services?

Named volumes or object storage, depending workflow.

Q98: What is logging section in Compose?

Configures log driver and options per service.

Q99: Why configure logging options?

Control size/rotation and centralization behavior.

Q100: What is json-file max-size/max-file?

Limits local log file growth.

Q101: What is resource constraints in Compose?

CPU/memory/pids limits to prevent host exhaustion.

Q102: Why set memory limits in dev too?

Catch memory issues early and protect workstation stability.

Q103: What is healthcheck retry/startperiod?

Tuning for startup grace and transient failures.

Q104: What is intermediate anti-pattern?

Single compose file trying to cover all envs with heavy conditionals.

Q105: Better pattern?

Base compose + targeted overrides/profiles per environment.

Q106: What is image immutability practice in Compose workflows?

Pin explicit versions/digests for reproducible runs.

Q107: Why avoid mutable tags in CI integration tests?

Can cause nondeterministic failures across runs.

Q108: What is Compose in CI use case?

Spin up integration dependencies for automated test suites.

Q109: How ensure clean CI state?

Use unique project names and always teardown after tests.

Q110: What is orphan container warning?

Containers from old config no longer referenced by current compose set.

Q111: How remove orphans?

Use --remove-orphans when bringing stack up/down as appropriate.

Q112: What is volume migration concern?

Schema/data upgrades must be managed between image versions.

Q113: Why backup named volumes?

Protect state before destructive changes.

Q114: What is intermediate debugging toolkit?

compose logs, exec, top, events, inspect, config output.

Q115: What is intermediate security concern?

Excessive host mounts exposing sensitive filesystem paths.

Q116: Mitigation for mount risk?

Mount least required paths read-only where possible.

Q117: What is intermediate reliability principle?

Design services to start independently and retry dependencies gracefully.

Q118: Intermediate maturity signal?

Team can reproduce full local stack with one command and deterministic behavior.

Q119: Intermediate operations principle?

Standardize compose templates and document service contracts/ports/health.

Q120: Intermediate best practice?

Use Compose as declarative environment contract, not ad-hoc scripts.

Advanced

Q121: What is Compose as “platform interface” concept?

A stable developer-facing contract abstracting infra complexity.

Q122: Why treat Compose files as product assets?

They define reproducible onboarding, testing, and incident-debug environments.

Q123: What is drift between local and prod concern?

Differences in config/dependencies cause “works on my machine” failures.

Q124: How reduce environment drift?

Use shared images, pinned versions, and prod-like settings in dev profiles.

Q125: What is multi-arch development challenge?

Different host CPUs (amd64/arm64) can change behavior/performance.

Q126: Mitigation for multi-arch issues?

Buildx multi-platform images and explicit platform testing matrix.

Q127: What is hermetic integration test environment?

Self-contained stack with controlled dependencies and deterministic inputs.

Q128: Why hermetic CI stacks matter?

Reduce flaky tests caused by shared external services.

Q129: What is ephemeral preview environment pattern?

Per-branch isolated Compose stack for validation/review.

Q130: What is project namespace collision risk?

Shared host conflicts in container/network/volume names.

Q131: How prevent collisions?

Unique project names plus automated lifecycle cleanup.

Q132: What is advanced secret management pattern with Compose?

External secret store injection at runtime, not committed plaintext values.

Q133: What is supply-chain security for Compose workflows?

Signed images, SBOMs, vulnerability scanning, trusted registries.

Q134: Why verify image provenance in Compose stacks?

Prevent pulling tampered or untrusted artifacts.

Q135: What is policy-as-code for Compose?

Automated checks enforcing rules (no root, pinned tags, limits required).

Q136: What is least-privilege runtime in Compose?

Drop caps, read-only FS, non-root user, minimal mounts/networks.

Q137: What is egress restriction challenge in Compose?

Limit outbound access for sensitive services to reduce exfiltration risk.

Q138: What is sidecar pattern in Compose?

Auxiliary container (proxy/agent/exporter) paired with main service.

Q139: Sidecar tradeoff?

Better modularity/observability but more operational complexity.

Q140: What is service mesh simulation in Compose?

Local emulation of proxies/policies for integration testing.

Q141: What is advanced health orchestration pattern?

Dependency graph with healthchecks + init jobs + retry-capable apps.

Q142: Why startup order alone fails at scale?

Real readiness depends on migrations, warmups, and external dependencies.

Q143: What is chaos testing with Compose?

Inject failures (kill, delay, packet loss) to validate resilience behavior.

Q144: Tooling for network fault injection concept?

Traffic control/proxy tools can emulate latency/loss in local stacks.

Q145: What is observability stack in Compose?

Local Prometheus/Grafana/ELK/OTel services alongside app for diagnostics.

Q146: Why include observability in local compose?

Catch telemetry gaps before production.

Q147: What is performance testing with Compose caveat?

Local host limits may not reflect production infrastructure accurately.

Q148: How still gain value from local perf tests?

Trend comparisons and bottleneck discovery under controlled scenarios.

Q149: What is data lifecycle governance for Compose volumes?

Backup/restore/versioning/cleanup policies for persistent local/CI data.

Q150: What is migration-safe workflow for stateful services?

Versioned migrations + compatibility checks + rollback plans.

Q151: What is blue/green style testing with Compose?

Run old/new service versions concurrently and switch traffic route locally.

Q152: What is canary simulation in Compose?

Route subset of test traffic to new container version.

Q153: What is dependency pinning governance?

Central policy for approved base images and versions.

Q154: What is advanced anti-pattern in Compose ecosystems?

Using Compose as production orchestrator substitute beyond its intended scope.

Q155: Better production direction?

Use Compose for dev/test; use full orchestrator for large-scale production needs.

Q156: What is incident reproduction advantage of Compose?

Recreate prod-like bug scenarios quickly on engineer machines.

Q157: What is runbook codification in Compose?

Encode operational steps (init, debug, recovery) as repeatable service tasks.

Q158: What is security scanning integration point?

Pre-merge CI validates compose config and referenced images.

Q159: What is compliance evidence for Compose-based workflows?

Versioned configs, scan reports, signed artifacts, audit trails.

Q160: What is cost-awareness in Compose CI pipelines?

Optimize parallel stack counts, cache reuse, and teardown discipline.

Q161: What is flakiness root cause in Compose CI?

Port collisions, shared resources, weak readiness checks, orphaned state.

Q162: Flakiness mitigation checklist?

Unique namespaces, health-gated startup, deterministic seeds, strict cleanup.

Q163: What is advanced debugging pattern?

Capture full compose events/logs/config snapshot as CI artifacts.

Q164: What is recovery strategy for corrupted local volumes?

Documented reset scripts plus optional seed data restore.

Q165: What is platform team role for Compose?

Provide golden templates, lint rules, and shared service definitions.

Q166: What is final reliability principle?

Stacks must be reproducible, restartable, and dependency-failure tolerant.

Q167: What is final security principle?

No plaintext secrets, least privilege everywhere, trusted artifacts only.

Q168: What is final maintainability principle?

Keep Compose files modular, documented, and policy-validated.

Q169: What is final developer-experience principle?

One command up/down with predictable behavior across machines.

Q170: Final maturity principle?

Compose excellence is deterministic multi-service environments with strong guardrails.

version: "3.9"

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    environment:
      SPRING_PROFILES_ACTIVE: docker
      DB_HOST: db
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:8080/actuator/health"]
      interval: 10s
      timeout: 3s
      retries: 10
    restart: unless-stopped

  db:
    image: postgres:16.4
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 3s
      retries: 20
    restart: unless-stopped

volumes:
  db_data: