Running Containers: docker run, Runtime Options, Volumes & Bind Mounts, Compose, Dev Workflow
"The
docker runcommand runs a command in a new container, pulling the image if needed and starting the container." — Docker CLI reference,docker container run(docs.docker.com)
Summary: An image is a frozen filesystem; everything that decides how it behaves on a host (its name, restart policy, environment, published ports, networks, limits, logging, health, stop budget and, above all, where its data lives) is chosen at run time by docker run flags or a compose.yaml, and most production incidents with containers are run-time choices, not image bugs. Focus: docker run options (detach, interactive tty, name, --rm, --init), restart policies, env and env-file, ports publish and expose vs publish, networks (bridge, host, none, user-defined networks and DNS), resource limits (--memory --cpus --pids-limit) and ulimits, logging drivers and log rotation, healthcheck at runtime, exec, logs, inspect, stats, events, stop vs kill and stop timeout, prune; volumes: named volumes vs bind mounts vs tmpfs, volume drivers, permissions and UID mapping in bind mounts, file ownership issues on macOS and Linux, data persistence and backup of volumes; Docker Compose v2 (and v5): compose.yaml, services, depends_on with conditions, healthcheck in compose, profiles, override files, env interpolation, secrets and configs, build in compose (the BuildKit link), watch (develop.watch), compose networks, scale, project names, docker compose up/down/logs/exec; the dev workflow for a Go service (air/hot reload, bind-mounted source, build cache), the dev workflow for Laravel (Sail, php-fpm + nginx + mysql + redis, artisan in exec), production anti-patterns (compose on prod), Docker Desktop vs Colima vs OrbStack vs Podman Desktop, rootless Docker, context and remote daemons. Learning goal: Run any image with the right flags and say why each flag is there; choose and operate volumes, bind mounts and tmpfs without losing data or fighting file ownership; write a Compose project (base, dev override, production override) for a Go service and a Laravel stack that starts in the right order, keeps secrets out of the environment, rotates its logs and stops cleanly; and know where Compose ends and an orchestrator such as Kubernetes begins.
This chapter is the third in the Containers group. Containers Under the Hood owns what a container is to the kernel (namespaces, cgroups v2, OverlayFS, containerd, runc), so cgroups appear here only as the knobs docker run sets. Images & Dockerfiles owns building the image (layers, cache, multi-stage, HEALTHCHECK, ENTRYPOINT vs CMD and PID 1); this page runs those images. The packet-level view of Docker networks (the iptables rules Docker writes, overlay, macvlan, MTU) is Docker Networking; hardening a running container (capabilities, seccomp, AppArmor/SELinux, user namespaces in depth) is Container Security; the same ideas inside a cluster are Kubernetes Workloads (probes, restarts, rollouts) and Kubernetes Config, Secrets & Storage (ConfigMaps, Secrets, PV/PVC); the architectural case for containers and orchestration is Containers & Kubernetes. Connection pools sized per container are in Connection Pooling, the Go build and Makefile side in Project Layout, Linting & Build, and the command tables in the Docker cheatsheet.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why run-time configuration is separate from the image | Why it exists |
docker run 2013, Fig 2014, Compose v2 2020, Compose Specification, Compose v5 2025 | Where it comes from |
-d, -it, --name, --rm, --init, --pull | docker run options |
no, on-failure, always, unless-stopped, back-off | Restart policies |
-e, --env-file, precedence | Environment |
-p, -P, EXPOSE, expose:, 127.0.0.1 binding | Ports |
| bridge, host, none, user-defined networks, embedded DNS | Networks |
--memory, --cpus, --pids-limit, --ulimit, OOM | Resource limits |
| json-file, local, journald, fluentd, rotation | Logging |
--health-*, health status, events | Healthcheck at runtime |
exec, logs, inspect, stats, events, cp | Operating a container |
| SIGTERM, stop timeout, SIGKILL, exit 137 and 143 | Stop vs kill |
| Volumes, bind mounts, tmpfs, image mounts | Mounts |
| NFS, CIFS, rclone, block devices | Volume drivers |
| UID/GID on bind mounts, macOS vs Linux, rootless mapping | Permissions |
| Persistence rules, backup and restore, prune | Persistence, backup, prune |
Compose v1/v2/v5, compose.yaml, services, project names | Compose |
depends_on conditions, healthcheck in Compose | Start-up order |
profiles, compose.override.yaml, -f, !reset, !override | Profiles and override files |
${VAR:-default}, .env, env_file, precedence | Env interpolation |
secrets:, configs:, /run/secrets, _FILE | Secrets and configs |
build: in Compose, BuildKit, Bake | Build in Compose |
develop.watch, sync, rebuild, sync+restart | Watch |
Compose networks, scale, replicas | Compose networks and scale |
up, down, logs, exec, run, ps, config | Compose CLI |
| Docker Desktop, Colima, OrbStack, Podman Desktop, Rancher Desktop | Desktop runtimes |
Rootless Docker, userns-remap | Rootless Docker |
docker context, DOCKER_HOST, ssh:// | Contexts and remote daemons |
| What Compose on a server gets wrong | Production anti-patterns |
| Create/start flow, Compose model pipeline, knobs, errors | Mechanics |
| Code | Go, Laravel |
| Twelve classic problems and their fixes | Solving the classic problems |
| Which mount, which restart policy, which desktop runtime | Choosing |
| From one laptop to many hosts | In architecture |
| Commands with real and expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The docker run flags that matter (Docker Engine 29.x; defaults from the CLI reference).
| Flag | Plain words | Default | Trap |
|---|---|---|---|
-d, --detach | Run in the background, print the ID | foreground | The container exits when PID 1 exits; service nginx start returns at once |
-i, -t | Keep STDIN open; allocate a pseudo-TTY | off | -t in scripts or CI mangles output and line endings |
--name | A stable name instead of a random one | random (awesome_brattain) | Names are unique per daemon; a second run --name fails |
--rm | Delete the container (and its anonymous volumes) on exit | keep | Cannot be combined with --restart |
--restart | Restart policy | no | always also brings back a container you stopped, after a daemon restart |
-e, --env-file | Environment variables | image ENV | Visible in docker inspect; not for secrets |
-p host:container | Publish a port on the host | nothing published | Without an IP it binds 0.0.0.0, past UFW |
--network | Which network(s) to join | default bridge | Default bridge has no DNS between containers |
-m, --cpus, --pids-limit | Memory, CPU, process limits | unlimited | No memory limit = the host's OOM killer chooses |
--ulimit | nofile, nproc, core... | daemon defaults | nproc counts per user, not per container |
--log-driver, --log-opt | Where stdout/stderr go | json-file, no rotation | Disk fills on a chatty container |
--health-cmd and friends | Runtime health check | image HEALTHCHECK | Docker marks unhealthy but does not restart it |
--stop-timeout, --stop-signal | Grace period and first signal | 10 s (Linux), SIGTERM | Longer drains need a longer timeout |
-v / --mount | Volumes, bind mounts, tmpfs | none | -v silently creates missing host directories; --mount errors |
-u, --user | UID:GID to run as | image USER, else root | Numbers matter across bind mounts, not names |
--init | tini-backed docker-init as PID 1 | off | Needed when PID 1 is a shell or spawns children |
--read-only | Read-only root filesystem | off | Pair with --tmpfs /tmp and a volume for data |
Three kinds of mounts (plus the writable layer you should not use for data).
| Kind | Lives in | Survives rm / down | Owner seen in the container | Use for |
|---|---|---|---|---|
| Container writable layer | Storage driver (overlay2 / containerd snapshot) | No (survives stop/start only) | Image's files | Nothing you need to keep |
| Named volume | Daemon's volume area (/var/lib/docker/volumes/<name>/_data, local driver) | Yes; down -v / volume rm delete it | Copied from the image path on first use | Databases, uploads, caches you keep |
| Anonymous volume | Same area, random name | Yes, except with --rm; not re-attached by compose up | Same as named | Throwaway VOLUME paths |
| Bind mount | Any host path | Yes (Docker never deletes it) | The host file's numeric UID/GID | Source code in dev, config files, sockets |
| tmpfs | Memory (counts against --memory) | No; gone when the container stops | uid=/gid=/mode= options | Scratch files, secrets in memory, /tmp on --read-only |
Compose in one table (Compose v2/v5, the Compose Specification).
| You write | Compose does | Remember |
|---|---|---|
compose.yaml (+ auto-loaded compose.override.yaml) | Loads, interpolates ${VAR} per file, merges, applies profiles | docker compose config prints the final model |
name: / -p / COMPOSE_PROJECT_NAME | Prefixes containers, networks, volumes (orders_pgdata) | Two checkouts with one name share volumes |
services: | One or more containers per service | scale / deploy.replicas for more |
depends_on: {db: {condition: service_healthy}} | Waits for the dependency's healthcheck at start-up | Short syntax waits only for "started" |
healthcheck: | Same as Dockerfile HEALTHCHECK, overrides it | test: ["NONE"] or disable: true turns it off |
ports: / expose: | Publish to host / document for other containers | Quote "HOST:CONTAINER" |
volumes: (top-level) | Named volumes, created on up, kept on down | down -v deletes them |
secrets: / configs: | Files mounted at /run/secrets/<name> / /<name> | File secrets are bind mounts: host mode applies |
profiles: [debug] | Service starts only when the profile is enabled | Core services get no profile |
develop.watch | Sync files, rebuild or restart on change | Needs build:; works with up --watch or watch |
-f a.yaml -f b.yaml | Later files override earlier ones | !reset, !override for sequences |
Why it exists
The image answers "what is installed". It cannot answer "which database does this copy talk to, how much memory may it use, what happens when it crashes, where does its data go, which port does the world reach it on". Those answers differ between your laptop, CI, staging and production, and they change without a rebuild. Docker therefore splits the world in two: the image (immutable, content-addressed, built once) and the container configuration (chosen per run). docker run is that configuration as flags; a Compose file is the same configuration written down, versioned and shared by a team, for several containers at once.
Data is the sharpest case. A container's writable layer is tied to the container's life: re-create the container, which every deploy does, and the layer is gone. Anything that must outlive a deploy (a database, uploaded files, a module cache you want warm) must live outside the container, in a volume or a bind mount, and that choice decides persistence, speed, backup and file ownership.
| Simpler choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
| Data in the container layer | Named volume | Survives re-creation, faster than overlay writes | Backup is your job; invisible to the host file browser |
| Named volume for code | Bind mount for code (dev) | Edit on the host, run in the container | Host UID/permissions leak in; slow on macOS for many files |
| Default bridge network | User-defined network per project | DNS by name, isolation between stacks | One more object (Compose creates it for you) |
-p 8080:8080 | -p 127.0.0.1:8080:8080 | Not reachable from the LAN or internet | Must add a proxy to expose deliberately |
| No limits | --memory, --cpus, --pids-limit | One container cannot starve the host | Tuning; OOM kills inside the limit |
json-file with defaults | local driver or max-size/max-file | Disk never fills from logs | Fewer local history lines |
restart: always | unless-stopped / on-failure:N + health | Predictable behaviour after manual stops | Need to think about which failures to retry |
| Environment variables for passwords | Secrets mounted as files | Not in inspect, not inherited by children | App must read a file (_FILE convention) |
Many docker run lines | Compose project | One file, one command, ordered start-up | Single host only; no scheduling or rolling updates |
The analogy used through this page: a rented workshop. The image is the toolbox you bring; it is the same in every workshop. The container is the workshop booked for you: the landlord (the Docker daemon) decides which door number customers use (published ports), which internal phone extensions exist (networks and DNS), how much electricity you may draw (limits), whether someone reopens the shop if you collapse (restart policy) and how long you get to tidy up when closing time is called (stop timeout). Your workbench surface (the writable layer) is wiped when the booking ends. Anything you want to keep goes into a locker the landlord manages (a named volume), or you bring your own shelf from home and bolt it to the wall (a bind mount), in which case your home's rules about who may touch it apply inside the workshop too. A whiteboard (tmpfs) is erased every evening. Compose is the booking form for a whole row of workshops that must open in a particular order.
Three common misunderstandings, up front
- "
docker stopanddocker startlose my data." They do not: stop/start keeps the same container and its writable layer. What loses data isdocker rm,docker compose downfollowed byup(new containers), or any redeploy. The fix is not "never remove containers" but volumes. See Mounts. - "
depends_onmakes my app wait until the database is ready." The short syntax only waits until the database container has started; with it, the reference says, "Compose does not wait for dependency services to be" healthy. Usecondition: service_healthywith a healthcheck, and still retry connections in the app. See Start-up order. - "
EXPOSE 8080(orexpose:) makes the port reachable." Exposing documents a port for other containers; only-p/ports:publishes it on the host. And-p 8080:8080without an address publishes on every interface: Docker's reference warns these ports "are externally accessible", even if UFW blocks them. See Ports.
Where it comes from
| When | What happened | Source |
|---|---|---|
| 2014 | Compose v1 "first released in 2014. It was written in Python and invoked with docker-compose" (it began as Fig) | Compose history page |
| 2014 / 2016 / 2017 | Compose file formats 1, 2.x (Compose 1.6.0) and 3.x (Compose 1.10.0, Swarm-oriented) | Compose history page |
| Before Compose v2 | User-defined networks with embedded DNS (127.0.0.11) replace --link, which the docs now call "considered legacy" | Bridge and network overview docs (release not dated in saved sources) |
| API 1.25 | --init, --cpus, --stop-timeout appear in the run reference with this API marker | docker run options table |
| 2020 | Compose v2 "announced in 2020, is written in Go and is invoked with docker compose"; it ignores the version: key | Compose history page |
| With Compose v2 | File formats 2.x and 3.x merged into the rolling Compose Specification (compose-spec.io); version: becomes optional | Compose history page |
| Compose 2.17 / 2.20 | depends_on.restart (2.17.0), depends_on.required (2.20.0) | Compose services reference |
| Compose 2.23.1 | configs from environment and inline content; Compose Watch (develop.watch) is part of the current Compose Specification | Compose configs and develop references |
| Engine 23 | Relative host paths in -v (-v ./content:/content) | docker run reference |
| Docker Desktop 4.34 | Host networking supported on Docker Desktop (opt-in setting) | Host network docs |
| 2 Dec 2025 | Compose v5.0.0: official Go SDK; "build is delegated to Docker Bake"; v3 and v4 skipped to avoid confusion with file formats 2.x/3.x | Compose v5.0.0 release notes |
| Nov 2026 | Compose 5.8.0 adds experimental jobs: (scheduled one-shot work, needs Engine 29.10 with the jobs extension); Engine 29.10.1 (24 Nov 2026) | Compose release notes, Engine 29 release notes |
Two lineages explain most confusion you meet in the wild. First, Compose v1 (docker-compose, Python) and its numbered file formats: tutorials still start files with version: "3.8", which Compose v2 and v5 ignore, and some still type docker-compose with a hyphen. Second, the Swarm-era deploy: section from file format 3.x: in the Compose Specification deploy is an optional part that the Docker Compose CLI honours for resources and replicas, while placement constraints and rolling-update settings only mean something to Swarm. Today the docker compose plugin implements the Compose Specification; Podman, Podman Desktop, OrbStack, Colima and Rancher Desktop run the same files through the same or a compatible implementation.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.
docker run options: detach, interactive tty, name, --rm, --init Must-know
In plain words: docker run is docker create (make a container from an image plus your options) followed by docker start. The flags decide whether your terminal is attached, whether input reaches the process, what the container is called and whether it cleans up after itself.
Common misunderstanding: "-d keeps a container running." A container lives exactly as long as its PID 1. The reference spells it out: containers in detached mode "exit when the root process used to run the container exits", so docker run -d nginx-image service nginx start starts nginx in the background, the service script returns, PID 1 exits and the container stops. Run the server in the foreground (nginx -g 'daemon off;').
Definition: -d runs detached and prints the container ID. -i "keeps the container's STDIN open"; -t "attaches a pseudo-TTY", which gives line editing, colours and hidden password prompts; together (-it) they make an interactive shell. --name assigns a unique, stable name used by every later command and by DNS on user-defined networks. --rm removes the container "and its associated anonymous volumes when it exits" (named volumes stay). --init runs docker-init ("backed by tini") as PID 1 to forward signals and reap zombies. --pull is missing by default; always re-resolves the tag, never fails if the image is not local. Exit codes of docker run itself: 125 (daemon error), 126 (command cannot be invoked), 127 (command not found); anything else is the container's own exit code.
docker run -d --name api -p 127.0.0.1:8080:8080 ghcr.io/acme/orders-api:1.4.2
1 CLI: image present locally? (--pull=missing) -> no -> pull index, manifest, layers
2 CLI -> daemon: POST /containers/create {Image, Env, HostConfig{PortBindings, RestartPolicy, Mounts, Memory...}}
3 daemon: snapshot for the writable layer, network endpoint on "bridge", name "api" reserved
4 CLI -> daemon: POST /containers/api/start -> containerd -> runc -> PID 1 = /orders-api
5 -d: CLI prints the ID and returns; without -d it attaches to stdout/stderr until PID 1 exits
6 PID 1 exits -> container "exited" (kept unless --rm); restart policy decides what happens nextReal scenarios:
- A CI step runs
docker run --rm -i image go test ./...and pipes a file in:-iwithout-tkeeps output clean for logs. docker exec -it api shfails on a distroless image: there is no shell. Debug with an image mount, a:debugimage, ordocker debugwhere available.- A cron job runs
docker run --name nightly ...and fails on the second night: the name is still taken by last night's exited container. Add--rm. - A PHP worker spawns
exec()children that become zombies:--init(or Composeinit: true) reaps them.
| Product | Equivalent of these flags |
|---|---|
| Docker Compose | stdin_open: true, tty: true, container_name: (avoid: blocks scaling), init: true, pull_policy:; docker compose run --rm for one-offs |
| Podman | Same flags (podman run -dit --rm --name); daemonless, so -d containers are children of conmon |
| Kubernetes | stdin, tty in the container spec; names are generated per Pod; kubectl run --rm -it for one-offs |
containerd nerdctl | Docker-compatible nerdctl run -d --name --rm |
Fix / how to use it: services run -d with a --name (or as a Compose service); one-off tools run --rm -it; never rely on a random name in scripts; add --init when PID 1 is a shell script or a process that forks. Signal handling in the image itself is covered in Images & Dockerfiles.
Restart policies Must-know
In plain words: A restart policy tells the Docker daemon what to do when a container's PID 1 exits: nothing, restart on errors, or always restart. It is the single-host substitute for a supervisor like systemd.
Common misunderstanding: "restart: always restarts unhealthy containers." It does not. Restart policies react to the process exiting; a container that is running but unhealthy stays running and unhealthy. Plain Docker and Compose have no "restart on unhealthy"; that is an orchestrator feature (Kubernetes liveness probes, Swarm). If you need it on one host, make the process exit on fatal errors, or run a small watchdog.
Definition: --restart takes no (default), on-failure[:max-retries] (non-zero exit only; "It doesn't restart the container if the daemon restarts"), always ("If it's manually stopped, it's restarted only when Docker daemon restarts or the container itself is manually restarted") and unless-stopped (like always, but a stopped container "isn't restarted even after Docker daemon restarts"). Restarts back off: "the daemon waits for 100 ms, then 200 ms, 400, 800, 1600, and so on" up to a 1-minute maximum, and the delay resets once a restarted container runs for at least 10 seconds (run reference). The restart-policy guide adds that a policy "only takes effect after a container starts successfully" (up at least 10 seconds), to keep a container that never starts out of a restart loop; the two pages describe the same mechanism from different sides, and the exact first-start behaviour was not verified here by running Docker. --restart with --rm is an error. docker inspect shows attempts in the container's RestartCount field (template in the Lab, step 4); docker update --restart unless-stopped <c> changes the policy of a running container. Restart policies are different from the daemon's live-restore, which keeps containers running while dockerd itself is upgraded.
restart: unless-stopped, app panics on a bad config value at boot
(sequence follows the run reference's back-off description; not run here)
t=0.0s start -> exit 2 after 0.3 s (under 10 s of uptime: the back-off is not reset)
t=0.4s restart after 100 ms back-off -> exit 2
t=0.9s restart after 200 ms -> exit 2 ... 400, 800, 1600 ms ...
t=~60s delay capped at 1 minute; docker ps shows "Restarting (2) 3 seconds ago"
fix config, docker compose up -d -> new container, runs > 10 s, back-off resets to 100 ms
docker stop -> stays stopped, also after a host reboot (always would bring it back)Real scenarios:
- A Redis container on a small VM should come back after a kernel update reboot:
unless-stopped. - A migration job must not loop forever on a bad SQL file:
on-failure:3orrestart: "no"plus alerting. - An operator stops a misbehaving
alwayscontainer for investigation; after the nightly Docker upgrade it is running again.unless-stoppedwould have respected the manual stop. - A crash-looping API floods logs and CPU: the exponential back-off limits restarts to about one a minute, and
docker events --filter event=restartshows the loop.
| Product | Restart model |
|---|---|
| Docker Engine | no, on-failure[:N], always, unless-stopped; exponential back-off 100 ms to 1 min |
| Docker Compose | Same values under restart:; deploy.restart_policy (condition, delay, max_attempts) is the Swarm-style form |
| Podman | Same --restart flags; there is no long-running daemon, so restarts across host reboots need a systemd unit |
| Kubernetes | Pod restartPolicy (Always, OnFailure, Never); the kubelet restarts with "an exponential backoff delay (10s, 20s, 40s, …), that is capped at 300 seconds (5 minutes)", reset after 10 minutes of trouble-free running |
| systemd | Restart=on-failure with RestartSec; Docker's docs recommend restart policies over process managers for containers |
Fix / how to use it: long-running services unless-stopped (or always if a manual stop must not survive a reboot); one-shot jobs no or on-failure:N; make fatal errors exit non-zero so the policy can act; watch restarts with docker events and the RestartCount.
Configuration: env and env-file Must-know
In plain words: Environment variables are the standard way to give the same image different settings in different places. -e KEY=value sets one; --env-file file reads many from a file.
Common misunderstanding: "Environment variables are a safe place for passwords." They appear in docker inspect output, in /proc/<pid>/environ for anyone in the container's PID namespace, in crash dumps and in many error reporters; Docker's secrets guide warns they "can also be printed in logs when debugging errors without your knowledge". Use secrets for credentials.
Definition: -e VAR=value sets a value; -e VAR without = copies the value from the client's environment, and if the variable is not exported locally, it "is unset in the container". An env file has VAR=value or VAR lines and # comment lines; "a # appearing anywhere else in a line is treated as part of the variable value". Values set at run time override the image's ENV. In Compose, environment: beats env_file:, and both beat the image ENV; docker compose run -e beats everything (see Env interpolation for the separate question of ${VAR} in the YAML).
Image: ENV LOG_LEVEL=info
Run: docker run --env-file prod.env -e LOG_LEVEL=debug -e TZ orders-api
1 daemon starts with the image env: LOG_LEVEL=info
2 --env-file prod.env is applied: DB_ADDR=db:5432, LOG_LEVEL=warn
3 -e LOG_LEVEL=debug wins (later, explicit): LOG_LEVEL=debug
4 -e TZ: client exports TZ=Europe/Berlin -> TZ=Europe/Berlin; not exported -> TZ unsetReal scenarios: one image promoted from staging to production with a different --env-file; a DB_HOST=localhost copied from a laptop .env that makes the container talk to itself; a value with a # (a password, a colour) truncated by a different tool's parser; a Laravel APP_KEY passed as an env var and visible to everyone who can run docker inspect.
| Product | How environment is set |
|---|---|
| Docker CLI | -e, --env, --env-file (no interpolation inside the file) |
| Docker Compose | environment: (map or list), env_file: (list, required:, format: raw), interpolation with ${VAR} |
| Kubernetes | env, envFrom a ConfigMap or Secret; Secrets can also be files |
| Laravel | .env read by phpdotenv when no real environment variable is set; config:cache freezes values |
| Go | os.Getenv, os.LookupEnv (distinguishes empty from unset) |
Fix / how to use it: non-secret settings in environment: / --env-file; secrets as files; containers never read localhost for another service (use the service name); check the final environment in the Config.Env field of docker inspect <c> (or docker compose config for Compose).
Ports publish, expose vs publish Must-know
In plain words: Publishing (-p, ports:) opens a door on the host that leads to a port in the container. Exposing (EXPOSE, --expose, expose:) only writes on the container "this is the port I listen on".
Common misunderstanding: "My firewall protects published ports." On Linux, Docker writes its own iptables rules for published ports. The reference's note: with -p 80:80 Docker "publishes the port on all interfaces (address 0.0.0.0) by default. These ports are externally accessible. This also applies if you configured UFW to block this specific port, as Docker manages its own iptables rules." Bind to 127.0.0.1 unless you mean it.
Definition: -p [ip:]hostPort:containerPort[/tcp|udp|sctp], ranges allowed; -p 8080 alone picks a random host port. -P publishes every exposed port to random host ports from the ephemeral range. --expose / EXPOSE add exposed ports without publishing. docker port <c> prints the mapping. Containers on the same network reach each other on the container port, never the host port. With --network host publishing is meaningless: Docker prints WARNING: Published ports are discarded when using host network mode. In Compose, ports: short syntax should be quoted ("8080:80") because of YAML's base-60 numbers, and the long syntax adds host_ip, published, target, protocol, app_protocol and name; Compose's expose: ports "should not be published to the host machine".
compose: api ports "127.0.0.1:8080:8080"; postgres no ports
1 browser on the host -> 127.0.0.1:8080 -> NAT rule -> api container 172.20.0.3:8080
2 api -> postgres:5432 (embedded DNS -> 172.21.0.2) on the backend network, no host port involved
3 laptop on the same Wi-Fi -> 192.168.1.20:8080 -> refused (bound to loopback only)
4 someone adds "5432:5432" to postgres for a GUI client -> 0.0.0.0:5432 now open to the LANReal scenarios: a dev database published as 5432:5432 on a laptop at a conference; two projects both wanting host port 8080 (Bind for 0.0.0.0:8080 failed: port is already allocated); php-fpm's 9000 published "to test it", exposing FastCGI; a reverse proxy container that is the only one with 80:80/443:443.
| Product | Publish / expose behaviour |
|---|---|
| Docker Engine (Linux) | iptables/nftables DNAT; bypasses UFW; userland-proxy for some paths |
| Docker Desktop / OrbStack / Colima | Ports forwarded from the VM to macOS localhost; Colima's port forwarder is ssh (TCP only) by default, grpc experimental for UDP |
| Docker Compose | ports: (publish), expose: (document); docker compose run does not publish unless --service-ports |
| Kubernetes | containerPort is informational like EXPOSE; Services (ClusterIP/NodePort/LoadBalancer) and Ingress publish |
| Podman rootless | Ports below 1024 need net.ipv4.ip_unprivileged_port_start; rootlesskit/pasta forward traffic |
Fix / how to use it: publish only the entry point (proxy or API), bound to 127.0.0.1 on servers behind a proxy; never publish database or FastCGI ports; let services talk over a network by name. The iptables view is in Docker Networking.
Networks: bridge, host, none, user-defined networks and DNS Must-know
In plain words: Every container gets a network stack. On a bridge network it gets a private IP behind NAT; on host it shares the host's stack; on none it has only loopback. User-defined networks add the feature you actually want: containers find each other by name.
Common misunderstanding: "Containers can always reach each other by name." Only on user-defined networks. The bridge driver docs: "Containers on the default bridge network can only access each other by IP addresses, unless you use the --link option, which is considered legacy." Compose always creates a user-defined network (<project>_default), which is why names work there and not with plain docker run.
Definition: Drivers: bridge (default; software bridge, masquerading for outbound traffic, publishing for inbound), host (no isolation of the network stack, no own IP; Linux, and Docker Desktop 4.34+ with a setting), none (only lo), plus overlay, macvlan and ipvlan (multi-host and L2 cases, covered in Docker Networking). Containers on user-defined networks use Docker's embedded DNS server at 127.0.0.11, which resolves container names, service names and --network-alias names and "forwards external DNS lookups to the DNS servers configured on the host". User-defined bridges also isolate stacks from each other, can be attached and detached live (docker network connect), and are configured per network (docker network create --subnet ... --internal). --network container:<name> joins another container's network namespace (the sidecar pattern).
docker network create shop
docker run -d --name db --network shop postgres:18
docker run -d --name api --network shop -e DB_ADDR=db:5432 orders-api
1 api resolves "db": resolver in api -> 127.0.0.11 -> embedded DNS -> 172.22.0.2
2 api resolves "api.example.com": 127.0.0.11 -> host's upstream DNS -> public IP
3 db is re-created: new IP 172.22.0.4; next lookup of "db" returns it; old TCP connections break
4 a container on the default bridge tries "db" -> NXDOMAIN (no embedded DNS there)Real scenarios: a Laravel app on the default bridge with DB_HOST=db that never connects; a monitoring agent that needs --network host to see host interfaces; a batch job that must not reach the internet (--network none, or Compose internal: true); a debugging container attached with --network container:api to run curl localhost:8080 inside the API's namespace.
| Mode | Isolation | DNS by name | Port publishing | Typical use |
|---|---|---|---|---|
default bridge | Per container IP, shared by all unrelated containers | No (only --link) | Yes | Quick one-offs |
| user-defined bridge | Per network | Yes, 127.0.0.11 | Yes | Every multi-container app; Compose default |
host | None for networking | Host's resolver | Ignored (warning) | Network tools, very high port counts, max performance |
none | Total | No | No | Offline batch jobs, untrusted code |
container:<name> | Shares another container's stack | That container's | Not allowed | Sidecars, debugging |
| overlay | Across hosts (Swarm) | Yes | Ingress routing mesh | Swarm services |
Fix / how to use it: one user-defined network per application (Compose does it), split into frontend/backend when a component should not be reachable from the edge, internal: true for networks that need no outbound traffic; reference services by name, never by IP, and make clients reconnect after a peer is re-created.
Resource limits (--memory --cpus --pids-limit) and ulimits Important
In plain words: Without limits a container may use all of the host's memory, CPU and process slots. Limits turn "one bad container takes the host down" into "one bad container gets throttled or killed".
Common misunderstanding: "--memory makes my app use less memory." It caps it. When the cgroup limit is reached the kernel's OOM killer kills a process inside the container (exit code 137, docker inspect shows OOMKilled: true, docker events an oom event). Runtimes that size themselves without the limit (old JVMs, PHP-FPM pm.max_children too high, Go without a GOMEMLIMIT) still need tuning.
Definition: Docker's resource docs: "By default, a container has no resource constraints". Memory: -m/--memory hard limit (minimum 6m), --memory-reservation soft limit applied under contention, --memory-swap total memory+swap (equal to --memory means no swap; unset means as much swap as memory), --memory-swappiness, --oom-kill-disable (only with -m), --oom-score-adj. CPU: --cpus=1.5 equals --cpu-period=100000 --cpu-quota=150000 (CFS bandwidth: throttling, not reservation), --cpu-shares relative weight (default 1024, only under contention), --cpuset-cpus pinning. PIDs: --pids-limit N caps processes and threads (fork bombs, thread leaks). ulimits: --ulimit nofile=1024:1024 sets soft:hard RLIMIT_* values; without a hard value the soft one is used for both, without any value the daemon's default-ulimits apply; nproc is per user across containers, not per container. docker update changes CPU and memory limits on a running container. In Compose: mem_limit, cpus, pids_limit, ulimits: or deploy.resources.limits (cpus, memory, pids); the two forms must agree.
--memory=256m --cpus=1 on a 4-CPU host, Go service under a traffic spike
1 load rises; 4 runnable goroutine threads, quota 100 ms per 100 ms period -> throttled after 100 ms
2 container-aware GOMAXPROCS (module go >= 1.25, or opted in via godebug): min(4 CPUs, limit 1) but never below 2 -> 2
3 heap grows to 250 MiB; with no GOMEMLIMIT the GC is not working towards the 256 MiB cap
4 RSS crosses 256 MiB -> kernel OOM kill inside the cgroup -> exit 137, OOMKilled=true
5 restart policy brings it back; GOMEMLIMIT=230MiB (about 10% headroom) would have made the GC work harder firstReal scenarios: a PHP-FPM container with pm.max_children=50 and 60 MB per worker on a 1 GB limit (OOM under load); a log shipper that leaks threads until --pids-limit stops it; Elasticsearch or a JVM that needs nofile=65536; a noisy neighbour CI job throttled to --cpus=2 so the database on the same host keeps its latency.
| Product | Memory | CPU | Processes / files |
|---|---|---|---|
| Docker Engine | -m, --memory-swap, --memory-reservation | --cpus, --cpu-shares, --cpuset-cpus | --pids-limit, --ulimit |
| Docker Compose | mem_limit / deploy.resources.limits.memory | cpus / deploy.resources.limits.cpus | pids_limit / deploy...pids, ulimits: |
| Kubernetes | resources.limits.memory (OOMKilled), requests for scheduling | limits.cpu (CFS quota), requests.cpu (shares) | PID limits per node/pod; no per-container ulimit field |
| Docker Desktop / Colima / OrbStack | The VM has its own cap (Desktop: memory limit defaults to 50% of the host) | VM CPUs | Inside the VM |
| Go runtime | GOMEMLIMIT (set by you) | Container-aware GOMAXPROCS for language version 1.25+ (or godebug containermaxprocs=1), never below 2 | n/a |
Fix / how to use it: set memory and PID limits on every long-running service, CPU limits where latency of neighbours matters; give the runtime the same numbers (GOMEMLIMIT, FPM pm.max_children, JVM -XX:MaxRAMPercentage); watch docker stats and oom events. The cgroup files behind these flags are in Containers Under the Hood.
Logging drivers and log rotation Important
In plain words: Docker captures what PID 1 writes to stdout and stderr and hands it to a logging driver. The driver decides where logs go and whether old logs are thrown away.
Common misunderstanding: "Docker rotates container logs." Not by default. The default json-file driver keeps everything: the docs say "By default, no log-rotation is performed", and recommend the local driver, which "performs log-rotation by default, and uses a more efficient file format". A chatty container on the default driver will eventually fill /var/lib/docker.
Definition: Drivers include none, local, json-file (default), syslog, journald, gelf, fluentd, awslogs, splunk, etwlogs, gcplogs, plus plugins. json-file options: max-size (default -1, unlimited), max-file (default 1; "Only effective when max-size is also set"), compress (default false). local defaults: max-size 20m, max-file 5, compress true, about 100 MB per container. Set a daemon default in daemon.json (log-driver, log-opts, values as strings) or per container with --log-driver / --log-opt, or in Compose logging:. Changing the daemon default only affects new containers. docker logs works with remote drivers through dual logging (a local cache, by default 5 files of 20 MB). Delivery mode=blocking (default) can stall an app when the driver is slow; mode=non-blocking with max-buffer-size (default 1 MB) drops messages instead.
json-file default, API logs 2 KB per request, 300 requests per second
1 ~600 KB/s -> ~50 GB per day in /var/lib/docker/containers/<id>/<id>-json.log
2 day 3: host disk 100% -> postgres cannot write WAL, Docker cannot create containers
3 fix: daemon.json {"log-driver":"local","log-opts":{"max-size":"10m","max-file":"5"}}
4 restart dockerd; NEW containers rotate; old ones keep json-file until re-created (compose up -d --force-recreate)Real scenarios: a disk-full outage traced to a debug log level left on; centralising logs with fluentd or gelf to Graylog while keeping docker logs through dual logging; journald on systemd hosts so journalctl CONTAINER_NAME=api works; Laravel writing storage/logs/laravel.log inside the container instead of stderr (lost on re-create, never rotated).
| Driver | docker logs works | Rotation | Fits |
|---|---|---|---|
json-file (default) | Yes | Only with max-size | Compatibility, Kubernetes nodes historically |
local | Yes | Yes by default (5 x 20 MB, compressed) | Single hosts, Compose on a server |
journald | Yes | journald's own limits | systemd hosts |
syslog, gelf, fluentd, awslogs, gcplogs, splunk | Through dual logging | At the destination | Central logging |
none | No ("configured logging driver does not support reading") | n/a | Noise you never need |
Fix / how to use it: apps log to stdout/stderr (Go slog JSON, Laravel LOG_CHANNEL=stderr); servers set local or json-file with max-size/max-file in daemon.json (snippet in Solving the classic problems); ship logs centrally for anything beyond one host. The observability concepts are in Logs, Metrics & Traces.
Healthcheck at runtime Important
In plain words: A health check is a command Docker runs inside the container every few seconds; exit 0 means healthy, 1 unhealthy. You can set or override it at run time without rebuilding the image.
Common misunderstanding: "If the health check fails, Docker restarts the container." Docker only records the status (starting, healthy, unhealthy) and emits a health_status event. What uses the status: Compose's depends_on: condition: service_healthy, docker compose up --wait, Swarm (which replaces unhealthy tasks), and your monitoring. Kubernetes ignores HEALTHCHECK entirely and uses its own probes.
Definition: docker run flags --health-cmd, --health-interval, --health-timeout, --health-retries, --health-start-period, --health-start-interval (API 1.44+) and --no-healthcheck override the image's HEALTHCHECK (whose defaults and exit-code rules are in Images & Dockerfiles). The State.Health object in docker inspect shows Status, FailingStreak and the last outputs; Engine 29 adds a .HealthStatus placeholder to docker ps --format. A health command runs inside the container, so it needs its binary there: curl is absent in distroless and Alpine-based images, which is why the Go service ships its own healthcheck subcommand.
--health-cmd='/orders-api healthcheck' --health-interval=10s --health-retries=3 --health-start-period=5s
t=0s start; Status=starting
t=0-5s start period: failures do not count (the app is booting)
t=10s check 1 exit 0 -> Status=healthy; health_status: healthy event
t=40s database gone; /healthz is liveness only -> still healthy (by design)
t=60s app deadlocks; check times out -> FailingStreak 1, 2, 3 -> Status=unhealthy
nothing restarts it; an alert or `docker compose up --wait` in a deploy script must actReal scenarios: a deploy script that runs docker compose up -d --wait and fails the deploy if a service never becomes healthy; a health command using curl that fails forever because the image has no curl; a check that queries the database and turns a database blip into every API container being marked unhealthy at once; overriding a vendor image's slow health check with --health-interval=2s in CI.
| Product | Who acts on health |
|---|---|
| Docker Engine | Records status and events only |
| Docker Compose | depends_on service_healthy; up --wait; ps shows (healthy) |
| Docker Swarm | Replaces unhealthy tasks |
| Kubernetes | Ignores HEALTHCHECK; liveness restarts, readiness removes from Service endpoints, startup probes gate both |
| Amazon ECS | Container healthCheck in the task definition; unhealthy essential containers stop the task |
| Podman | Runs HEALTHCHECK; --health-on-failure=none/kill/restart/stop (default none) acts on an unhealthy transition |
Fix / how to use it: liveness checks the process only (/healthz), readiness checks dependencies (/readyz); a check binary that exists in the image; Compose healthchecks on every dependency that others wait for; act on unhealthy with Compose waits, Swarm or an orchestrator, not by hoping Docker restarts it.
Operating a running container: exec, logs, inspect, stats, events Must-know
In plain words: Five commands answer almost every "what is this container doing?" question: run a command inside it, read its output, read its configuration and state, watch its resource use, and watch what the daemon did to it.
Common misunderstanding: "docker exec runs in a copy of the container." It runs a new process inside the same namespaces and filesystem as PID 1; whatever you change there is changed in the running container (and lost on re-create). Also, it "only runs while the container's primary process (PID 1) is running", and a chained command needs a shell: docker exec c sh -c "a && b", not docker exec c "a && b".
Definition: docker exec [-it] [-u user] [-w dir] [-e K=V] <c> <cmd> runs an extra process. docker logs [-f] [--since 10m] [--until] [-n 100] [-t] <c> reads the logging driver's stored output. docker inspect <c> prints the full JSON (State, Config, HostConfig, Mounts, NetworkSettings, RestartCount); -f/--format takes a Go template. docker stats [--no-stream] streams CPU %, memory usage/limit, network and block I/O and PIDs (on Linux the CLI subtracts page cache from memory: inactive_file on cgroup v2). docker events [--filter ...] streams daemon events: container create, start, die (with exitCode), kill, oom, health_status, restart, destroy, and image, volume and network events. Also: docker top, docker cp, docker diff, docker port.
Incident: "the API keeps restarting"
1 docker ps -a -> api Restarting (137) 5 seconds ago
2 docker events --since 30m --filter container=api
... container oom ... container die (exitCode=137 ...) ... container restart ...
3 docker inspect -f '{{.State.OOMKilled}} {{.HostConfig.Memory}}' api -> true 268435456
4 docker stats --no-stream api -> MEM USAGE / LIMIT 255MiB / 256MiB
5 docker logs --since 10m api | tail -> last request before the kill
-> memory limit too small for the workload, or a leak: raise the limit, set GOMEMLIMIT, profileReal scenarios: running php artisan tinker with docker compose exec app php artisan tinker; finding which volume a container really mounted in the Mounts array of docker inspect; a monitoring script that alerts on docker events --filter event=oom; copying a heap profile out with docker cp api:/tmp/heap.pprof ..
| Need | Docker | Compose | Kubernetes |
|---|---|---|---|
| Shell or command inside | docker exec -it c sh | docker compose exec svc sh (TTY by default) | kubectl exec -it pod -- sh |
| Output | docker logs -f c | docker compose logs -f svc | kubectl logs -f pod |
| Config and state | docker inspect c | docker compose ps, config | kubectl get pod -o yaml, describe |
| Resource use | docker stats | docker compose stats | kubectl top pod (metrics-server) |
| What happened | docker events | docker compose events | kubectl get events |
Fix / how to use it: keep a runbook of these five; script with --format templates and --no-stream; never "fix" production by editing files through exec, change the image or the configuration instead.
Stop vs kill and stop timeout Must-know
In plain words: docker stop asks politely and waits; docker kill does not ask. The wait is the stop timeout, and it is the whole budget your application has to finish requests and close connections.
Common misunderstanding: "docker stop waited 10 seconds, so my app was shutting down cleanly." Often the opposite: the app never saw the signal (a shell-form CMD makes /bin/sh PID 1, and it "does not pass signals"), Docker waited the full timeout and then sent SIGKILL. A clean stop is fast; a stop that always takes exactly the timeout is a bug.
Definition: docker stop: "The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL." The first signal is STOPSIGNAL from the image, --stop-signal at create time, or docker stop -s. The grace period is docker stop -t N, else the container's --stop-timeout, else the daemon default, "10 seconds for Linux containers, and 30 seconds for Windows containers"; -1 waits forever. docker kill sends SIGKILL by default or any --signal (which may be non-terminal, such as SIGHUP to reload). Compose uses stop_grace_period (default 10 s) and stop_signal, and docker compose down -t / stop -t. Exit code 143 means the process died of SIGTERM (128+15), 137 of SIGKILL (128+9), as in the exitCode=143 / exitCode=137 die events in Docker's events reference.
docker stop api (Go service, shutdownTimeout 8 s, stop timeout 10 s)
t=0.0s daemon -> SIGTERM -> PID 1 /orders-api; signal.NotifyContext cancels ctx
t=0.0s readiness=false; srv.Shutdown stops accepting, waits for in-flight requests
t=0.4s last request done -> "stopped" -> exit 0; die event exitCode=0
docker stop worker (queue:work, job takes 45 s, default 10 s)
t=0s SIGTERM -> Laravel finishes the current job ...
t=10s SIGKILL -> job killed half-way, retried later -> stop_grace_period: 60s fixes itReal scenarios: Laravel queue workers losing in-flight jobs on every deploy; a Go API returning 502s during deploys because the proxy kept sending traffic until the kill; php-fpm stopped with SIGQUIT (its image sets STOPSIGNAL SIGQUIT for a graceful stop); docker kill -s HUP nginx to reload configuration without a restart.
| Runtime | First signal | Grace period | Then |
|---|---|---|---|
| Docker Engine | STOPSIGNAL / --stop-signal, default SIGTERM | -t, --stop-timeout, daemon default 10 s (Linux) | SIGKILL |
| Docker Compose | stop_signal | stop_grace_period (10 s), down -t | SIGKILL |
| Kubernetes | preStop hook, then SIGTERM | terminationGracePeriodSeconds; the pod docs: a term that "defaults to 30 seconds" | SIGKILL |
| systemd | KillSignal | TimeoutStopSec | SIGKILL |
| Podman | Same as Docker; podman stop -t | 10 s default | SIGKILL |
Fix / how to use it: exec-form entrypoints or exec "$@" in scripts, --init for forking PID 1s, handle SIGTERM in the app, set the app's drain timeout below the stop timeout and raise the stop timeout for long jobs (stop_grace_period: 60s on queue workers).
Volumes: named volumes vs bind mounts vs tmpfs Must-know
In plain words: A mount puts a directory (or file) from somewhere else over a path inside the container. A volume is storage Docker creates and manages; a bind mount is a path from the host; a tmpfs is memory. Inside the container all three look like ordinary directories.
Common misunderstanding: "Mounting a volume shows me the files the image had at that path." Only the first time, and only for an empty volume: Docker's rule is that if you mount an empty volume over existing files "these files or directories are propagated (copied) into the volume by default", while a non-empty volume or any bind mount hides what the image had ("the pre-existing files are obscured by the mount"). That is why a new image version with new files under /app/public keeps showing the old files: the volume is no longer empty.
Definition: Docker's own guidance: "Volumes are the preferred mechanism for persisting data generated by and used by Docker containers." They are managed by the daemon (docker volume create/ls/inspect/rm/prune), work on Linux and Windows containers, are easier to back up and share, and on a Linux host give the same raw performance as the host filesystem; "Directly accessing or interacting with the volume data is unsupported". Anonymous volumes get a random name, are not reused between containers, and are deleted by --rm. Bind mounts link a host path: the host directory "is mounted from the host into a container", processes on both sides can change the files, they are "created to the Docker daemon host, not the client" (a remote daemon cannot see your laptop's files), and with -v a missing source is created as a directory, while --mount fails with bind source path does not exist unless bind-create-src is given. tmpfs lives in memory, counts against the container's memory limit, may be swapped, cannot be shared, and "When the container stops, the tmpfs mount is removed". Image mounts (containerd image store) mount another image read-only. Syntax: --mount type=volume|bind|tmpfs,src=...,dst=...,readonly,... is explicit and supports every option (volume-subpath, volume-nocopy, volume-opt, bind-propagation, bind-recursive, tmpfs-size, tmpfs-mode); -v src:dst:opts is shorter, and "usage of --mount is recommended". SELinux hosts need :z (shared) or :Z (private) relabelling on bind mounts, which --mount cannot do.
docker run -v appdata:/var/www/html/public (image v1 has public/build/app-1.js)
1 volume "appdata" does not exist -> created empty -> image's public/ copied in: app-1.js
2 deploy image v2 (public/build/app-2.js), same volume
3 volume is NOT empty -> no copy -> container sees app-1.js only -> 404 for app-2.js
-> do not put image-owned files (code, built assets) in a volume; mount volumes on data paths only
docker run --mount type=bind,src=./storage,dst=/var/www/html/storage
4 host ./storage owned by uid 1000; container runs as www-data (uid 33) -> "Permission denied"
-> see Permissions belowReal scenarios:
- PostgreSQL's data in
pgdata:/var/lib/postgresql(18+) survivesdocker compose downand image upgrades. - A Go source tree bind-mounted into a dev container so
airrebuilds on save. --read-onlyroot filesystem plus--tmpfs /tmp:size=64m,noexecfor a hardened API.- A shared
logsvolume withvolume-subpath=app1so each container sees only its own subdirectory. - A nginx config file bind-mounted read-only (
./nginx.conf:/etc/nginx/conf.d/default.conf:ro) so edits need only a reload.
| Property | Named volume | Bind mount | tmpfs |
|---|---|---|---|
| Created by | Docker (volume create or first use) | You (host path) | Docker, per container |
Persists after rm | Yes | Yes (host files) | No |
| Initial content | Copied from image path if empty | Host content hides image content | Empty |
| Ownership | From the image path on first copy | Host UID/GID as numbers | uid=, gid=, mode= options |
| Speed on Linux | Native | Native | Memory |
| Speed on Docker Desktop / Colima / OrbStack | Native (inside the VM) | Crosses VirtioFS, gRPC FUSE, sshfs or 9p | Memory |
| Backup | docker run --rm -v vol:/data ... tar | Host backup tools | Not applicable |
| Compose | Top-level volumes: + vol:/path | ./path:/path (relative must start with .) | tmpfs: or type: tmpfs |
| Kubernetes analogue | PersistentVolumeClaim | hostPath (avoid) | emptyDir: {medium: Memory} |
Fix / how to use it: volumes for state the service owns (databases, uploads, queues), bind mounts for things the host owns (source in development, config files, sockets), tmpfs for scratch and secrets in memory; never mount a volume over a path whose content ships in the image; prefer --mount in scripts because a typo fails loudly.
Volume drivers and shared storage Good to know
In plain words: The default local driver stores a volume on the daemon's disk. Other drivers store it somewhere else (NFS, SMB, a block device, a cloud bucket) while the container still just sees a directory.
Common misunderstanding: "An NFS volume makes my database highly available." It makes the files reachable from several hosts; it does not make two database processes safe on the same files, and NFS locking and fsync semantics are a classic source of corruption for PostgreSQL and MySQL. Replicate databases at the database level.
Definition: docker volume create --driver <driver> --opt key=value name, or --mount type=volume,volume-driver=...,volume-opt=.... The built-in local driver accepts mount options: Docker's examples create NFSv3/NFSv4 volumes (volume-opt=type=nfs,volume-opt=device=:/var/docker-nfs,volume-opt=o=addr=10.0.0.10), CIFS/Samba volumes and block devices. Plugin drivers such as rclone/docker-volume-rclone mount remote storage. Compose: volumes: {media: {driver: local, driver_opts: {type: nfs, o: "addr=10.0.0.10,rw,nfsvers=4", device: ":/exports/media"}}}; external: true uses a volume created outside the project.
Two web containers on two hosts, shared uploads via an NFS volume
1 host A: docker volume create --driver local --opt type=nfs --opt o=addr=10.0.0.10,rw,nfsvers=4 --opt device=:/exports/uploads uploads
2 host B: same command -> same server directory mounted
3 user uploads avatar.png through host A -> written to the NFS server -> host B serves it
4 NFS server reboots -> both hosts' writes hang (hard mount) -> uploads return 504
-> object storage (S3-compatible) in the application removes the shared filesystem entirelyReal scenarios: legacy PHP apps that write uploads to disk, moved to two hosts with an NFS volume; a media server mounting a NAS share through CIFS; a backup sidecar writing to an rclone-backed bucket; a Swarm service with an NFS volume declared per node.
| Driver | Where data lives | Notes |
|---|---|---|
local | Daemon disk (/var/lib/docker/volumes) | Default; also NFS/CIFS/block via mount options |
rclone/docker-volume-rclone (plugin) | Any rclone backend (S3, SFTP, ...) | Docker's own example plugin |
| Cloud CSI drivers | EBS, Persistent Disk, Azure Disk | Kubernetes world: Config, Secrets & Storage |
| OrbStack | VM disk, visible under ~/OrbStack/docker | orb docker volume clone for copies |
Fix / how to use it: keep local for single-host state; for shared files prefer object storage in the application; when you must share a filesystem, use NFSv4 with hard mounts for read-mostly content, never for a database's data directory.
Permissions and UID mapping in bind mounts; file ownership issues on macOS and Linux Must-know
In plain words: The Linux kernel checks file permissions by number (UID, GID), not by name. A bind mount shows the container the host's files with the host's numbers. If the container runs as a different number, it cannot write; if it runs as root, it leaves root-owned files on your host.
Common misunderstanding: "It works on my Mac, so the permissions are fine." Docker Desktop, OrbStack and Colima share macOS folders into a Linux VM through a file-sharing layer that maps ownership for you: files usually look writable to whatever UID the container uses, and files the container creates belong to you on the Mac. On a Linux laptop or CI runner there is no VM: the container's UID writes directly to your disk. The same Compose file that worked on macOS then produces Permission denied (container UID 33 cannot write a directory owned by UID 1000) or root-owned vendor/ and storage/ files that your user cannot delete.
Definition: Without user namespaces, container UID n is host UID n. The fixes, in order of preference: (1) run the container as your host user, -u "$(id -u):$(id -g)" or Compose user: "${HOST_UID}:${HOST_GID}" (the shell's UID variable is not exported, so Compose sees nothing unless .env provides it); (2) build a dev image whose service user is renumbered to your IDs (Sail's WWWUSER/WWWGROUP, usermod -u in a dev Dockerfile); (3) make paths group-writable for a shared GID; (4) for volumes (not bind mounts), create the directory in the image with the right owner, so the empty volume copies it (COPY --chown=65532:65532 in the runtime stage). With rootless Docker, the mapping changes: "container UID 0 is mapped to the host UID of the user running rootless Docker", and UID n ≥ 1 maps to subuid + (n - 1), so "files owned by your host user appear as owned by root inside the container". With userns-remap, container UID 0 maps to the first subordinate UID. Compose file-based secrets are bind mounts too: their uid/gid/mode attributes are "silently ignored", so the host file's mode decides whether a non-root service can read /run/secrets/.... On SELinux hosts (Fedora, RHEL) a correct UID still fails until the mount is relabelled with :z/:Z.
Linux CI runner, uid 1001; Laravel dev image runs php-fpm as www-data (uid 33)
1 git checkout -> ./storage owned by 1001:1001, mode 755
2 docker compose up -> app container (uid 33) writes storage/logs/laravel.log -> EACCES
3 "fix": chmod -R 777 storage -> works, but every user on the host can now write it
4 real fix: the Dockerfile's dev stage renumbers www-data to HOST_UID=1001/HOST_GID=1001 from .env
5 container writes as 1001 -> files on the runner are owned by the CI user -> cleanup works
macOS laptop, uid 501, gid 20 (staff)
6 same dev stage: groupmod -g 20 fails because Debian's "dialout" already has GID 20 -> use -oReal scenarios: git clean failing on a Linux workstation because a container created root-owned files; a distroless (UID 65532) service that cannot write a volume Docker created as root because the image had no /data; a rootless-Docker developer whose files appear as root inside the container (correct, by design); a non-root container failing to read a 0600 secret file owned by the deploying user; Podman's --userns=keep-id making the container user match the host user.
| Environment | Who owns files the container writes to a bind mount | Typical fix |
|---|---|---|
| Linux, rootful Docker | Container UID as is (often 0 = root) | user: your UID, or a dev image with renumbered user |
| Linux, rootless Docker | Container root = you; other UIDs map into your subuid range | Run as root inside (it is you), or chown via docker run |
| Linux, Podman rootless | Same subuid model | --userns=keep-id |
| Docker Desktop for Mac (VirtioFS) | Your macOS user | Usually nothing; Linux teammates still need a fix |
| Colima (sshfs / 9p / virtiofs) | Mapped by the mount type; $HOME mounted writable by default | Mount paths outside $HOME explicitly in colima.yaml |
| OrbStack (VirtioFS, tuned) | Your macOS user | Nothing; volumes visible under ~/OrbStack |
| SELinux (Fedora, RHEL) | UID correct but access denied | :z / :Z on -v |
Fix / how to use it: the dev Compose files on this page pass HOST_UID/HOST_GID from .env (written by scripts/dev-env.sh) and either run as that user (Go) or renumber the service user (Laravel); production images run a fixed numeric non-root UID and own their data paths through the image. Deeper user-namespace hardening is in Container Security.
Data persistence, backup of volumes and prune Important
In plain words: Data lives as long as the thing it is stored in. Know which command deletes which thing, back up volumes like any other disk, and treat prune as a delete command.
Common misunderstanding: "docker compose down is safe; down -v is what deletes data." Correct, and the reason people lose data is the other direction: they run docker volume prune -a to free disk space, and every named volume that no container references goes, including the database of a project whose containers were already removed with docker compose down (a stopped container still counts as a reference; docker volume prune "Unused local volumes are those which are not referenced by any containers"). docker system prune --volumes is narrower: it prunes anonymous volumes only. Also: copying files out of a running database volume is not a backup.
Definition: Lifetimes: writable layer = container; anonymous volume = until removed (or --rm); named volume = until docker volume rm, docker compose down -v or a prune; bind mount = never touched by Docker. docker compose down removes the project's containers and networks; "Networks and volumes defined as external are never removed", anonymous volumes are not removed by default but are also not re-attached by the next up. Prune commands: docker container prune (stopped containers), docker image prune [-a], docker network prune, docker builder prune (build cache, including BuildKit cache mounts), docker volume prune ("By default, it only removes anonymous volumes"; -a also named volumes not referenced by any container), docker system prune (all of the above except volumes; --volumes prunes anonymous volumes). Filters such as --filter label=... and until=24h narrow them. Backup: Docker's recipe runs a throwaway container with the volume mounted and tars it to a bind-mounted host directory; restore untars into a new or empty volume. For databases, take a logical dump through the database (pg_dump, mysqldump --single-transaction) or stop the writer first.
Backup and restore of the orders project (scripts/volume-backup.sh, volume-restore.sh)
1 docker compose exec -T postgres pg_dump -U orders -Fc orders > orders.dump (consistent, online)
2 scripts/volume-backup.sh orders_redis-data --stop redis (stop writer, tar, start again)
3 disaster: docker volume rm orders_pgdata
4 docker compose up -d postgres -> new empty volume -> initdb runs -> empty database
5 docker compose exec -T postgres pg_restore -U orders -d orders < orders.dump
6 scripts/volume-restore.sh backups/orders_redis-data-<time>.tar.gz orders_redis-data (refuses non-empty)Real scenarios: an upgrade from postgres:17 to postgres:18 where the volume is still mounted at /var/lib/postgresql/data and the new image's PGDATA is /var/lib/postgresql/18/docker (the 18+ images changed the path; major upgrades need pg_upgrade or dump/restore anyway); a laptop that ran out of disk and a prune -a --volumes that took a month of local data; nightly cron backups of a single-host Compose deployment copied to object storage; migrating a volume to a new host with tar over SSH.
| Command | Containers | Images | Networks | Volumes | Build cache |
|---|---|---|---|---|---|
docker compose down | Project's | No (--rmi) | Project's (not external) | No (-v: named + anonymous) | No |
docker container prune | Stopped | No | No | No | No |
docker volume prune | No | No | No | Unused anonymous (-a: all unused) | No |
docker system prune | Stopped | Dangling (-a: unused) | Unused | Only with --volumes (anonymous) | Yes |
docker builder prune | No | No | No | No | Yes |
Fix / how to use it: label volumes that matter, never run volume prune -a on a host with state you care about (and know that system prune --volumes still deletes unreferenced anonymous volumes), back up with a dump for databases and tar for other volumes, and test restores. The two backup scripts are in the Go section.
Docker Compose v2: compose.yaml, services, project names Must-know
In plain words: Compose turns a list of docker run commands into a YAML file. You describe services, networks and volumes; docker compose up creates or updates them as one project.
Common misunderstanding: "version: "3.8" at the top selects the Compose features." Compose v2 "ignores the version top-level element" and uses the rolling Compose Specification; the key only produces a warning. Another: "Compose v2 is the old docker-compose." docker-compose with a hyphen is v1 (Python, end of life); docker compose is the Go plugin (v2, and v5 since December 2025, which the history page calls "functionally identical to Compose v2" with an official Go SDK).
Definition: The default file is compose.yaml (also accepted: compose.yml, and the legacy docker-compose.yaml/.yml), plus compose.override.yaml if present. Top-level elements: name, services, networks, volumes, secrets, configs, include, extension fields x-*, and (Compose 5.8, experimental) jobs. A service is an abstract component; "All containers within a service are identically created". The project name isolates projects: it prefixes every container, network and volume (orders-api-1, orders_default, orders_pgdata). Precedence: -p, then COMPOSE_PROJECT_NAME, then top-level name:, then the project directory's base name; names "must contain only lowercase letters, decimal digits, dashes, and underscores". Compose labels everything it creates (com.docker.compose.project, com.docker.compose.service) and compares the configuration hash on each up to decide which containers to re-create.
~/code/orders/compose.yaml with name: orders; services api, postgres, redis
1 docker compose up -d
2 creates network orders_frontend, orders_backend; volumes orders_pgdata, orders_redis-data
3 creates containers orders-postgres-1, orders-redis-1, waits for health, then orders-api-1
4 edit api's environment -> docker compose up -d -> only orders-api-1 is re-created (config hash changed)
5 git worktree ~/code/orders-feature, same name: orders -> SAME volumes: two branches share one database
-> COMPOSE_PROJECT_NAME=orders_feature in that worktree's .env gives it its own volumes and networkReal scenarios: CI running each pipeline as -p ci_$CI_PIPELINE_ID so parallel jobs do not collide; a monorepo with include: pulling in a shared infrastructure Compose file; a service name with container_name: set that suddenly cannot be scaled; a team that standardises docker compose config in code review to see the merged model.
| Implementation | Reads Compose files | Notes |
|---|---|---|
Docker Compose v2 / v5 (docker compose) | Compose Specification | Reference implementation; Go; v5 adds an SDK, builds through Bake |
docker-compose v1 | File formats 2.x/3.x | Python, unsupported |
Podman (podman compose) | Through a provider: docker-compose takes precedence, else podman-compose | Thin wrapper around an external tool |
| Podman Desktop | Sets up Compose, shows projects as container groups | GUI on top of a provider |
| OrbStack, Colima, Rancher Desktop | The Docker Compose CLI against their engine | Same files |
| Kubernetes | Not natively; Kompose converts, Compose Bridge generates manifests | Conversion is a starting point, not a deployment strategy |
Fix / how to use it: one compose.yaml per application at the repository root, a top-level name:, no version:, no container_name:; docker compose config before you trust a merged file.
depends_on with conditions, healthcheck in compose Must-know
In plain words: depends_on orders start-up and shutdown inside a project. With a condition it can wait for a dependency to be healthy, or for a one-off task to finish successfully.
Common misunderstanding: "With service_healthy my app never sees the database down." The condition only applies when Compose starts the project. If the database restarts at 3 a.m., Compose is not involved; the application must retry and reconnect. And a service_healthy condition on a dependency without a healthcheck is never satisfied.
Definition: Short syntax (depends_on: [db, redis]): create in dependency order, remove in reverse, and "Compose guarantees dependency services have been started before starting a dependent service". Long syntax per dependency: condition: service_started | service_healthy | service_completed_successfully, restart: true (re-start this service when Compose restarts the dependency, Compose 2.17.0+), required: false (only warn if the dependency is missing, 2.20.0+). Compose's healthcheck: "works in the same way, and has the same default values, as the HEALTHCHECK Dockerfile instruction" and overrides it: test (["CMD", ...], ["CMD-SHELL", "..."], or ["NONE"]), interval, timeout, retries, start_period, start_interval, disable: true. docker compose up --wait waits until services are running or healthy and fails otherwise (--wait-timeout), which makes it the deploy-time gate. Compose 5.x also has pre_start (init containers that run before a service starts) and post_start/pre_stop hooks.
Laravel stack: docker compose up -d --wait
t=0s create mysql, redis (no deps) -> start; Status=starting
t=6s redis healthy (redis-cli ping)
t=24s mysql healthy (mysqladmin ping after first-boot init)
t=24s start migrate -> php artisan migrate --force -> exit 0 at t=27s
t=27s start app (php-fpm) -> started; start web, queue, scheduler (service_started)
t=45s web healthy (/up through nginx + FastCGI) -> --wait returns 0
if migrate exits 1: app is never started, `up` reports the dependency failure, --wait exits non-zeroReal scenarios: an API that crashed on boot because the database was still running initdb; migrations run once per deploy as a service_completed_successfully dependency instead of in every web container's entrypoint; restart: true so the API reconnects after docker compose restart postgres; a health check written with $$ so Compose does not interpolate a shell variable.
| Mechanism | Waits for | Scope |
|---|---|---|
depends_on short | Container started | Compose start-up only |
condition: service_healthy | Dependency's healthcheck healthy | Compose start-up only |
condition: service_completed_successfully | Dependency exited 0 | Compose start-up only |
up --wait | Every service running/healthy | One up command |
| App-level retry with back-off | Whatever the app needs | Always (the real guarantee) |
| Kubernetes | No ordering; readiness probes, init containers, retries | Cluster |
Fix / how to use it: healthchecks on every stateful dependency, service_healthy edges to them, service_completed_successfully for migrations, up --wait in deploy scripts, and connection retry with back-off in the app anyway.
Profiles and override files Important
In plain words: Override files layer changes on top of a base file (dev adds bind mounts, production adds limits). Profiles switch optional services on and off within one model (a database UI, a Vite server, a load generator).
Common misunderstanding: "An override replaces lists." For most sequences Compose appends: "A YAML sequence is merged by appending values from the overriding Compose file". ports, volumes, secrets and configs are merged by a unique key (ports by {ip, target, published, protocol}, the others by target), so a second "80:80" next to "127.0.0.1:8080:80" adds a second published port. command, entrypoint and healthcheck.test are replaced, not appended. To remove or replace explicitly, use the !reset and !override YAML tags.
Definition: Compose reads compose.yaml and, if present, compose.override.yaml; -f a -f b (or COMPOSE_FILE) gives an explicit ordered list, and then the override file is not auto-loaded. Merge rules: mappings merge key by key, sequences append, scalars replace, unique resources merge by key, !reset null / !reset [] clears an attribute, !override replaces a whole value. include: imports another Compose file as a separate sub-project with its own relative paths. Profiles: a service with profiles: [debug] starts only when that profile is enabled (--profile debug, COMPOSE_PROFILES=debug,tools, or --profile "*"); "Services without a profiles attribute are always enabled"; naming a profiled service on the command line (docker compose run tools) starts it and its dependencies without enabling the profile. Profile names match [a-zA-Z0-9][a-zA-Z0-9_.-]+.
Files: compose.yaml (base) + compose.override.yaml (dev) + compose.prod.yaml (prod)
docker compose up
1 load compose.yaml, interpolate -> load compose.override.yaml, interpolate -> merge
2 api.build.target: runtime -> dev (scalar replaced); api.volumes keyed by target: /data replaced, /src added
3 profile "debug" not enabled -> adminer skipped
docker compose -f compose.yaml -f compose.prod.yaml up -d
4 override NOT loaded (explicit -f list); api.build: !reset null -> no build; image from ${API_IMAGE}
5 web.ports: !override ["80:80"] -> the loopback mapping from the base is gone, not duplicatedReal scenarios: a dev override that adds ports to Postgres for a GUI client while the base keeps it private; compose.ci.yaml that swaps volumes for tmpfs so tests start clean; a debug profile with Adminer and Mailpit; an assets profile that runs Vite only for frontend work; a prod file that accidentally keeps the dev bind mount because someone ran docker compose up (auto-loading the override) on the server.
| Need | Tool | Example |
|---|---|---|
| Environment-specific differences | Override file | compose.override.yaml, compose.prod.yaml |
| Optional services | Profile | profiles: [debug] |
| Shared fragments within a file | x-* + YAML anchors | x-laravel: &laravel then <<: *laravel |
| Reuse another project's file | include: | Shared infrastructure stack |
| Inherit one service from another | extends: | extends: {file: common.yaml, service: base} |
| Remove an inherited value | !reset | build: !reset null |
| Replace a list instead of appending | !override | ports: !override ["80:80"] |
Fix / how to use it: base file = what every environment shares and nothing environment-specific; compose.override.yaml = dev only; production via an explicit -f compose.yaml -f compose.prod.yaml (or a COMPOSE_FILE in the server's environment); verify each combination with docker compose -f ... config.
Env interpolation Important
In plain words: ${VAR} inside a Compose file is replaced by Compose before anything runs, using your shell and an .env file. That is a different thing from the environment variables a container receives.
Common misunderstanding: "The .env file is the container's environment." The project-level .env feeds interpolation of the YAML; a container only gets variables listed under environment: or env_file:. (Laravel blurs the line because its own .env is in the same directory and Sail's Compose file uses it for both.) Second trap: an unset variable without a default becomes an empty string with only a warning ("it displays a warning and substitutes the variable with an empty string"), so image: shop:${TAG} quietly becomes shop:.
Definition: Syntax: $VAR, ${VAR}, ${VAR:-default} (default if unset or empty), ${VAR-default} (if unset), ${VAR:?error} / ${VAR?error} (fail), ${VAR:+replacement} / ${VAR+replacement}, nesting such as ${VARIABLE:-${FOO}}; $$ is a literal $ (needed in command: and healthchecks that use shell variables). Other shell features like ${VARIABLE/foo/bar} "are not supported". Sources, highest first: shell environment, --env-file file, else the project directory's .env. Interpolation applies per file before merging, to values not keys, and in .env/env_file files to unquoted and double-quoted values (single-quoted values are literal; format: raw turns it off for an env_file). Container environment precedence: docker compose run -e, then interpolated environment/env_file values, then plain environment, then env_file, then image ENV. docker compose config --environment shows what was used.
.env: TAG=1.4.2 shell: TAG=1.5.0-rc1 exported compose.yaml: image: orders-api:${TAG:-dev}
1 docker compose config -> image: orders-api:1.5.0-rc1 (shell beats .env)
2 unset TAG in the shell -> image: orders-api:1.4.2
3 remove .env too -> image: orders-api:dev (:- default)
4 compose.prod.yaml: image: ${API_IMAGE:?set API_IMAGE} without API_IMAGE
-> Compose stops with an error that names API_IMAGE and prints the text after :? (before touching any container)Real scenarios: a CI job that exported TAG from a previous step and deployed the wrong version; a password with $ in a .env that Compose expanded (use single quotes or $$); HOST_UID=${UID} evaluating to empty because bash does not export UID; required-variable checks (:?) on every production image reference.
| Where the value comes from | Used for | Precedence notes |
|---|---|---|
| Shell environment | Interpolation | Highest for interpolation |
--env-file | Interpolation | Replaces the default .env |
.env in the project directory | Interpolation | Default; project dir = --project-directory, else first -f file's dir |
environment: | Container env | Beats env_file: |
env_file: | Container env | Later files win; required: false to tolerate absence |
Image ENV | Container env | Lowest |
Fix / how to use it: defaults (:-) for dev convenience, required checks (:?) for production identities and digests, $$ for literal dollars, docker compose config in review and CI.
Secrets and configs Important
In plain words: Compose can hand a container a file instead of an environment variable. Secrets appear under /run/secrets/<name>; configs at a path you choose. The application reads the file.
Common misunderstanding: "Compose secrets are encrypted like Swarm or Kubernetes secrets." With plain Docker Compose a file: secret is a read-only bind mount of a file on the host; nothing is encrypted and anyone who can read the host file can read the secret. What you gain is real but different: the value is not in the environment, not in docker inspect, not inherited by child processes and not printed by error pages that dump $_ENV.
Definition: Top-level secrets: sources: file: or environment: (a host variable; not supported by docker stack deploy), or external: on Swarm. A service must be granted each secret explicitly; short syntax mounts it read-only at /run/secrets/<name>, long syntax sets source, target, uid, gid, mode (default 0444) — but those three are only implemented for environment sources; for file sources Compose "uses a bind-mount under the hood which doesn't allow uid remapping". Top-level configs: sources: file, environment, content (inline, interpolated; Compose 2.23.1+) or external; mounted by default at /<config-name>, mode 0444. Many official images read *_FILE variables: the MySQL and PostgreSQL images document that "_FILE may be appended" to their password variables, causing the entrypoint to read the value from a file.
secrets: db_password: file: ./secrets/db_password.txt (host file mode 0600, owner uid 1000)
1 postgres container: entrypoint runs as root, reads /run/secrets/db_password -> OK, then drops to postgres
2 api container (distroless, uid 65532): open /run/secrets/db_password -> EACCES (0600, owner 1000)
3 long syntax `mode: 0440, uid: "65532"` -> silently ignored for file secrets
4 fix: host file 0644 on a single-user dev box, or 0640 with a group the container is in,
or an `environment:` secret (uid/gid/mode honoured), or Swarm/Kubernetes secrets in productionReal scenarios: MYSQL_ROOT_PASSWORD_FILE=/run/secrets/db_root_password keeping the root password out of docker inspect; a Go service implementing the same _FILE convention (code in Go); an nginx config delivered as a config with content: and ${...} interpolation; Laravel reading the database password from /run/secrets/db_password in config/database.php.
| Platform | Secret storage | Delivered as |
|---|---|---|
| Docker Compose (no Swarm) | Host file or host env var, unencrypted | File in /run/secrets (bind mount) |
| Docker Swarm | Raft store, encrypted at rest | tmpfs file in /run/secrets |
| Kubernetes | etcd (encryption at rest optional), external stores via ESO | Env var or volume file |
| BuildKit (build time) | Never stored | RUN --mount=type=secret |
| Laravel | .env / environment by default | Read a file yourself, or a secrets package |
Fix / how to use it: secrets as files, _FILE variants for official images, a small file-reading helper in your app, host secret files with a mode the container UID can read, and an external secret store once you leave a single host (Kubernetes Config, Secrets & Storage).
Build in compose, and the BuildKit link Important
In plain words: A service can say "build me from this Dockerfile" instead of (or as well as) "pull this image". docker compose up --build or docker compose build then runs a BuildKit build per service.
Common misunderstanding: "Compose has its own builder." Compose v2 already used BuildKit; Compose v5 removed the internal builder completely: "build is delegated to Docker Bake (same as docker build command)". Everything about cache, multi-stage targets, secrets and multi-arch is therefore the BuildKit story from Images & Dockerfiles.
Definition: build: accepts a context path or a mapping: context, dockerfile, dockerfile_inline, target, args, secrets, ssh, cache_from, cache_to, additional_contexts, platforms, tags, labels, network, no_cache, pull, provenance, sbom, shm_size, ulimits, extra_hosts, entitlements, privileged. With both image: and build:, the built image gets that name (and docker compose push pushes it); pull_policy: build forces a build. docker compose build --no-cache, --pull, --push and up --build drive it. Since builds go through Bake, docker buildx bake can read the same Compose file.
docker compose up --build api (api.build: {context: ., target: dev})
1 Compose v5 -> Bake: target "api" from compose.yaml -> BuildKit solve with the dev stage
2 BuildKit: cached base layers, cache mounts /cache/mod and /cache/build reused
3 image orders-api:dev-air tagged locally
4 container re-created because the image ID changedReal scenarios: a dev target with tools and a runtime target without them in one Dockerfile; build args for HOST_UID/HOST_GID in a PHP dev image; cache_from: type=registry,... so CI builds through Compose reuse the registry cache; a production host that must never build (build: !reset null, pull_policy: always).
| Tool | Builds with | Notes |
|---|---|---|
| Compose v2 | BuildKit | Compose's own build path |
| Compose v5 | Docker Bake (BuildKit) | Internal builder removed |
docker buildx bake | BuildKit | Reads docker-bake.hcl or Compose files |
| Podman | Buildah | podman compose via provider |
| Kubernetes | Nothing; images come from CI | Build in CI, deploy by digest |
Fix / how to use it: build: with target: per environment in development, never on production hosts; keep cache-friendly Dockerfiles; in CI build with buildx/Bake directly, then reference digests in Compose.
Watch (develop.watch) Important
In plain words: Compose Watch watches your source tree and, per rule, copies changed files into the running container, restarts it, runs a command, or rebuilds and replaces it. It is an alternative to bind-mounting the whole source.
Common misunderstanding: "Watch is a faster bind mount." It is a different mechanism: Compose copies files into the container (so the container needs stat, mkdir and rmdir, and its USER must be able to write the target), applies .dockerignore rules and ignores .git, and only works for services built with build: ("It doesn't track changes for services that rely on pre-built images"). For compiled languages the honest action is rebuild.
Definition: develop.watch is a list of rules with path, action and optionally target, ignore, include, initial_sync, exec. Actions: sync (copy changes, the app hot-reloads itself), rebuild ("Compose automatically builds a new image with BuildKit and replaces the running service container", like up --build <svc>), restart, sync+restart (copy, then restart the container: config files), sync+exec (copy, then run exec.command in the container). Start with docker compose up --watch or docker compose watch (logs separated); superseded dangling images are pruned unless --prune=false. Paths are relative to the project directory and globs are not supported in path; include: "*.go" must be quoted because * starts a YAML alias.
compose.watch.yaml: api develop.watch: rebuild on "*.go" and go.mod
1 save handler.go -> Compose sees a matching change
2 rebuild: BuildKit build (cached deps + cache mounts) -> new image
3 new container replaces the old one -> SIGTERM drain (8 s budget) -> new one healthy
4 laptop: no bind mount, so no macOS file-sharing cost and no UID mismatch; but each save is a container swapReal scenarios: a Vite frontend with sync and hot module reload while the backend uses rebuild; nginx config changes picked up with sync+restart; PHP source synced into an image-based dev container on a slow file share; composer.json changes triggering rebuild while .php files sync.
| Approach | Edit-to-running latency | Works with | Costs |
|---|---|---|---|
| Bind mount + in-container reloader (air, PHP per request) | Instant (file already there) | Any image with tools | macOS file sharing speed; UID issues on Linux |
Watch sync | About a copy | Interpreted code with hot reload | Needs build:, tools in image, writable target |
Watch rebuild | A cached build + restart | Compiled languages | Container replaced each time |
Rebuild by hand (up --build) | Manual | Everything | Slowest feedback |
Fix / how to use it: Go: bind mount + air, or Watch rebuild; PHP: bind mount (PHP reads files per request), or Watch sync when the file share is slow; always ignore vendor/, node_modules/ and build output.
Compose networks and scale Important
In plain words: Each project gets its own network, and every service is reachable by its service name on it. Scaling runs several identical containers behind that one name.
Common misunderstanding: "--scale web=3 load-balances like Kubernetes." Compose starts three containers; DNS for the service name returns their addresses and clients connect to whichever they pick; there is no health-aware load balancer, and published host ports conflict unless you publish a range or put a proxy in front.
Definition: By default Compose creates <project>_default (a user-defined bridge) and attaches every service; each service registers its name with the embedded DNS. The top-level networks: declares more (driver, driver_opts, ipam, internal, attachable, external, name, enable_ipv6), and a service joins with networks: [frontend, backend] (long form adds aliases, ipv4_address, priority). network_mode: host | none | service:<name> | container:<name> bypasses project networks. When a container is re-created it "joins the network under a different IP address but the same name", and existing connections to the old one are closed. Scale with docker compose up --scale queue=3, the scale: attribute or deploy.replicas; container_name: and fixed host ports prevent scaling. docker compose exec --index 2 queue ... targets one replica.
docker compose up -d --scale queue=3
1 containers shop-queue-1, shop-queue-2, shop-queue-3 on shop_backend
2 each runs queue:work against the same Redis queue -> jobs spread across workers (by Redis, not Compose)
3 docker compose up -d --scale web=2 with ports "127.0.0.1:8080:80"
-> second web: Bind for 127.0.0.1:8080 failed: port is already allocated
-> scale workers freely; for HTTP put one proxy (nginx, Traefik, Caddy) in front and scale behind itReal scenarios: queue workers scaled to drain a backlog; a backend network marked internal: true so the database has no route out; an external: true network shared by several projects behind one reverse proxy; a container in network_mode: service:vpn sharing a VPN sidecar's stack.
| Feature | Compose | Kubernetes |
|---|---|---|
| Name-based discovery | Service name on project networks | Service DNS (svc.namespace.svc.cluster.local) |
| Replicas | --scale, scale, deploy.replicas | replicas in a Deployment, HPA |
| Load balancing | DNS round-robin answers, client-side | kube-proxy / Service VIP, Ingress, Gateway API |
| Network isolation | Separate networks, internal: true | NetworkPolicy |
| Rolling update | Not provided (re-create) | Deployment strategy, maxSurge/maxUnavailable |
Fix / how to use it: split frontend/backend, scale stateless workers, put a proxy in front of scaled HTTP services, and move to an orchestrator when you need health-aware balancing or rolling updates.
docker compose up/down/logs/exec and the rest of the CLI Must-know
In plain words: up makes reality match the file, down removes it, logs and exec are the operator's eyes and hands, run is for one-off commands.
Common misunderstanding: "docker compose restart applies my changes to compose.yaml." restart restarts existing containers with their old configuration. up -d is the command that re-creates containers whose configuration or image changed.
Definition: docker compose up [-d] [--build] [--wait] [--watch] [--force-recreate] [--no-deps] [--remove-orphans] [--scale s=n] [--pull always|missing|never] [svc...]; -t is the shutdown timeout for re-created containers; --abort-on-container-exit and --exit-code-from svc turn a project into a test runner. down [-v] [--rmi local|all] [--remove-orphans] [-t]. logs [-f] [--since] [--tail N] [svc]. exec [-T] [-u user] [-w dir] [--index n] svc cmd allocates a TTY by default (-T disables it, needed in scripts and pipes). run [--rm] [--service-ports] [-e] svc cmd starts a new one-off container that does not publish the service's ports unless asked. Also ps, stop, start, restart, pull, push, build, config, cp, top, events, stats, watch, ls (all projects), version.
Daily dev loop for the Laravel stack
1 docker compose up -d # create / update everything
2 docker compose exec app php artisan migrate
3 docker compose exec -T app php artisan test --parallel # -T: no TTY in a pipe or CI
4 docker compose logs -f app queue # tail two services
5 docker compose run --rm app composer require laravel/sanctum
6 docker compose down # keep volumes; down -v wipes the databaseReal scenarios: a CI job running docker compose up --abort-on-container-exit --exit-code-from tests; docker compose exec in a cron script with no terminal, fixed by -T; --remove-orphans cleaning up a service that was renamed; a deploy script using pull then up -d --wait.
| Task | Command |
|---|---|
| Start or update in the background | docker compose up -d |
| Start and fail unless healthy | docker compose up -d --wait |
| Rebuild one service and replace only it | docker compose up -d --build --no-deps api |
| Stop and remove (keep data) | docker compose down |
| Remove including named volumes | docker compose down -v |
| Follow logs | docker compose logs -f --tail 100 api |
| Shell in a running service | docker compose exec app sh |
| One-off command in a new container | docker compose run --rm app php artisan tinker |
| Final merged config | docker compose config |
| List projects on this daemon | docker compose ls |
Fix / how to use it: up -d after every edit, exec for commands in running services, run --rm for one-offs, -T in scripts, down without -v unless you mean to delete data.
Docker Desktop vs Colima vs OrbStack vs Podman Desktop Important
In plain words: Containers need a Linux kernel. On macOS and Windows every tool runs a small Linux VM and forwards the Docker API, ports and your files into it. The tools differ in licence, speed, file sharing and extras.
Common misunderstanding: "My Mac runs containers natively." It runs them in a VM, which is why bind mounts are slower than volumes, why the VM's memory limit caps every container, why file-change events may not arrive, and why --network host means the VM's network (Docker Desktop needs an opt-in setting for host networking since 4.34).
Definition: Docker Desktop bundles Engine, CLI, Compose, Buildx, Kubernetes and more; on Mac the default file sharing is VirtioFS (gRPC FUSE optional), Synchronized file shares cache large trees in the VM and target "large repositories or monorepos with 100 000 files or more"; the VM memory limit "Defaults to 50% of your host's memory". Its licence: free for "Small businesses (fewer than 250 employees AND less than $10 million in annual revenue)", personal use, education and non-commercial open source; larger companies need a paid subscription. Colima ("container runtimes on macOS (and Linux) with minimal setup", on Lima) runs Docker, containerd or Incus; vmType qemu (default) or vz, mount types virtiofs (vz only, fastest), 9p, sshfs, with $HOME mounted writable by default and inotify propagation marked experimental; it registers itself as a Docker context. OrbStack is a proprietary macOS app with its own engine and network stack, VirtioFS "with additional tuning", volumes browsable under ~/OrbStack/docker, Rosetta for amd64 images; commercial use needs a per-user licence. Podman Desktop (a CNCF sandbox project) manages Podman machines, sets up Compose, and works with Kind, Minikube and OpenShift Local; podman compose delegates to docker-compose or podman-compose.
Same Laravel repo, `docker compose up`, first request
Docker Desktop (VirtioFS) bind mount ok; vendor/ (thousands of files) slower than a volume
Docker Desktop + sync file share repo cached on ext4 in the VM -> near-volume speed; .syncignore for big dirs
Colima vmType=qemu, sshfs works; air/Vite may miss changes -> poll, or vmType=vz + virtiofs
OrbStack fast VirtioFS; volumes visible in Finder
Linux laptop (no VM) native speed; UID mapping is your job (see Permissions)Real scenarios: a company over the Docker Desktop threshold moving developers to Colima or OrbStack (paid) or Podman Desktop; a monorepo where composer install in a bind mount takes minutes until vendor/ moves to a named volume or Synchronized file shares; air not reloading on Colima until poll = true; an Apple Silicon team running linux/amd64 images under Rosetta and seeing different behaviour from CI.
| Tool | Engine | Licence (2026) | Mac file sharing | Notes |
|---|---|---|---|---|
| Docker Desktop | Docker Engine in a VM (also WSL 2 on Windows) | Free below 250 employees and $10M revenue; paid above | VirtioFS, gRPC FUSE, Synchronized file shares | Kubernetes, Scout, Model Runner, Enhanced Container Isolation (Business) |
| Colima | Docker, containerd or Incus on Lima | Open source (MIT) | virtiofs (vz), 9p, sshfs | CLI only; Docker context colima |
| OrbStack | Own engine (Docker-compatible) | Free personal; paid commercial per user | Tuned VirtioFS, two-way | Linux machines, Rosetta, domains |
| Podman Desktop | Podman machine (daemonless Podman) | Open source (Apache-2.0) | Podman machine mounts | Compose via provider, Kind/Minikube/OpenShift |
| Rancher Desktop | containerd + nerdctl or dockerd, k3s | Open source | Lima-based | Kubernetes-first |
| Native Linux | Docker Engine / Podman | Open source | None needed | Fastest; rootless option |
Fix / how to use it: pick by licence first, then file-sharing behaviour for your repo size; keep dependencies (vendor/, node_modules/, Go caches) in volumes on macOS; make dev files work on Linux too (UID mapping) so the same compose.yaml serves the whole team.
Rootless Docker Good to know
In plain words: Normally dockerd runs as root and anyone in the docker group can control it, which equals root on the host. Rootless mode runs the daemon and the containers as your own user inside a user namespace.
Common misunderstanding: "Rootless means the container is not root." Inside, the process may still be UID 0; that UID is mapped to your unprivileged host user. What changes is what a container escape can reach. Docker's post-install docs are blunt about the alternative: "The docker group grants root-level privileges to the user."
Definition: Rootless mode "executes the Docker daemon and containers inside a user namespace"; it needs newuidmap/newgidmap and at least 65,536 subordinate IDs in /etc/subuid and /etc/subgid, is installed with dockerd-rootless-setuptool.sh install, runs as a systemd user service, and creates a rootless CLI context (or DOCKER_HOST=unix:///run/user/<uid>/docker.sock). Mapping: container root = your UID, container UID n = subuid + (n - 1). Limitations relevant to this page: ports below 1024 need CAP_NET_BIND_SERVICE on rootlesskit or net.ipv4.ip_unprivileged_port_start; cgroup v2 with systemd delegation is required for resource limits; some storage drivers and network modes differ. userns-remap is the older middle ground: a root daemon, containers in a remapped namespace.
Rootless dev box, user alice uid 1000, /etc/subuid alice:100000:65536
1 docker run -v "$PWD":/src alpine touch /src/a -> container uid 0 -> host uid 1000: file owned by alice
2 docker run -u 33 -v "$PWD":/src alpine touch /src/b -> container uid 33 -> host uid 100032: alice cannot edit b
3 docker run -p 80:80 nginx -> error binding a privileged port (fix: sysctl ip_unprivileged_port_start=80 or port 8080)Real scenarios: shared CI runners where developers must not get root through the Docker socket; a university server where users run their own daemons; Podman's rootless default on Fedora; bind-mount ownership that looks "wrong" but is the mapping working as designed.
| Mode | Daemon runs as | Container UID 0 is | Bind-mount files you own appear as |
|---|---|---|---|
| Rootful Docker | root | host root | Your UID |
userns-remap | root | first subordinate UID | Unmapped (nobody) unless remapped |
| Rootless Docker | you | you | root |
| Podman rootless | you (no daemon) | you | root (--userns=keep-id: your UID) |
Fix / how to use it: consider rootless or Podman for shared Linux hosts and CI; remember that docker group membership is root; the hardening side (capabilities, seccomp, no-new-privileges) is in Container Security.
Context and remote daemons Good to know
In plain words: The docker command is only a client. A context tells it which daemon to talk to: the local socket, a VM, or a server over SSH.
Common misunderstanding: "docker compose up against a remote host uploads my bind-mounted folders." Bind mounts are "created to the Docker daemon host, not the client": ./src:/src refers to ./src on the remote host, which usually does not exist (and -v will create it empty). Remote contexts suit deploying images, not developing with bind mounts.
Definition: A context is "a combination of several properties": name, description, endpoint and TLS info. docker context ls / create / use / inspect / rm; docker context create prod --docker "host=ssh://deploy@203.0.113.10" uses SSH; DOCKER_HOST, DOCKER_CONTEXT, --context and --host override the current context per command. Desktop tools install their own contexts (desktop-linux, colima, orbstack, rootless). Exposing the daemon on TCP needs TLS (DOCKER_TLS_VERIFY, DOCKER_CERT_PATH); an unauthenticated TCP socket is remote root.
docker context create prod --docker "host=ssh://deploy@203.0.113.10"
DOCKER_CONTEXT=prod docker compose -f compose.yaml -f compose.prod.yaml pull
DOCKER_CONTEXT=prod docker compose -f compose.yaml -f compose.prod.yaml up -d --wait
1 CLI opens SSH to the server, talks to its /var/run/docker.sock
2 images pulled ON THE SERVER from the registry (by digest)
3 ./secrets/db_password.txt is read... on the server's filesystem, relative to the project dirReal scenarios: switching between Docker Desktop and Colima with docker context use; a small team deploying a Compose project to one VM over SSH; a CI job pointing DOCKER_HOST at a dind service; Sail on Docker Desktop for Linux needing docker context use default.
| Endpoint | Example | Security |
|---|---|---|
| Local Unix socket | unix:///var/run/docker.sock | Socket permissions (docker group = root) |
| Rootless socket | unix:///run/user/1000/docker.sock | Your user |
| SSH | ssh://deploy@host | SSH keys; daemon stays on a local socket |
| TCP + TLS | tcp://host:2376 | Mutual TLS required |
| Desktop VM | desktop-linux, colima, orbstack contexts | Local only |
Fix / how to use it: SSH contexts for small remote deployments, never a plain TCP socket, and remember every path in the Compose file is resolved on the daemon's host.
Production anti-patterns (compose on prod) Important
In plain words: Compose is a fine way to run a small application on one server. It becomes dangerous when the development setup is copied to production unchanged, or when one server is expected to behave like a cluster.
Common misunderstanding: "Docker says Compose is for production, so the dev file is fine." Docker's production guide lists the changes you need: "Removing any volume bindings for application code", different ports, quieter logging, a restart policy, and "consider defining an additional Compose file, for example compose.production.yaml". To scale beyond one server it points to running Compose apps on a Swarm cluster; most teams pick Kubernetes, ECS or Nomad instead.
Definition: Anti-patterns and their fixes:
| Anti-pattern | Why it hurts | Instead |
|---|---|---|
Dev override auto-loaded on the server (docker compose up with compose.override.yaml present) | Bind-mounted code, dev ports, debug tools in production | Explicit -f compose.yaml -f compose.prod.yaml; no override file on servers |
Building on the server (build: + up --build) | Untested, non-reproducible images; compilers on the host | Build in CI, deploy by digest; build: !reset null |
Tags like :latest | "Same tag, different code" across hosts and rollbacks | image@sha256:... from CI |
Publishing databases and FastCGI (3306:3306, 9000:9000) | Public attack surface, bypasses UFW | No ports: on internal services; internal: true network |
| No log rotation | Disk-full outages | local driver or max-size/max-file |
| No limits | One leak takes the host down | deploy.resources.limits, pids |
Secrets in environment: and in the repo | Leaks through inspect, logs, Git history | Secret files outside Git, _FILE, a secret store |
restart: always as health management | Unhealthy containers stay up; manual stops undone after reboot | unless-stopped, up --wait, an orchestrator for self-healing |
docker compose down -v in a deploy script | Deletes the database | pull + up -d --wait |
| Expecting zero-downtime deploys | up stops the old container before starting the new one | A proxy with two instances (blue/green), or Kubernetes rolling updates |
| One host for everything forever | No failover, no capacity headroom | Managed database, then an orchestrator |
"git pull && docker compose up -d --build" on the production VM
1 git pull brings compose.override.yaml along -> auto-loaded
2 api is built on the VM from whatever is checked out (tests never ran on this image)
3 dev bind mount .:/src replaces the image's code with the working tree
4 postgres gets "5432:5432" from the dev override -> open to the internet
5 json-file default, no rotation -> disk full in three weeksReal scenarios: a startup running its first year on one VM with Compose (fine with the prod file above, backups and monitoring); a staging server that silently ran with the dev override for months; a deploy that dropped all queued jobs because the stop timeout was 10 s; the move to managed PostgreSQL plus Kubernetes once two servers were needed.
Fix / how to use it: the compose.prod.yaml files on this page (digests, no build, unless-stopped, local logs, limits, internal backend network), deploys with pull and up -d --wait, backups of every volume, and an honest threshold for moving to Kubernetes, ECS or Nomad (see In architecture).
Mechanics
What docker compose up does, step by step
docker compose -f compose.yaml -f compose.prod.yaml up -d --wait
1 project directory = dir of the first -f file; project name: -p > COMPOSE_PROJECT_NAME > name: > dir name
2 read .env (or --env-file) for interpolation; shell variables win
3 for EACH file: parse YAML, resolve anchors/x-*, interpolate ${...} (errors for ${X:?msg})
4 merge files in order (mappings merge, sequences append, unique keys for ports/volumes/secrets/configs, !reset/!override)
5 apply profiles (drop disabled services), validate against the Compose Specification
6 create missing networks (<project>_default, ...) and volumes (<project>_pgdata, ...); externals must exist
7 per service: pull (pull_policy) or build (Bake/BuildKit) -> image ID
8 compute a config hash per service; existing container with the same hash -> keep, else re-create
9 create and start in dependency order; wait for service_healthy / service_completed_successfully edges
10 --wait: block until every service is running or healthy, or fail with the first unhealthy onedocker compose config prints the result of steps 1 to 5, which is the fastest way to debug an override or interpolation surprise. Step 8 is why up -d is idempotent and why restart does not apply changes.
What happens to a mount when the container starts
mount type=volume,src=pgdata,dst=/var/lib/postgresql (volume-nocopy not set)
1 volume exists? no -> create /var/lib/docker/volumes/orders_pgdata/_data (local driver)
2 volume empty AND image has content at the target -> copy that content (and its ownership) into the volume
3 bind the volume directory onto the container's rootfs at the target (rprivate propagation)
mount type=bind,src=./src,dst=/src
4 resolve ./src relative to the Compose file / client cwd -> absolute path ON THE DAEMON HOST
5 source missing: -v creates a directory; --mount fails ("bind source path does not exist")
6 bind it; what the image had at /src is hidden; on Docker Desktop the path goes through the VM's file share
mount type=tmpfs,dst=/tmp,tmpfs-size=64m
7 new tmpfs in the container's mount namespace; pages are charged to the container's memory cgroupKnobs
| Knob | Where | Default | Notes |
|---|---|---|---|
--restart | run / Compose restart | no | Back-off 100 ms doubling to 1 min; resets after 10 s up |
--stop-timeout / stop_grace_period | run / Compose | 10 s Linux, 30 s Windows | -1 waits forever |
--stop-signal / stop_signal | run / Compose | image STOPSIGNAL, else SIGTERM | php-fpm images use SIGQUIT |
--memory | run / mem_limit / deploy.resources.limits.memory | unlimited | Minimum 6m |
--memory-swap | run / memswap_limit | twice --memory if swap exists | Equal to --memory disables swap |
--cpus | run / cpus | unlimited | = --cpu-period=100000 --cpu-quota=N*100000 |
--cpu-shares | run / cpu_shares | 1024 | Only under contention |
--pids-limit | run / pids_limit | unlimited (-1) | Counts threads too |
--ulimit | run / ulimits | daemon default-ulimits | soft:hard; nproc is per user |
--log-driver | run / logging.driver / daemon.json | json-file | local recommended |
max-size / max-file (json-file) | --log-opt | -1 / 1 | Strings in daemon.json |
max-size / max-file / compress (local) | --log-opt | 20m / 5 / true | ~100 MB per container |
mode / max-buffer-size | --log-opt | blocking / 1m | non-blocking drops when full |
--health-interval / -timeout / -start-period / -retries / -start-interval | run / healthcheck | image values (30s / 30s / 0s / 3 / 5s in the Dockerfile defaults) | --no-healthcheck disables |
--pull | run | missing | always, never |
--tmpfs options | run / tmpfs: | rw, suid, async documented as defaults | size=, mode=, uid=, gid=, noexec, nosuid |
COMPOSE_PROJECT_NAME / COMPOSE_FILE / COMPOSE_PROFILES | env | dir name / compose.yaml (+override) / none | Set per checkout in .env |
up --wait-timeout | Compose | none | Seconds to wait for healthy |
live-restore | daemon.json | false | Containers keep running while dockerd restarts |
| Docker Desktop memory limit | Desktop settings | 50% of host memory | Caps every container |
Colima vmType / mountType / mountInotify | colima.yaml | qemu / sshfs (virtiofs with vz) / false | Cannot change after VM creation |
Error messages you will actually see
| Message | Meaning | Fix |
|---|---|---|
docker: Error response from daemon: No such image: hello-world:latest. | --pull=never and the image is not local | Pull it, or use missing |
invalid mount config for type "bind": bind source path does not exist: /dev/noexist. | --mount with a missing host path | Create it, or bind-create-src |
WARNING: Published ports are discarded when using host network mode | -p with --network host | Drop -p, or use a bridge network |
Bind for 0.0.0.0:8080 failed: port is already allocated (format string in moby's port allocator) | Host port in use by another container | Another host port, stop the other one |
Error response from daemon: configured logging driver does not support reading | docker logs with --log-driver=none (or a remote driver without dual logging) | Use local/json-file, enable dual logging |
| A permission-denied error from the app or the entrypoint when it writes or executes a file on a bind mount | UID or mode mismatch, or SELinux label | user:, renumbered dev user, :z/:Z |
cannot attach stdin to a TTY-enabled container because stdin is not a terminal (Docker CLI) | docker exec -it / docker run -it in a script or pipe | Drop -t (Docker), -T for docker compose exec |
dependency failed to start: container orders-postgres-1 is unhealthy (Compose dependency_wait.go) | A service_healthy dependency never became healthy | docker compose logs postgres, fix the check or the service |
service "migrate" didn't complete successfully: exit 1 (same file) | service_completed_successfully dependency failed | Read its logs; fix the migration |
Exit code 137, OOMKilled: true | Memory limit reached, kernel OOM kill | Raise the limit, tune the runtime (GOMEMLIMIT, FPM workers) |
Exit code 137 after exactly the stop timeout | The app ignored SIGTERM | Exec form, signal handling, --init |
[8] System error: resource temporarily unavailable | --ulimit nproc reached (per user) | Raise or remove nproc; use --pids-limit per container |
WARNING: No swap limit support (docker info) | Kernel lacks swap accounting | Enable it, or ignore swap limits |
The "TAG" variable is not set. Defaulting to a blank string. (compose-go template.go) | ${VAR} unset without a default | Set it, or use :- / :? |
Go: dev workflow for a Go service (air/hot reload, bind-mounted source, build cache)
The Go service is orders-api from Images & Dockerfiles grown into a Compose citizen: it reads configuration from the environment and secrets from files (_FILE), logs JSON to stdout for the logging driver, separates liveness (/healthz) from readiness (/readyz, which checks the database and Redis by name and that its data volume is writable by its UID), and drains on SIGTERM inside the stop timeout.
Before
The usual first attempt at "Go in Docker for development": one docker run line.
# Before: works once, then fights you
docker run -it -p 8080:8080 -v "$(pwd)":/src -w /src golang:1.27 go run .
# - every container starts with an empty module and build cache: full download and compile each time
# - runs as root: on a Linux host, files it writes into ./ (go build output, generated code) are root-owned
# - no restart on code change: Ctrl-C and run again
# - publishes on 0.0.0.0:8080 (reachable from the LAN)
# - no database: DB_ADDR=localhost:5432 points at the container itself
# - no name, no --rm: a pile of exited containers after a dayAfter
The application side. config.go implements the _FILE convention and refuses ambiguous configuration; checks.go holds the readiness probes; main.go wires the handler, the healthcheck subcommand and the SIGTERM drain:
package main
import (
"errors"
"fmt"
"os"
"strings"
"time"
)
// Config is everything the service reads from its environment. Compose fills
// it from `environment:`, `env_file:` and `secrets:`; `docker run` from -e,
// --env-file and mounted files. Nothing is baked into the image.
type Config struct {
Port string // PORT, default 8080 (matches EXPOSE)
DBAddr string // DB_ADDR host:port, e.g. postgres:5432 (a Compose service name)
RedisAddr string // REDIS_ADDR host:port, e.g. redis:6379
DBPassword string // DB_PASSWORD or the file named by DB_PASSWORD_FILE
DataDir string // DATA_DIR, a volume the service must be able to write
ShutdownTimeout time.Duration // SHUTDOWN_TIMEOUT, must stay below the stop timeout (10 s default)
}
// errBothSet is returned when a value is given both directly and as a file.
var errBothSet = errors.New("set either the variable or its _FILE variant, not both")
// secret implements the `_FILE` convention used by the official postgres and
// mysql images: if NAME_FILE is set, the value is the file's content (a
// Compose secret is mounted at /run/secrets/<name>). One trailing newline,
// which editors add, is removed.
func secret(name string, getenv func(string) string, readFile func(string) ([]byte, error)) (string, error) {
direct, path := getenv(name), getenv(name+"_FILE")
switch {
case direct != "" && path != "":
return "", fmt.Errorf("%s: %w", name, errBothSet)
case path == "":
return direct, nil
}
b, err := readFile(path)
if err != nil {
// A permission error here usually means the secret file on the host is
// not readable by the container's UID: file-based Compose secrets are
// bind mounts and keep the host file's owner and mode.
return "", fmt.Errorf("%s_FILE: %w", name, err)
}
return strings.TrimSuffix(strings.TrimSuffix(string(b), "\n"), "\r"), nil
}
// loadConfig reads the configuration through injected functions so tests do
// not depend on the real environment or filesystem.
func loadConfig(getenv func(string) string, readFile func(string) ([]byte, error)) (Config, error) {
c := Config{
Port: def(getenv("PORT"), "8080"),
DBAddr: getenv("DB_ADDR"),
RedisAddr: getenv("REDIS_ADDR"),
DataDir: def(getenv("DATA_DIR"), "/data"),
ShutdownTimeout: 8 * time.Second,
}
if v := getenv("SHUTDOWN_TIMEOUT"); v != "" {
d, err := time.ParseDuration(v)
if err != nil {
return Config{}, fmt.Errorf("SHUTDOWN_TIMEOUT: %w", err)
}
c.ShutdownTimeout = d
}
pw, err := secret("DB_PASSWORD", getenv, readFile)
if err != nil {
return Config{}, err
}
c.DBPassword = pw
return c, nil
}
func def(v, fallback string) string {
if v == "" {
return fallback
}
return v
}
// loadFromOS is the production wiring.
func loadFromOS() (Config, error) { return loadConfig(os.Getenv, os.ReadFile) }package main
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"time"
)
// check is one readiness probe; it returns nil when the dependency is usable.
type check func(ctx context.Context) error
// tcpCheck dials host:port. It proves the Compose DNS name resolves (embedded
// DNS at 127.0.0.11 on a user-defined network) and something listens; it does
// not prove the database accepts queries. A real service pings with its driver.
func tcpCheck(addr string) check {
return func(ctx context.Context) error {
var d net.Dialer
conn, err := d.DialContext(ctx, "tcp", addr)
if err != nil {
return err
}
return conn.Close()
}
}
// writableCheck creates and removes a file in dir. It fails the way a
// bind mount or volume with the wrong owner fails: EACCES for this UID.
func writableCheck(dir string) check {
return func(ctx context.Context) error {
f, err := os.CreateTemp(dir, ".probe-*")
if err != nil {
return fmt.Errorf("%s not writable by uid %d (owner uid %s): %w", dir, os.Getuid(), ownerUID(dir), err)
}
name := f.Name()
f.Close()
return os.Remove(filepath.Clean(name))
}
}
// runChecks runs every check with a shared deadline and returns the failures
// by name; an empty map means ready.
func runChecks(ctx context.Context, checks map[string]check, timeout time.Duration) map[string]string {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
failed := map[string]string{}
for name, c := range checks {
if err := c(ctx); err != nil {
failed[name] = err.Error()
}
}
return failed
}// Command orders-api is the Go service run by this chapter's Compose files.
// It shows the application side of `docker run` / Compose runtime options:
// configuration from the environment and `_FILE` secrets, logs on stdout for
// the logging driver, liveness and readiness for healthcheck/depends_on, a
// writable-volume check that surfaces UID problems, and a SIGTERM drain that
// finishes before the stop timeout sends SIGKILL.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
func main() {
// `orders-api healthcheck` is the exec-form HEALTHCHECK / Compose
// healthcheck command: the distroless runtime image has no curl or shell.
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
os.Exit(healthcheck(os.Getenv("PORT")))
}
// JSON on stdout: the container's logging driver (json-file, local,
// journald, fluentd...) collects it; never write log files in the container.
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
cfg, err := loadFromOS()
if err != nil {
log.Error("config", "err", err)
os.Exit(2)
}
// SIGTERM is what `docker stop` and `docker compose down` send first.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
ln, err := net.Listen("tcp", ":"+cfg.Port)
if err != nil {
log.Error("listen", "err", err)
os.Exit(1)
}
log.Info("listening", "addr", ln.Addr().String(), "uid", os.Getuid(), "gid", os.Getgid(), "data_dir", cfg.DataDir)
if err := serve(ctx, ln, newHandler(cfg, log, &atomic.Bool{}), cfg.ShutdownTimeout, log); err != nil {
log.Error("shutdown", "err", err)
os.Exit(1)
}
}
// app holds the readiness flag so serve can turn it off before draining.
type app struct {
cfg Config
log *slog.Logger
ready *atomic.Bool
checks map[string]check
}
func newHandler(cfg Config, log *slog.Logger, ready *atomic.Bool) *app {
checks := map[string]check{"data_dir": writableCheck(cfg.DataDir)}
if cfg.DBAddr != "" {
checks["db"] = tcpCheck(cfg.DBAddr)
}
if cfg.RedisAddr != "" {
checks["redis"] = tcpCheck(cfg.RedisAddr)
}
ready.Store(true)
return &app{cfg: cfg, log: log, ready: ready, checks: checks}
}
func (a *app) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/healthz":
// Liveness: the process answers. Never check dependencies here, or a
// database blip restarts every API container at once.
w.Write([]byte("ok\n"))
case "/readyz":
// Readiness: can this instance serve traffic right now?
if !a.ready.Load() {
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
failed := runChecks(r.Context(), a.checks, 2*time.Second)
w.Header().Set("Content-Type", "application/json")
if len(failed) > 0 {
w.WriteHeader(http.StatusServiceUnavailable)
}
json.NewEncoder(w).Encode(map[string]any{"ready": len(failed) == 0, "failed": failed})
default:
http.NotFound(w, r)
}
}
// serve runs the server until ctx is cancelled, then turns readiness off and
// drains in-flight requests for at most timeout. Keep timeout below the
// runtime's stop timeout (Docker: 10 s default, Compose stop_grace_period).
func serve(ctx context.Context, ln net.Listener, a *app, timeout time.Duration, log *slog.Logger) error {
srv := &http.Server{Handler: a, ReadHeaderTimeout: 5 * time.Second}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
select {
case err := <-errc:
return err
case <-ctx.Done():
}
a.ready.Store(false)
log.Info("shutting down", "timeout", timeout.String())
sctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
return err
}
if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
return err
}
log.Info("stopped")
return nil
}
// healthcheck returns 0 when /healthz answers 200 on localhost, 1 otherwise,
// which is the exit-code contract of Docker health checks.
func healthcheck(port string) int {
if port == "" {
port = "8080"
}
c := http.Client{Timeout: 2 * time.Second}
resp, err := c.Get(fmt.Sprintf("http://127.0.0.1:%s/healthz", port))
if err != nil {
return 1
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 1
}
return 0
}//go:build unix
package main
import (
"os"
"strconv"
"syscall"
)
// ownerUID reports the numeric owner of path, which is what matters across a
// bind mount: the kernel compares numbers, not user names.
func ownerUID(path string) string {
fi, err := os.Stat(path)
if err != nil {
return "?"
}
if st, ok := fi.Sys().(*syscall.Stat_t); ok {
return strconv.FormatUint(uint64(st.Uid), 10)
}
return "?"
}The tests cover the _FILE secret (trailing newline, both-set error, missing file), TCP readiness against a live and a closed port, the permission failure on a read-only directory, liveness that ignores dependencies, the healthcheck exit codes, and the drain on cancellation and its timeout:
package main
import (
"context"
"encoding/json"
"errors"
"io"
"io/fs"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
func env(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
func files(m map[string]string) func(string) ([]byte, error) {
return func(p string) ([]byte, error) {
v, ok := m[p]
if !ok {
return nil, &fs.PathError{Op: "open", Path: p, Err: fs.ErrNotExist}
}
return []byte(v), nil
}
}
func TestConfigDefaults(t *testing.T) {
c, err := loadConfig(env(nil), files(nil))
if err != nil {
t.Fatal(err)
}
if c.Port != "8080" || c.DataDir != "/data" || c.ShutdownTimeout != 8*time.Second {
t.Fatalf("defaults: %+v", c)
}
}
func TestSecretFromFileTrimsNewline(t *testing.T) {
c, err := loadConfig(
env(map[string]string{"DB_PASSWORD_FILE": "/run/secrets/db_password"}),
files(map[string]string{"/run/secrets/db_password": "s3cret\n"}),
)
if err != nil {
t.Fatal(err)
}
if c.DBPassword != "s3cret" {
t.Fatalf("password %q", c.DBPassword)
}
}
func TestSecretBothSetIsAnError(t *testing.T) {
_, err := loadConfig(env(map[string]string{"DB_PASSWORD": "a", "DB_PASSWORD_FILE": "/run/secrets/x"}), files(nil))
if !errors.Is(err, errBothSet) {
t.Fatalf("want errBothSet, got %v", err)
}
}
func TestSecretMissingFile(t *testing.T) {
_, err := loadConfig(env(map[string]string{"DB_PASSWORD_FILE": "/run/secrets/missing"}), files(nil))
if !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("want ErrNotExist, got %v", err)
}
}
func TestBadShutdownTimeout(t *testing.T) {
if _, err := loadConfig(env(map[string]string{"SHUTDOWN_TIMEOUT": "eight"}), files(nil)); err == nil {
t.Fatal("want parse error")
}
}
func TestTCPCheck(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
c.Close()
}
}()
if err := tcpCheck(addr)(context.Background()); err != nil {
t.Fatalf("live listener: %v", err)
}
ln.Close()
if err := tcpCheck(addr)(context.Background()); err == nil {
t.Fatal("closed port should fail")
}
}
func TestWritableCheck(t *testing.T) {
dir := t.TempDir()
if err := writableCheck(dir)(context.Background()); err != nil {
t.Fatalf("writable dir: %v", err)
}
if os.Getuid() == 0 {
t.Skip("root ignores directory permissions")
}
ro := filepath.Join(dir, "ro")
if err := os.Mkdir(ro, 0o555); err != nil {
t.Fatal(err)
}
err := writableCheck(ro)(context.Background())
if err == nil || !errors.Is(err, fs.ErrPermission) || !strings.Contains(err.Error(), "not writable by uid") {
t.Fatalf("want permission error naming the uid, got %v", err)
}
}
func testApp(t *testing.T, cfg Config) *app {
t.Helper()
return newHandler(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)), &atomic.Bool{})
}
func TestReadyzReportsFailedDependency(t *testing.T) {
a := testApp(t, Config{DataDir: t.TempDir(), DBAddr: "127.0.0.1:1"})
rec := httptest.NewRecorder()
a.ServeHTTP(rec, httptest.NewRequest("GET", "/readyz", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status %d", rec.Code)
}
var body struct {
Ready bool `json:"ready"`
Failed map[string]string `json:"failed"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Ready || body.Failed["db"] == "" || body.Failed["data_dir"] != "" {
t.Fatalf("body %+v", body)
}
}
func TestHealthzIgnoresDependencies(t *testing.T) {
a := testApp(t, Config{DataDir: t.TempDir(), DBAddr: "127.0.0.1:1"})
rec := httptest.NewRecorder()
a.ServeHTTP(rec, httptest.NewRequest("GET", "/healthz", nil))
if rec.Code != http.StatusOK {
t.Fatalf("liveness must not depend on the database, got %d", rec.Code)
}
}
func TestHealthcheckCommand(t *testing.T) {
a := testApp(t, Config{DataDir: t.TempDir()})
srv := httptest.NewServer(a)
_, port, _ := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://"))
if got := healthcheck(port); got != 0 {
t.Fatalf("live server: exit %d", got)
}
srv.Close()
if got := healthcheck(port); got != 1 {
t.Fatalf("closed server: exit %d", got)
}
}
// TestServeDrainsOnSignal is the SIGTERM path: readiness goes off, the
// in-flight request completes, serve returns nil well inside the timeout.
func TestServeDrainsOnSignal(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
a := testApp(t, Config{DataDir: t.TempDir()})
started, release := make(chan struct{}), make(chan struct{})
a.checks["slow"] = func(ctx context.Context) error { close(started); <-release; return nil }
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- serve(ctx, ln, a, 3*time.Second, slog.New(slog.NewTextHandler(io.Discard, nil))) }()
resp := make(chan int, 1)
go func() {
r, err := http.Get("http://" + ln.Addr().String() + "/readyz")
if err != nil {
resp <- -1
return
}
r.Body.Close()
resp <- r.StatusCode
}()
<-started
cancel() // what SIGTERM does through signal.NotifyContext
time.Sleep(50 * time.Millisecond)
if a.ready.Load() {
t.Fatal("readiness should be off while draining")
}
close(release)
if code := <-resp; code != http.StatusOK {
t.Fatalf("in-flight request got %d", code)
}
if err := <-done; err != nil {
t.Fatalf("serve: %v", err)
}
}
// TestServeGivesUpAfterDeadline shows a too-long drain: the application's own
// deadline passes, Shutdown reports it, serve returns the error and main exits
// 1. Docker's SIGKILL would come later, at the stop timeout, only if the
// process were still alive.
func TestServeGivesUpAfterDeadline(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
a := testApp(t, Config{DataDir: t.TempDir()})
started, never := make(chan struct{}), make(chan struct{})
a.checks["stuck"] = func(ctx context.Context) error { close(started); <-never; return nil }
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- serve(ctx, ln, a, 200*time.Millisecond, slog.New(slog.NewTextHandler(io.Discard, nil)))
}()
go http.Get("http://" + ln.Addr().String() + "/readyz")
<-started
cancel()
if err := <-done; !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want DeadlineExceeded, got %v", err)
}
}module academy/docker-run-volumes-compose
go 1.24
// The language version 1.24 keeps the pre-1.25 GOMAXPROCS defaults
// (containermaxprocs=0, updatemaxprocs=0). Opt in to the container-aware
// default and its periodic updates explicitly; a toolchain of Go 1.25 or
// newer (the image uses 1.27) is needed to build with these settings.
godebug (
containermaxprocs=1
updatemaxprocs=1
)One Dockerfile with a dev target (toolchain plus a pinned air, caches under /cache) and the distroless runtime target; the runtime image creates /data owned by UID 65532 so an empty named volume inherits that owner:
# syntax=docker/dockerfile:1
#
# orders-api for this chapter's Compose files: one Dockerfile, three targets.
# dev golang toolchain + air; source is bind-mounted by compose.override.yaml
# build compiles a static binary (used by runtime)
# runtime distroless, non-root, what compose.yaml and compose.prod.yaml run
# The image side (layers, cache mounts, multi-arch, signing) is the subject of
# /platform/docker-images-dockerfiles; this file keeps only what running needs.
ARG GO_VERSION=1.27
FROM golang:${GO_VERSION}-trixie AS base
WORKDIR /src
# Module and build caches live under /cache so dev can keep them in a named
# volume (go-cache) that survives container re-creation. 1777 lets any UID
# (the HOST_UID that dev runs as) write there; an empty named volume mounted on
# /cache is pre-populated from this directory the first time it is used.
ENV GOMODCACHE=/cache/mod GOCACHE=/cache/build
RUN mkdir -p /cache && chmod 1777 /cache
# ---- dev: hot reload with air (needs Go 1.25+ to install; the image has 1.27) ----
FROM base AS dev
ARG AIR_VERSION=v1.67.4
# /data for the dev volume (api-data-dev); 1777 because dev runs as HOST_UID.
RUN mkdir -p /data && chmod 1777 /data
RUN --mount=type=cache,target=/cache/mod \
--mount=type=cache,target=/cache/build \
GOBIN=/usr/local/bin go install github.com/air-verse/air@${AIR_VERSION}
EXPOSE 8080
CMD ["air", "-c", ".air.toml"]
# ---- build: static binary ----
FROM base AS build
COPY go.mod ./
RUN --mount=type=cache,target=/cache/mod go mod download
COPY . .
RUN --mount=type=cache,target=/cache/mod \
--mount=type=cache,target=/cache/build \
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/orders-api . \
&& mkdir -p /out/data
# ---- runtime ----
FROM gcr.io/distroless/static-debian13:nonroot AS runtime
COPY --from=build /out/orders-api /orders-api
# /data exists in the image and belongs to 65532, so an EMPTY named volume
# mounted there starts with that owner instead of root: the non-root process
# can write to it. (A bind mount keeps the host directory's owner instead.)
COPY --from=build --chown=65532:65532 /out/data /data
USER 65532:65532
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --retries=3 \
CMD ["/orders-api", "healthcheck"]
ENTRYPOINT ["/orders-api"]# air config for the dev target (github.com/air-verse/air, keys from air_example.toml).
# The source tree is bind-mounted at /src; air rebuilds and restarts on change.
root = "."
tmp_dir = "tmp"
[build]
cmd = "go build -o ./tmp/orders-api ."
entrypoint = ["./tmp/orders-api"]
include_ext = ["go"]
exclude_dir = ["tmp", "vendor"]
exclude_regex = ["_test\\.go"]
# fsnotify needs inotify events from the bind mount. Docker Desktop (VirtioFS)
# and OrbStack deliver them; Colima with sshfs/9p mounts does not by default
# (its mountInotify is experimental). If saves are not picked up, poll instead:
poll = false
poll_interval = 500 # ms
delay = 200 # ms, debounce bursts of saves
stop_on_error = true
[log]
time = false# Keep the build context small and the cache stable.
.git
tmp/
secrets/
.env
compose*.yamlThe base Compose file: named volumes, file secret, loopback-only port, healthchecks on every dependency, depends_on with conditions, two networks, a debug profile:
# Base Compose file for orders-api: what every environment shares.
# docker compose up -> this file + compose.override.yaml (dev)
# docker compose -f compose.yaml -f compose.prod.yaml up -d -> production-like
# Secrets are files under ./secrets/ (created by scripts/dev-env.sh, never committed).
name: orders
services:
api:
build:
context: .
target: runtime
image: ghcr.io/acme/orders-api:${TAG:-dev}
environment:
DB_ADDR: postgres:5432 # service name, resolved by Compose's network DNS
REDIS_ADDR: redis:6379
DB_PASSWORD_FILE: /run/secrets/db_password
DATA_DIR: /data
secrets:
- db_password # mounted read-only at /run/secrets/db_password
volumes:
- api-data:/data # named volume: survives `down`, removed by `down -v`
ports:
- "127.0.0.1:${API_PORT:-8080}:8080" # loopback only; never 0.0.0.0 by accident
healthcheck:
test: ["CMD", "/orders-api", "healthcheck"]
interval: 10s
timeout: 2s
retries: 3
start_period: 5s
depends_on:
postgres:
condition: service_healthy # wait for pg_isready, not just "container started"
restart: true # restart api when Compose restarts postgres
redis:
condition: service_healthy
stop_grace_period: 10s # SIGTERM, then SIGKILL after 10 s; the app drains in 8 s
networks: [frontend, backend]
postgres:
image: postgres:18
environment:
POSTGRES_DB: orders
POSTGRES_USER: orders
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
volumes:
# PostgreSQL 18+ images keep PGDATA in /var/lib/postgresql/18/docker,
# so the volume goes on /var/lib/postgresql (17 and older: .../data).
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U orders -d orders"]
interval: 5s
timeout: 3s
retries: 10
start_period: 10s
networks: [backend]
redis:
image: redis:8-alpine
command: ["redis-server", "--appendonly", "yes"]
volumes:
- redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
networks: [backend]
# Only with `--profile debug`: a database UI that never runs by default.
adminer:
image: adminer:5
profiles: [debug]
ports:
- "127.0.0.1:8081:8080"
depends_on: [postgres]
networks: [backend, frontend]
networks:
frontend: {}
backend: {}
volumes:
api-data: {}
pgdata: {}
redis-data: {}
secrets:
db_password:
file: ./secrets/db_password.txtDev loop, option A (auto-loaded): bind-mounted source, air, your UID, module and build cache in a named volume, a separate dev data volume:
# Dev overrides, loaded automatically by `docker compose up` next to compose.yaml.
# Option A of the Go dev loop: bind-mount the source and let air rebuild in place.
services:
api:
build:
target: dev # golang + air instead of distroless
image: orders-api:dev-air
# Run as your host user so files air writes into the bind mount (./tmp) are
# yours on Linux. HOST_UID/HOST_GID come from .env (scripts/dev-env.sh);
# the shell's UID is not exported, so ${UID} would interpolate to "".
user: "${HOST_UID:-1000}:${HOST_GID:-1000}"
working_dir: /src
volumes:
- .:/src # bind mount: edits on the host appear at once
- go-cache:/cache # module + build cache outlive the container
# A separate dev volume: api-data was first populated by the runtime image
# (owner 65532), so HOST_UID could not write to it.
- api-data-dev:/data
healthcheck:
test: ["NONE"] # the dev image has no /orders-api binary
postgres:
ports:
- "127.0.0.1:5432:5432" # psql / GUI clients from the host
volumes:
go-cache: {}
api-data-dev: {}Dev loop, option B: Compose Watch with rebuild:
# Option B of the Go dev loop: no bind mount, Compose Watch rebuilds the image.
# docker compose -f compose.yaml -f compose.watch.yaml watch
# (or: docker compose -f compose.yaml -f compose.watch.yaml up --watch)
# A Go binary must be recompiled anyway, so `rebuild` (= up --build api) is the
# honest action; BuildKit's cache mounts keep each rebuild to seconds.
services:
api:
develop:
watch:
- action: rebuild
path: .
include: "*.go" # quoted: a bare * starts a YAML alias
ignore:
- tmp/
- action: rebuild
path: go.modOne-host production: digest from CI, no build, restart policy, read-only root with tmpfs, local log rotation, limits, internal backend network:
# Production-like overrides for ONE host (a VM, an edge box, a demo server):
# docker compose -f compose.yaml -f compose.prod.yaml up -d --wait
# Images are pulled by digest from CI, never built here. For many hosts,
# rolling updates and self-healing across machines, use Kubernetes instead.
services:
api:
image: ${API_IMAGE:?set API_IMAGE to ghcr.io/acme/orders-api@sha256:...}
build: !reset null # never build on the production host
pull_policy: always
restart: unless-stopped
read_only: true # root filesystem read-only; writes go to /data and /tmp
tmpfs:
- /tmp
logging:
driver: local # rotated by default (5 x 20 MB); json-file is not
options:
max-size: "10m"
max-file: "5"
deploy:
resources:
limits:
cpus: "1.0"
memory: 256m
pids: 256
ulimits:
nofile:
soft: 65536
hard: 65536
postgres:
restart: unless-stopped
shm_size: 256mb
logging:
driver: local
deploy:
resources:
limits:
memory: 1g
redis:
restart: unless-stopped
logging:
driver: local
networks:
backend:
internal: true # postgres and redis get no route to the outside# Copy to .env (scripts/dev-env.sh does it). Compose reads .env for
# INTERPOLATION of compose.yaml (${TAG}, ${API_PORT}...); it is NOT the
# container environment unless a service lists it under env_file.
COMPOSE_PROJECT_NAME=orders
TAG=dev
API_PORT=8080
# Your numeric user and group, so dev containers write host-owned files.
HOST_UID=1000
HOST_GID=1000Scripts shared by both stacks: dev-env.sh writes HOST_UID/HOST_GID and creates secret files; the backup and restore scripts implement Docker's throwaway-container recipe with safety checks:
#!/usr/bin/env bash
# dev-env.sh: prepare a Compose project directory for local development.
# - writes HOST_UID/HOST_GID into .env (Compose interpolation; the shell's
# UID is a non-exported bash variable, so ${UID} would be empty in Compose)
# - creates ./secrets/*.txt with random passwords, readable by the container
# Usage: scripts/dev-env.sh <project-dir> [secret-name ...]
set -euo pipefail
dir=${1:?usage: dev-env.sh <project-dir> [secret-name ...]}
shift
secrets=("$@")
[ ${#secrets[@]} -eq 0 ] && secrets=(db_password)
cd "$dir"
[ -f .env ] || cp .env.example .env
set_var() { # set_var NAME VALUE: replace the line or append it
if grep -q "^$1=" .env; then
sed -i.bak "s/^$1=.*/$1=$2/" .env && rm -f .env.bak
else
printf '%s=%s\n' "$1" "$2" >> .env
fi
}
set_var HOST_UID "$(id -u)"
set_var HOST_GID "$(id -g)"
mkdir -p secrets
for name in "${secrets[@]}"; do
f="secrets/${name}.txt"
if [ ! -s "$f" ]; then
# 24 random bytes, base64, no trailing newline.
head -c 24 /dev/urandom | base64 | tr -d '\n' > "$f"
fi
# File-based Compose secrets are bind mounts: the container sees this file's
# owner and mode. 0644 lets a non-root container UID (65532, www-data) read
# it on a Linux host; on a shared host prefer a group-readable 0640 file
# whose group matches the container's GID.
chmod 0644 "$f"
done
printf 'HOST_UID=%s HOST_GID=%s, secrets: %s\n' "$(id -u)" "$(id -g)" "${secrets[*]}"#!/usr/bin/env bash
# volume-backup.sh: archive a named volume to ./backups/<volume>-<UTC time>.tar.gz
# with a throwaway container (the pattern from Docker's volume docs, using
# tar czf over a read-only mount instead of --volumes-from).
#
# A file copy of a RUNNING database is not a consistent backup. For postgres
# and mysql prefer a logical dump through the service itself:
# docker compose exec -T postgres pg_dump -U orders -Fc orders > orders.dump
# docker compose exec -T mysql sh -c 'mysqldump -u root -p"$(cat /run/secrets/db_root_password)" --single-transaction shop' > shop.sql
# or stop the writer first (--stop <service>), as this script can do.
#
# Usage: scripts/volume-backup.sh <volume> [--stop <compose-service>]
set -euo pipefail
vol=${1:?usage: volume-backup.sh <volume> [--stop <compose-service>]}
svc=""
if [ "${2:-}" = "--stop" ]; then svc=${3:?--stop needs a service name}; fi
docker volume inspect "$vol" > /dev/null # fail early on a typo: no silent empty volume
stamp=$(date -u +%Y%m%dT%H%M%SZ)
mkdir -p backups
out="${vol}-${stamp}.tar.gz"
if [ -n "$svc" ]; then docker compose stop "$svc"; fi
# Restart the writer even if tar fails.
trap '[ -n "$svc" ] && docker compose start "$svc"' EXIT
docker run --rm \
--mount "type=volume,src=${vol},dst=/data,readonly" \
--mount "type=bind,src=$(pwd)/backups,dst=/backup" \
alpine:3.23 \
tar czf "/backup/${out}" -C /data .
echo "backups/${out}"#!/usr/bin/env bash
# volume-restore.sh: restore an archive made by volume-backup.sh into a volume.
# Refuses a non-empty target unless --force, because tar would merge old and
# new files. Ownership and modes inside the archive are preserved (tar runs as
# root in the helper container), so the restored data keeps the UIDs the
# service expects (for example 65532 for the distroless nonroot user).
#
# Usage: scripts/volume-restore.sh <archive.tar.gz> <volume> [--force]
set -euo pipefail
archive=${1:?usage: volume-restore.sh <archive.tar.gz> <volume> [--force]}
vol=${2:?usage: volume-restore.sh <archive.tar.gz> <volume> [--force]}
force=${3:-}
[ -f "$archive" ] || { echo "no such archive: $archive" >&2; exit 1; }
docker volume create "$vol" > /dev/null # no-op if it exists
entries=$(docker run --rm --mount "type=volume,src=${vol},dst=/data" alpine:3.23 \
sh -c 'ls -A /data | wc -l')
if [ "$entries" -ne 0 ] && [ "$force" != "--force" ]; then
echo "volume $vol is not empty ($entries entries); stop its services and pass --force" >&2
exit 1
fi
dir=$(cd "$(dirname "$archive")" && pwd)
docker run --rm \
--mount "type=volume,src=${vol},dst=/data" \
--mount "type=bind,src=${dir},dst=/backup,readonly" \
alpine:3.23 \
tar xzf "/backup/$(basename "$archive")" -C /data
echo "restored $archive into $vol"The daemon-wide defaults for a server (rotation by default, live-restore, a sane nofile):
{
"log-driver": "local",
"log-opts": {
"max-size": "10m",
"max-file": "5"
},
"live-restore": true,
"default-ulimits": {
"nofile": {
"Name": "nofile",
"Hard": 65536,
"Soft": 65536
}
}
}The Go angle
- CPU limits and
GOMAXPROCS. Go 1.25 added container-aware defaults: "On Linux, the runtime considers the CPU bandwidth limit of the cgroup". The runtime's own documentation (runtime/debug.go) adds three rules that matter here. It is tied to the module's language version:GODEBUG=containermaxprocs=0andupdatemaxprocs=0are the default "for language version 1.24 and below", so ago 1.24module built by a 1.27 toolchain keeps the oldruntime.NumCPU()default. The value is the minimum of CPU count, affinity and quota/period, but the runtime "will never set GOMAXPROCS less than 2 unless the logical CPU count or CPU affinity mask count are below 2", and a fractional limit "rounds up to the next whole number" (--cpus=1.5gives 2). This chapter'sgo.modstaysgo 1.24and opts in with agodebugblock;go version -mon the built binary showscontainermaxprocs=1,updatemaxprocs=1(without the block:0, see the Lab). SettingGOMAXPROCSyourself disables both the default and the updates. - Memory limits and
GOMEMLIMIT. The Go GC guide recommends using the memory limit when the program runs in "containers with a fixed amount of available memory", and "a good rule of thumb is to leave an additional 5-10% of headroom to account for memory sources the Go runtime is unaware of":GOMEMLIMIT=230MiBfor--memory=256m. Without it, the GC is paced only byGOGCand the first sign of pressure can be exit 137. - Signals and the stop budget.
signal.NotifyContextturns SIGTERM into a cancelled context;serveflips readiness off and callssrv.Shutdownwith 8 s, below Docker's and Compose's 10 s default. The tests show both outcomes: a clean drain, andcontext.DeadlineExceededwhen a request outlives the budget. In that second case the application gives up at 8 s,servereturns the error andmainexits 1; Docker's SIGKILL would only arrive at the 10 s stop timeout if the process were still running. - Liveness vs readiness.
/healthznever touches dependencies, so the Composehealthcheck(and later a Kubernetes liveness probe) does not restart every replica when Postgres blips;/readyzdoes, and is what a proxy or a Kubernetes readiness probe should use. - Config from the environment and files.
os.Getenvfor settings,os.ReadFilefor/run/secrets/...; the_FILEconvention matches the official postgres and mysql images, so onesecrets:entry feeds both the database and the service. - The dev loop. air needs Go 1.25+ to install (its README) and is installed into the
devimage only, pinned (v1.67.4), never added togo.mod.GOMODCACHE/GOCACHEunder/cachein a named volume keep rebuilds incremental across container re-creation;poll = truein.air.tomlis the switch for file shares that do not deliver inotify events (Colima sshfs/9p). Option B (Watchrebuild) avoids bind mounts entirely and relies on BuildKit cache mounts instead. - Connection pools per replica. Every scaled API container opens its own
database/sqlpool; ten replicas withSetMaxOpenConns(20)can open 200 connections. Size pools against the database's limit (Connection Pooling). - Build flags, Makefiles and multi-binary layouts: Project Layout, Linting & Build.
Laravel: dev workflow for Laravel (Sail, php-fpm + nginx + mysql + redis, artisan in exec)
Before
A hand-rolled Compose file that many Laravel projects start with:
# Before: one container doing everything, every port published, data in the container
services:
app:
image: php:8.4-cli
working_dir: /var/www/html
volumes:
- .:/var/www/html # runs as root: root-owned storage/ and vendor/ on Linux hosts
command: php artisan serve --host=0.0.0.0 --port=8000 # dev server, single process
ports:
- "8000:8000" # 0.0.0.0
depends_on: [mysql] # "started", not "ready": first boot fails to connect while MySQL initialises
mysql:
image: mysql:latest # moving tag
environment:
MYSQL_ROOT_PASSWORD: secret # in the environment and in Git
ports:
- "3306:3306" # database open to the network
# no volume: the database lives in the container layer and dies with `down`After
The base file: nginx in front of php-fpm, queue worker and scheduler from the same image, migrations as a one-off dependency, MySQL and Redis with healthchecks and named volumes, secrets as files, an FPM pool config with inline content:
# Laravel 13 on php-fpm + nginx + mysql + redis, plus queue worker, scheduler
# and a one-off migrate service. Copy compose*.yaml and docker/ into the root
# of a Laravel project (the directory with artisan); images are built from
# docker/php/Dockerfile there (targets `app` = php-fpm, `web` = nginx, `dev`).
# docker compose up -> this file + compose.override.yaml (dev)
# docker compose -f compose.yaml -f compose.prod.yaml up -d --wait
name: shop
# Extension field + YAML anchor: one definition for every PHP container.
x-laravel: &laravel
image: ghcr.io/acme/shop-app:${TAG:-dev}
build:
context: .
dockerfile: docker/php/Dockerfile
target: app
env_file:
- path: .env # Laravel's own .env doubles as Compose's interpolation file
required: true
# Real environment variables override the app's .env (Laravel configuration docs),
# so the stack's wiring does not depend on what .env says.
environment:
DB_CONNECTION: mysql
DB_HOST: mysql # Compose service names, not localhost
DB_PORT: "3306"
DB_DATABASE: ${DB_DATABASE:-shop}
DB_USERNAME: ${DB_USERNAME:-shop}
REDIS_HOST: redis
CACHE_STORE: redis
SESSION_DRIVER: redis
QUEUE_CONNECTION: redis
LOG_CHANNEL: stderr # logs to the logging driver, not storage/logs
secrets:
- db_password # exported as DB_PASSWORD by docker/php/secret-env.sh
networks: [backend]
services:
web:
image: ghcr.io/acme/shop-web:${TAG:-dev}
build:
context: .
dockerfile: docker/php/Dockerfile
target: web
ports:
- "127.0.0.1:${APP_PORT:-8080}:80"
depends_on:
app:
condition: service_started # php-fpm has no HTTP endpoint to probe
healthcheck:
# /up passes through nginx and FastCGI, so it tests both containers.
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/up"]
interval: 15s
timeout: 3s
retries: 3
start_period: 20s
networks: [frontend, backend]
app:
<<: *laravel
expose:
- "9000" # FastCGI for nginx only; never published to the host
configs:
- source: fpm_pool
target: /usr/local/etc/php-fpm.d/zz-pool.conf
depends_on:
mysql:
condition: service_healthy
redis:
condition: service_healthy
migrate:
condition: service_completed_successfully
queue:
<<: *laravel
command: ["php", "artisan", "queue:work", "--max-time=3600"]
stop_grace_period: 60s # let the current job finish before SIGKILL
depends_on:
app:
condition: service_started
scheduler:
<<: *laravel
command: ["php", "artisan", "schedule:work"]
depends_on:
app:
condition: service_started
# Runs once per `up` and exits 0; app waits for it. Not restarted.
migrate:
<<: *laravel
command: ["php", "artisan", "migrate", "--force"]
restart: "no"
depends_on:
mysql:
condition: service_healthy
mysql:
image: mysql:8.4
environment:
MYSQL_DATABASE: ${DB_DATABASE:-shop}
MYSQL_USER: ${DB_USERNAME:-shop}
MYSQL_PASSWORD_FILE: /run/secrets/db_password
MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
secrets: [db_password, db_root_password]
volumes:
- mysql-data:/var/lib/mysql
healthcheck:
# $$ stops Compose interpolation; the container's shell expands it.
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u root -p\"$$(cat /run/secrets/db_root_password)\" --silent"]
interval: 5s
timeout: 5s
retries: 20
start_period: 30s
networks: [backend]
redis:
image: redis:8-alpine
command: ["redis-server", "--appendonly", "yes"]
volumes:
- redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
networks: [backend]
networks:
frontend: {}
backend: {}
volumes:
mysql-data: {}
redis-data: {}
secrets:
db_password:
file: ./secrets/db_password.txt
db_root_password:
file: ./secrets/db_root_password.txt
configs:
fpm_pool:
content: |
[www]
pm = dynamic
pm.max_children = ${FPM_MAX_CHILDREN:-10}
pm.max_requests = 500Dev overrides: source bind-mounted, a dev PHP image with www-data renumbered to your UID/GID, queue:listen instead of queue:work, stock nginx with the config mounted, Mailpit, Vite behind a profile:
# Dev overrides (auto-loaded): source bind-mounted, your UID inside, mail catcher.
# The bind mount provides the code and vendor/ (composer create-project ran on the host).
x-laravel-dev: &laravel-dev
image: shop-app:dev
build:
context: .
dockerfile: docker/php/Dockerfile
target: dev # replaces the base file's target: app (mappings merge)
args:
HOST_UID: ${HOST_UID:-1000} # from .env (scripts/dev-env.sh)
HOST_GID: ${HOST_GID:-1000}
volumes:
- .:/var/www/html # edit on the host, PHP sees it on the next request
services:
app:
<<: *laravel-dev
queue:
<<: *laravel-dev
# queue:work keeps the booted app in memory and misses code changes;
# queue:listen reloads per job (slower, fine for dev).
command: ["php", "artisan", "queue:listen", "--tries=1"]
scheduler:
<<: *laravel-dev
migrate:
<<: *laravel-dev
web:
image: nginx:1.28-alpine # stock nginx in dev; config and files mounted
build: !reset null
volumes:
- ./public:/var/www/html/public:ro
- ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
mysql:
ports:
- "127.0.0.1:${FORWARD_DB_PORT:-3306}:3306"
mailpit:
image: axllent/mailpit:v1.29
ports:
- "127.0.0.1:8025:8025" # web UI; Laravel sends to mailpit:1025
networks: [backend]
# Vite dev server only when asked: docker compose --profile assets up
node:
image: node:22-alpine
profiles: [assets]
working_dir: /app
user: "${HOST_UID:-1000}:${HOST_GID:-1000}"
command: ["sh", "-c", "npm ci && npm run dev -- --host 0.0.0.0"]
volumes:
- .:/app
ports:
- "127.0.0.1:5173:5173"One Dockerfile for the whole stack (copied into the Laravel project with the Compose files): base with pdo_mysql and phpredis, dev, production vendor/assets/app/web, and a tiny entrypoint that turns the secret file into DB_PASSWORD:
# syntax=docker/dockerfile:1
#
# Images for this chapter's Laravel stack (MySQL + Redis), built from the
# Laravel project root (the directory with artisan and composer.json):
# base php-fpm + the extensions this stack needs (pdo_mysql, phpredis, ...)
# dev base + composer + dev php.ini, www-data renumbered to HOST_UID/HOST_GID
# vendor composer install --no-dev (production dependencies only)
# assets npm ci && npm run build (Vite output in public/build)
# app production php-fpm image: code + vendor + assets, non-root
# web production nginx image: public/ + nginx config
# Layer caching, multi-stage and image hardening are taught in
# /platform/docker-images-dockerfiles; this file keeps what running needs.
ARG PHP_VERSION=8.4
FROM php:${PHP_VERSION}-fpm-trixie AS base
RUN apt-get update \
&& apt-get install -y --no-install-recommends libzip-dev libicu-dev unzip \
&& docker-php-ext-install pdo_mysql zip intl pcntl bcmath opcache \
&& pecl install redis && docker-php-ext-enable redis \
&& apt-get clean
# Laravel has no _FILE convention: export DB_PASSWORD from the Compose secret,
# then hand over to the image's normal entrypoint (exec keeps PID 1 = php-fpm).
COPY --chmod=0755 docker/php/secret-env.sh /usr/local/bin/secret-env
ENTRYPOINT ["secret-env", "docker-php-entrypoint"]
CMD ["php-fpm"]
WORKDIR /var/www/html
# ---- dev: source comes from the bind mount in compose.override.yaml ----
FROM base AS dev
ARG HOST_UID=1000
ARG HOST_GID=1000
RUN cp "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
# -o allows a non-unique ID: macOS users are in group 20 (staff), which is
# already "dialout" in Debian; renumbering www-data must not fail on that.
RUN groupmod -o -g "${HOST_GID}" www-data \
&& usermod -o -u "${HOST_UID}" -g "${HOST_GID}" www-data
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
USER www-data
# ---- vendor: production dependencies ----
FROM base AS vendor
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY . .
RUN composer dump-autoload --optimize --no-dev
# ---- assets: Vite build ----
FROM node:22-alpine AS assets
WORKDIR /app
COPY package*.json ./
# The Laravel skeleton ships package.json; use the lock file once you commit one.
RUN if [ -f package-lock.json ]; then npm ci; else npm install; fi
COPY . .
RUN npm run build
# ---- app: production php-fpm ----
FROM base AS app
RUN cp "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY --from=vendor --chown=www-data:www-data /var/www/html /var/www/html
COPY --from=assets --chown=www-data:www-data /app/public/build /var/www/html/public/build
USER www-data
# ---- web: production nginx in front of app:9000 ----
FROM nginx:1.28-alpine AS web
COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=vendor /var/www/html/public /var/www/html/public
COPY --from=assets /app/public/build /var/www/html/public/build#!/bin/sh
# secret-env: export Compose secrets as the variables Laravel reads, then exec
# the real entrypoint and command (so php-fpm, queue:work... stay PID 1 and get
# SIGTERM/SIGQUIT directly). Laravel reads real environment variables before
# its .env file, so the secret wins over any DB_PASSWORD line in .env.
set -eu
if [ -r /run/secrets/db_password ]; then
DB_PASSWORD=$(cat /run/secrets/db_password)
export DB_PASSWORD
fi
exec "$@"# Build context = the Laravel project root. Keep secrets, local state and
# host-built dependencies out of the images (vendor/ and node_modules/ are
# rebuilt inside the vendor and assets stages).
.git
.env
.env.*
!.env.example
secrets/
vendor/
node_modules/
public/build/
public/hot
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
compose*.yaml# Dev nginx config (bind-mounted read-only). Same shape as the Laravel
# deployment docs' example, with fastcgi_pass to the php-fpm service "app".
server {
listen 80;
server_name _;
root /var/www/html/public;
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass app:9000;
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;
}
location ~ /\.(?!well-known).* {
deny all;
}
}One-host production: digests, no builds, APP_ENV=production / APP_DEBUG=false / LOG_LEVEL=warning regardless of the .env on the server, rotation, limits, two queue replicas, one scheduler, internal backend network:
# One-host production overrides: pinned digests, restart policy, log rotation,
# resource limits, production app settings, nothing built or bind-mounted on the server.
x-prod: &prod
restart: unless-stopped
logging:
driver: local
options:
max-size: "10m"
max-file: "5"
x-laravel-prod: &laravel-prod
<<: *prod
image: ${APP_IMAGE:?set APP_IMAGE to ghcr.io/acme/shop-app@sha256:...}
build: !reset null
pull_policy: always
# Never inherit the dev .env's APP_ENV=local / APP_DEBUG=true: real environment
# variables win over .env, and this mapping merges into the base environment.
environment:
APP_ENV: production
APP_DEBUG: "false"
LOG_LEVEL: warning
services:
web:
<<: *prod
image: ${WEB_IMAGE:?set WEB_IMAGE to ghcr.io/acme/shop-web@sha256:...}
build: !reset null
ports: !override
- "80:80" # all interfaces: restrict with a cloud security group or load balancer (UFW is bypassed)
app:
<<: *laravel-prod
deploy:
resources:
limits: {cpus: "2.0", memory: 1g, pids: 512}
queue:
<<: *laravel-prod
deploy:
replicas: 2 # = docker compose up --scale queue=2
scheduler:
<<: *laravel-prod # exactly one: two schedulers run every task twice
migrate:
<<: *laravel-prod
restart: "no"
mysql:
<<: *prod
deploy:
resources:
limits: {memory: 2g}
redis:
<<: *prod
networks:
backend:
internal: trueWhat the merged production model looks like for one service (expected, not run; shape of docker compose config output, abbreviated):
# APP_IMAGE=ghcr.io/acme/shop-app@sha256:<digest> WEB_IMAGE=... \
# docker compose -f compose.yaml -f compose.prod.yaml config (excerpt)
services:
app:
image: ghcr.io/acme/shop-app@sha256:<digest>
environment:
APP_DEBUG: "false" # from compose.prod.yaml, beats APP_DEBUG=true in .env
APP_ENV: production
CACHE_STORE: redis
DB_CONNECTION: mysql
DB_HOST: mysql
LOG_CHANNEL: stderr
LOG_LEVEL: warning
QUEUE_CONNECTION: redis
# ... plus every variable from env_file .env
logging:
driver: local
options: {max-file: "5", max-size: 10m}
pull_policy: always
restart: unless-stoppedLines to append to the Laravel project's own .env (Compose interpolation values and HOST_UID/HOST_GID):
# Append these lines to the Laravel project's own .env (lab step 8 does it).
# Laravel reads .env (phpdotenv) AND Compose reads it for interpolation of
# ${...} in compose*.yaml. The stack's DB/Redis/queue wiring is set in
# compose.yaml `environment:`, which overrides .env; passwords live in
# ./secrets/*.txt and reach containers as /run/secrets/*.
APP_PORT=8080
DB_DATABASE=shop
DB_USERNAME=shop
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
# Compose-only values
COMPOSE_PROJECT_NAME=shop
TAG=dev
HOST_UID=1000
HOST_GID=1000Laravel has no _FILE convention. The stack uses secret-env.sh above, because real environment variables override .env ("Any variable in your .env file can be overridden by external environment variables"). If you prefer no wrapper, read the file in config/database.php instead (excerpt):
<?php
// config/database.php (excerpt): Laravel has no `_FILE` convention, so read
// the Compose secret mounted at /run/secrets/db_password when it exists and
// fall back to DB_PASSWORD elsewhere (CI, a host without secrets).
// `php artisan config:cache` runs at container start, when the file exists.
$secretFile = '/run/secrets/db_password';
$dbPassword = is_readable($secretFile)
? rtrim((string) file_get_contents($secretFile), "\r\n")
: env('DB_PASSWORD', '');
return [
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'mysql'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'shop'),
'username' => env('DB_USERNAME', 'shop'),
'password' => $dbPassword,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
],
],
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'host' => env('REDIS_HOST', 'redis'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
],
];The Laravel angle
- Sail is Compose. The Laravel 13 docs: "At its heart, Sail is the compose.yaml file and the sail script that is stored at the root of your project."
php artisan sail:installpublishes acompose.yamlwhoselaravel.testservice builds fromvendor/laravel/sail/runtimes/<php version>, bind-mounts.:/var/www/html, mapshost.docker.internal:host-gateway, and passesWWWUSER/WWWGROUPso the container'ssailuser (created with UID 1337, thenusermod -u $WWWUSERat start) matches yours. Sail's runtime runs supervisord withphp artisan serveon port 80, not php-fpm behind nginx: perfect for a laptop, not a production topology.sail up -d,sail stop,sail artisan,sail composer,sail shell,sail root-shell,sail tinkerare thin wrappers overdocker compose up/stop/exec. - artisan in exec. Without Sail the same commands are
docker compose exec app php artisan migrate,docker compose exec app php artisan tinker,docker compose run --rm app composer require ..., anddocker compose exec -T app php artisan testin CI (no TTY).execruns as the image's user (www-data); add-uonly when you mean it, because root-run artisan commands create root-owned cache files understorage/andbootstrap/cache/. - One image, several roles.
app(php-fpm),queue(queue:work --max-time=3600),scheduler(schedule:work) andmigrate(migrate --force) share the YAML anchorx-laravel. Scalequeuefreely; keep exactly onescheduler(two run every task twice, unless tasks useonOneServer(), which needs the database, memcached, dynamodb or redis cache driver and "the same central cache server"). - Workers and code changes. Laravel's queue docs: workers "store the booted application state in memory" and "will not notice changes in your code base after they have been started", so deploys must restart them (
docker compose up -dre-creates them;php artisan queue:restartasks them to exit gracefully). In dev,queue:listenreloads per job. Give workers astop_grace_periodlonger than your longest job. - Logs and writable paths.
LOG_CHANNEL=stderrsends logs to the logging driver; onlystorage/andbootstrap/cache/must be writable, and in development they are on the bind mount (hence the UID mapping), in production inside the image (owned bywww-data) or on a volume for user uploads (storage/app/public). - Config caching.
config:cachefreezesenv()values (includingDB_PASSWORDexported bysecret-env.sh); this stack does not cache in the image. If you cache, do it at container start (the entrypoint in Images & Dockerfiles) or in a release step, never in a build stage without the real environment. - Health.
/upthrough nginx is thewebhealthcheck; php-fpm itself has no HTTP endpoint, which is whywebwaits forappwithservice_startedand the health of the pair is measured atweb. - Ports. Only
webpublishes (127.0.0.1:8080in dev,80behind a firewall in production); php-fpm's 9000 isexposed to the network, never published; MySQL is published only by the dev override, on loopback.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| Data lost on redeploy | Named volumes on data paths | pgdata:/var/lib/postgresql | Survives re-creation | Backups are your job |
| App starts before the DB is ready | Healthchecks + service_healthy + app retries | depends_on: {db: {condition: service_healthy}} | Clean first boot | Only at start-up |
| Root-owned files on Linux hosts | Run as host UID / renumber dev user | user: "${HOST_UID}:${HOST_GID}", usermod -u | Host owns its files | Per-developer .env |
| Disk fills with logs | Log rotation | local driver or max-size/max-file | Bounded disk | Less local history |
| Container eats the host | Limits | --memory, --cpus, --pids-limit | Blast radius contained | Tuning, OOM kills |
| Deploys drop requests or jobs | Signal handling + stop budget | Drain < stop_grace_period; longer grace for workers | Clean stops | Slower deploys |
Secrets visible in inspect | Secret files | secrets: + _FILE | Out of env and logs | Host file permissions |
| Slow bind mounts on macOS | Volumes for dependencies, sync shares, Watch | vendor/ in a volume, Synchronized file shares, develop.watch | Near-native speed | More moving parts |
| Ports exposed to the internet | Loopback binding, no DB ports | 127.0.0.1:8080:8080, internal: true | Smaller attack surface | Proxy needed for public access |
| Two checkouts share a database | Distinct project names | COMPOSE_PROJECT_NAME per checkout | Isolated stacks | More disk |
| Dev settings leak to production | Explicit prod file | -f compose.yaml -f compose.prod.yaml, !reset, !override | Clear separation | Two files to maintain |
| Unhealthy container keeps running | Act on health | up --wait in deploys, watchdog, orchestrator | Failures surface | Not automatic on plain Docker |
Data lost on redeploy
Check what the container writes with docker diff <c> (A/C/D paths in the writable layer); every path that must survive gets a named volume; verify with docker compose down && docker compose up -d before you trust it. For PostgreSQL 18+ images mount at /var/lib/postgresql; the image docs warn that for 17 and below the volume must be at /var/lib/postgresql/data, because mounts at the parent "WILL NOT PERSIST database data when the container is re-created".
First boot fails because the database is still initialising
service_healthy edges plus a real readiness command (pg_isready, mysqladmin ping), and connection retries with back-off in the application for every later outage; in deploy scripts, docker compose up -d --wait.
Root-owned files and permission denied on Linux
Run scripts/dev-env.sh <project> once; it writes HOST_UID/HOST_GID into .env. The Go dev service runs as that user; the Laravel dev image renumbers www-data to it (with -o because macOS GID 20 collides with Debian's dialout). Never chmod -R 777.
Logs fill the disk
Put config/daemon.json (shown in Go) on the server, restart the daemon, re-create containers (docker compose up -d --force-recreate) because existing containers keep their old logging settings; or set logging: per service as in the prod files.
Deploys drop in-flight work
Exec-form entrypoints, SIGTERM handling, a drain shorter than the stop timeout, and longer stop_grace_period for workers. Check with time docker compose stop api: a clean stop is fast; exactly 10 s means SIGKILL.
Bind mounts are slow on macOS
Keep vendor/, node_modules/ and Go caches in named volumes; enable Synchronized file shares (Docker Desktop) for big repos; try OrbStack or Colima with vmType: vz and mountType: virtiofs; or switch interpreted code to Watch sync.
A second checkout or CI job clobbers the first
Give each one its own project name (COMPOSE_PROJECT_NAME=orders_feature, -p ci_$PIPELINE_ID); volumes and networks follow the name.
Choosing
Which mount type
| Data | Mount | Why |
|---|---|---|
| Database files | Named volume | Persistence, native speed, backup with dump |
| Uploaded files on one host | Named volume (or object storage) | Survives deploys; object storage for many hosts |
| Source code in development | Bind mount (or Watch sync) | Edit on the host |
Dependency trees (vendor/, node_modules/) on macOS | Named volume | Avoid file-share overhead |
| Go module and build cache | Named volume (dev), BuildKit cache mount (build) | Warm rebuilds |
| Config files | Bind mount :ro, or Compose configs | Host-owned, reloadable |
| Secrets | Compose secrets (file), tmpfs-backed in Swarm | Not in env |
Scratch, /tmp on read-only roots | tmpfs | No disk writes, cleared on stop |
| Docker socket for tools | Bind mount /var/run/docker.sock (avoid) | Equivalent to root on the host |
Which restart policy
| Workload | Policy | Extra |
|---|---|---|
| Web/API service on one host | unless-stopped | Healthcheck + up --wait in deploys |
| Database on one host | unless-stopped | Backups; longer stop timeout |
| Queue worker | unless-stopped | stop_grace_period > longest job |
| Migration / seed job | no | service_completed_successfully dependency |
| Flaky external integration poller | on-failure:5 | Alert when it gives up |
| CI one-off | no + --rm | --exit-code-from |
| Must come back even after a manual stop | always | Rarely what you want |
Which dev loop
| Stack and host | Loop | Reason |
|---|---|---|
| Go, Linux | Bind mount + air, user: your UID | Instant, native file events |
| Go, macOS (Docker Desktop / OrbStack) | Bind mount + air, caches in a volume | VirtioFS delivers events |
| Go, macOS (Colima sshfs/9p) | air with poll = true, or Watch rebuild | Events may not cross the mount |
| Laravel, any | Sail, or the php-fpm + nginx override here | PHP reads files per request |
Laravel, huge vendor/ on macOS | vendor/ in a volume or Synchronized file shares | File-share overhead |
| Frontend assets | Vite in a profile, or on the host | HMR needs a fast file watcher |
Which desktop runtime
| Situation | Choice | Reason |
|---|---|---|
| Company below Docker's licence thresholds, wants everything | Docker Desktop | Integrated Kubernetes, Scout, Synchronized file shares |
| Large company, no Docker subscription | Colima, Podman Desktop or Rancher Desktop | Open source |
| macOS, performance and battery first, licence budget | OrbStack | Fast file sharing and network |
| Fedora/RHEL, rootless by default | Podman (+ Podman Desktop) | Daemonless, user namespaces |
| Linux workstation | Native Docker Engine (rootless optional) | No VM at all |
In architecture: from a single process to a distributed system
Everything on this page is about one Docker host. The architecture question is how far one host goes, what must change before there are two, and which of these run-time settings survive the move to an orchestrator (most do, under new names).
Monolith: one process, one host, one Compose file
A Laravel monolith on one VM is the case Compose fits best: web + app + queue + scheduler + mysql + redis in one project, the production file from this page, docker compose pull && docker compose up -d --wait per release, nightly dumps to object storage, local log rotation, unless-stopped everywhere. The simplest correct version already needs named volumes for MySQL and uploads, healthchecks with service_healthy, a migrate one-off, secrets as files, loopback or firewall-protected ports, and a stop grace period for workers. Downtime per deploy is a few seconds while web and app are re-created; accept it or put a proxy with two app instances in front.
Modular monolith: one repository, several services, still one host
The codebase grows a Go sidecar (PDF rendering, a websocket gateway) next to the Laravel app. Compose handles it with more services and networks: frontend for the proxy, backend for app-to-sidecar traffic, data (internal) for databases, include: for a shared infrastructure file, profiles for optional tools. Ownership shows up in the file layout (one Compose fragment per module) and in project-wide conventions: one .env contract, one secret directory, one backup script that knows every volume.
Microservices: many images, many teams, an orchestrator
Twenty services do not run on one Compose host. Compose stays as the developer's tool (each team's compose.yaml runs its service plus fakes or real dependencies locally) while production moves to Kubernetes (or ECS, Nomad). The concepts map one-to-one, which is why getting them right in Compose pays off:
Compose (this page) Kubernetes (platform/kubernetes-* chapters)
1 service + replicas / --scale -> Deployment replicas, HPA
2 healthcheck + depends_on service_healthy -> readiness/liveness/startup probes; no start ordering
3 restart: unless-stopped -> restartPolicy Always + CrashLoopBackOff
4 stop_grace_period, SIGTERM -> terminationGracePeriodSeconds, preStop
5 deploy.resources.limits -> resources.requests/limits, QoS classes
6 named volumes -> PersistentVolumeClaims (CSI), StatefulSets
7 secrets/configs files -> Secrets/ConfigMaps as volumes, External Secrets Operator
8 networks + service-name DNS -> Services + CoreDNS, NetworkPolicy
9 logging driver -> node-level log collection (stdout still the contract)
10 compose.prod.yaml digests -> Helm values / Kustomize images, applied by Argo CD or FluxThe pipeline that produces the digests is GitHub Actions or GitLab CI (CI/CD Pipelines); clusters, registries and IAM are usually provisioned with Terraform (Infrastructure as Code); Helm charts and Argo CD are in Packaging for Kubernetes and GitOps. Kompose and Docker's Compose Bridge can convert a Compose file into manifests as a starting point. The architectural reasons to orchestrate at all are in Containers & Kubernetes.
Distributed data: volumes, replicas and state across hosts
A named volume is a directory on one host: it does not replicate, fail over or move. As soon as there are two hosts, state must move out of local volumes or into a system designed to replicate it: managed PostgreSQL/MySQL (or a database operator on Kubernetes), Redis with replication or a managed cache, object storage for uploads instead of an NFS volume. Shared filesystems (NFS, CIFS volume drivers) are acceptable for read-mostly assets and never for a database's data directory. Backups change from "tar a volume" to point-in-time recovery of the managed database. Session and cache state goes to Redis so that any replica can serve any request, which is the precondition for --scale web=3 behind a proxy.
Scaling path: 1x, 10x, 100x
| Scale | Runtime | State | Operations |
|---|---|---|---|
| 1x (one team, one VM) | Compose with base + prod files, unless-stopped, --wait deploys | Named volumes, nightly dumps | local logs, docker events/stats, a disk alert |
| 10x (several services, a few hosts) | Compose per host behind a proxy, or a first managed orchestrator (ECS, a small Kubernetes) | Managed database and Redis; object storage | Central logs (fluentd/gelf/Loki), metrics, digests from CI |
| 100x (many teams, clusters, regions) | Kubernetes with Helm/Kustomize and Argo CD; Compose only for local dev | Operators or managed services, multi-AZ | Policy, autoscaling, progressive delivery (Deployment Strategies) |
Lab
Label: every docker and docker compose command below is expected, not run: no Docker daemon and no Docker labs in this build environment (AUTHORING cost rule). Outputs are either the sample output printed in Docker's own documentation (marked "docs sample" or "docs text"), placeholders in angle brackets, or comments starting with expected: that restate documented behaviour; nothing is presented as captured output that was not captured. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64) and show real output, saved in pipeline/sources/docker-run-volumes-compose/lab-host-output.txt.
1. Build and test the Go service (ran on the host)
From the repository root:
cd docs/snippets/platform/docker-run-volumes-compose/go-service
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ok academy/docker-run-volumes-compose 1.681s2. Prepare a scratch copy for development (ran on the host)
Back at the repository root; the copy keeps generated .env and secret files out of the snippet tree. LAB is any new, empty directory path.
cd - # back to the repository root
cp -R docs/snippets/platform/docker-run-volumes-compose "$LAB" && cd "$LAB"
scripts/dev-env.sh go-service
# HOST_UID=501 HOST_GID=20, secrets: db_password
grep HOST_ go-service/.env
# HOST_UID=501
# HOST_GID=20
ls -l go-service/secrets/ | awk '{print $1, $5, $NF}'
# total 8
# -rw-r--r--@ 32 db_password.txtGID 20 is macOS's staff group; in Debian-based images GID 20 already belongs to dialout, which is why the Laravel dev stage renumbers with groupmod -o.
3. Config from files, readiness, permissions and the SIGTERM drain (ran on the host)
The service runs natively; a five-line Python accept-and-close loop stands in for Postgres and later for Redis. JSON time fields trimmed. The script that ran exactly these commands is saved as pipeline/sources/docker-run-volumes-compose/lab-run-steps-1-3.sh.txt.
cd go-service && go build -o orders-api . && mkdir -p data
go version -m orders-api | grep -o "containermaxprocs=[01]\|updatemaxprocs=[01]"
# containermaxprocs=1
# updatemaxprocs=1 (the godebug block in go.mod; without it both are 0)
LISTEN='import socket,sys; s=socket.socket(); s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1); s.bind(("127.0.0.1",int(sys.argv[1]))); s.listen(8)
while True: s.accept()[0].close()'
python3 -c "$LISTEN" 15432 & PG=$! # fake postgres; nothing on 16379 yet
PORT=18080 DB_ADDR=127.0.0.1:15432 REDIS_ADDR=127.0.0.1:16379 \
DB_PASSWORD_FILE=secrets/db_password.txt DATA_DIR=./data ./orders-api > run1.log 2>&1 & P=$!
curl -s -w ' %{http_code}\n' http://127.0.0.1:18080/healthz
# ok
# 200
curl -s -w ' %{http_code}\n' http://127.0.0.1:18080/readyz
# {"failed":{"redis":"dial tcp 127.0.0.1:16379: connect: connection refused"},"ready":false}
# 503
PORT=18080 ./orders-api healthcheck; echo "exit=$?" # exit=0 (liveness ignores Redis)
kill -TERM $P; wait $P; echo "exit=$?" # exit=0
cat run1.log
# {"level":"INFO","msg":"listening","addr":"[::]:18080","uid":501,"gid":20,"data_dir":"./data"}
# {"level":"INFO","msg":"shutting down","timeout":"8s"}
# {"level":"INFO","msg":"stopped"}
PORT=18081 DB_PASSWORD=x DB_PASSWORD_FILE=secrets/db_password.txt ./orders-api; echo "exit=$?"
# {"level":"ERROR","msg":"config","err":"DB_PASSWORD: set either the variable or its _FILE variant, not both"}
# exit=2
mkdir -p ro && chmod 0555 ro
PORT=18082 DATA_DIR=./ro ./orders-api > run2.log 2>&1 & P2=$!
curl -s -w ' %{http_code}\n' http://127.0.0.1:18082/readyz
# {"failed":{"data_dir":"./ro not writable by uid 501 (owner uid 501): open ./ro/.probe-170516149: permission denied"},"ready":false}
# 503
kill -TERM $P2
PORT=18083 ./orders-api healthcheck; echo "exit=$?" # nothing listening: exit=1
python3 -c "$LISTEN" 16379 & RD=$! # fake redis
PORT=18090 DB_ADDR=127.0.0.1:15432 REDIS_ADDR=127.0.0.1:16379 \
DB_PASSWORD_FILE=secrets/db_password.txt DATA_DIR=./data ./orders-api > run3.log 2>&1 & P3=$!
curl -s -w ' %{http_code}\n' http://127.0.0.1:18090/readyz
# {"failed":{},"ready":true}
# 200
kill -TERM $P3 $PG $RD(The curls to a freshly started process were preceded in the script by a curl --retry 20 --retry-connrefused wait on /healthz.) The read-only directory reproduces, on the host, the message a container gets when a volume or bind mount is owned by another UID.
4. Run options, restarts, networks (expected, not run; outputs are docs samples or expected: lines)
# a process that runs 12 s (past the 10 s "started successfully" mark), then fails
docker run -d --name my-container --restart=on-failure:2 alpine:3.23 sh -c 'sleep 12; exit 1'
sleep 60 # two restarts plus back-off, then on-failure:2 gives up
docker inspect -f "{{ .RestartCount }} {{ .State.Status }} {{ .State.ExitCode }}" my-container
# expected: 2 exited 1
docker run --rm --network none alpine:latest ip link show
# 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000
# link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 (docs sample)
docker run --ulimit nofile=1024:1024 --rm debian sh -c "ulimit -n"
# 1024 (docs sample)
docker run -d --network host -p 80:80 nginx:alpine
# WARNING: Published ports are discarded when using host network mode (docs text)
docker network create shop
docker run -d --name db --network shop -e POSTGRES_PASSWORD=dev postgres:18
docker run --rm --network shop alpine:3.23 nslookup db # expected: answered by 127.0.0.11
docker run --rm alpine:3.23 nslookup db # expected: default bridge, name not found5. Stop vs kill, exit codes and events (expected, not run)
docker events --filter event=die &
docker run -d --name stop-demo alpine:3.23 sleep 600
docker stop stop-demo # expected: sleep as PID 1 ignores SIGTERM -> 10 s wait -> SIGKILL -> exitCode=137
docker run -d --init --name stop-demo-init alpine:3.23 sleep 600
docker stop stop-demo-init # expected: docker-init forwards SIGTERM -> returns at once
# docs sample event lines from the docker events reference (other containers, not the two above):
# 2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
# 2017-01-05T00:42:11.119578204+08:00 container die d9cd...4d70 (exitCode=137, image=alpine, name=happy_meitner)6. Volumes: copy-on-first-mount, persistence, ownership (expected, not run)
docker volume create demo
docker run --rm -v demo:/etc/nginx nginx:1.28-alpine ls /etc/nginx # expected: image files copied into the empty volume
docker run --rm -v demo:/etc/nginx alpine:3.23 ls /etc/nginx # expected: same files, now stored in the volume
docker run --rm -v "$PWD/emptydir":/etc/nginx nginx:1.28-alpine ls /etc/nginx # expected: empty, the bind mount hides the image's files
# Linux host only:
docker run --rm -v "$PWD":/w alpine:3.23 touch /w/root-made && ls -ln root-made # <owner and group columns: 0 0 expected>
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/w alpine:3.23 touch /w/me-made && ls -ln me-made
docker volume prune
# WARNING! This will remove anonymous local volumes not used by at least one container. (docs text)7. The Go Compose project (expected, not run)
cd docs/snippets/platform/docker-run-volumes-compose/go-service
../scripts/dev-env.sh .
docker compose config --services # <service list; adminer appears only with --profile debug>
docker compose up -d --wait # postgres, redis healthy -> api (dev target, air)
docker compose ps # <names, status (healthy), ports 127.0.0.1:8080->8080/tcp>
curl -s localhost:8080/readyz # <ready JSON, same shape as the host run in step 3>
echo '// touch' >> main.go # air rebuilds inside the container: docker compose logs -f api
docker compose --profile debug up -d adminer
docker compose -f compose.yaml -f compose.watch.yaml watch # option B
API_IMAGE=ghcr.io/acme/orders-api@sha256:<digest> \
docker compose -f compose.yaml -f compose.prod.yaml config | grep -A3 'logging:'
time docker compose stop api # well under 10 s: clean drain
docker compose down # volumes kept
docker volume ls --filter label=com.docker.compose.project=orders # orders_pgdata, orders_redis-data, ...8. The Laravel stack, artisan in exec, backup and restore (expected, not run)
# 1. a Laravel 13 application, created with the Composer image (no PHP on the host needed)
cd "$LAB"
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/app -w /app composer:2 \
create-project laravel/laravel shop "^13.0" # post-create: key:generate, sqlite migrate
# 2. copy this chapter's stack into the project root and append the Compose values to its .env
cp -R laravel-stack/compose.yaml laravel-stack/compose.override.yaml laravel-stack/compose.prod.yaml \
laravel-stack/docker laravel-stack/.dockerignore shop/
cat laravel-stack/compose.env.example >> shop/.env
cd shop
../scripts/dev-env.sh . db_password db_root_password # HOST_UID/HOST_GID into .env, secrets/*.txt
# 3. start: the dev image (base + dev stage) bind-mounts this directory, vendor/ included
docker compose up -d --wait # mysql, redis -> migrate (exit 0) -> app -> web, queue, scheduler
docker compose exec app php artisan about
docker compose exec -T app php artisan test
docker compose exec app id # uid=<HOST_UID>(www-data) gid=<HOST_GID>
docker compose up -d --scale queue=3
docker compose exec -T mysql sh -c 'mysqldump -u root -p"$(cat /run/secrets/db_root_password)" --single-transaction shop' > shop.sql
../scripts/volume-backup.sh shop_redis-data --stop redis
../scripts/volume-restore.sh backups/shop_redis-data-<time>.tar.gz shop_redis-restore
docker compose down # data kept; `down -v` would delete shop_mysql-dataCommon misconceptions
| Belief | Reality |
|---|---|
docker stop loses the container's data | Stop/start keeps the writable layer; rm, down + up and redeploys lose it |
-d keeps a container alive | The container lives as long as PID 1; a daemonising command exits at once |
restart: always restarts unhealthy containers | Restart policies react to exits only; health is recorded, not acted on |
depends_on waits until the dependency is ready | Short syntax waits for "started"; use service_healthy, and retry in the app |
EXPOSE / expose: publishes a port | Documentation only; -p / ports: publishes |
| My firewall protects published ports | Docker's iptables rules bypass UFW; bind to 127.0.0.1 |
| Containers find each other by name everywhere | Only on user-defined networks (embedded DNS); not on the default bridge |
| Docker rotates logs | json-file default has no rotation; use local or max-size |
| A volume always shows the image's files | Only an empty volume is pre-populated; later image changes are hidden |
| Permissions are fine because it works on my Mac | macOS file sharing maps owners; Linux hosts see raw UIDs |
| Compose secrets are encrypted | Without Swarm they are bind-mounted host files |
.env is the container's environment | It feeds ${VAR} interpolation; containers get environment/env_file |
docker compose restart applies my YAML changes | Only up re-creates changed containers |
--scale web=3 load-balances | DNS answers several IPs; no health-aware balancer; host ports collide |
version: "3.8" selects features | Ignored by Compose v2/v5 |
| Compose on one server gives zero-downtime deploys | up replaces containers; use a proxy with two instances or an orchestrator |
volume prune only removes junk | It removes every unused volume it targets; with -a, also named ones |
Cheat sheet
| Topic | Remember |
|---|---|
docker run | -d --name --restart unless-stopped -p 127.0.0.1:H:C --network app --env-file --memory --cpus --pids-limit --init |
| Lifetimes | Writable layer = container; named volume = until rm/down -v/prune; bind = host; tmpfs = until stop |
| Restart | no default; on-failure:N; unless-stopped respects manual stops; back-off 100 ms to 1 min |
| Stop | SIGTERM, wait 10 s (Linux), SIGKILL; 143 = TERM, 137 = KILL or OOM; drain below the timeout |
| Ports | Publish only the edge; loopback unless public; never DB or FastCGI ports |
| Networks | User-defined (Compose default) for DNS by name at 127.0.0.11; internal: true for data tiers |
| Limits | Memory and PIDs on everything; GOMEMLIMIT (5-10% headroom), FPM pm.max_children to match; container-aware GOMAXPROCS needs language version 1.25+ or godebug, minimum 2 |
| Logs | stdout/stderr only; local driver or max-size/max-file; daemon defaults affect new containers |
| Health | Liveness without dependencies, readiness with them; Docker records, Compose depends_on/--wait act |
| Permissions | Numbers not names; user: "${HOST_UID}:${HOST_GID}" or a renumbered dev user; image-owned data dirs for volumes |
| Compose files | compose.yaml base, compose.override.yaml dev (auto), -f ... compose.prod.yaml prod; config to check |
| Interpolation | ${VAR:-default}, ${VAR:?error}, $$ literal; shell beats .env; .env is not container env |
| Secrets | Files at /run/secrets/<name>; _FILE convention; file mode on the host decides readability |
| Dev loops | Go: bind + air (or Watch rebuild); PHP: bind mount (or Watch sync); caches in volumes |
| Desktop runtimes | All run a Linux VM; licence (Desktop, OrbStack) vs open source (Colima, Podman Desktop) |
| Production | Digests, no builds, no dev override, rotation, limits, backups, up -d --wait; orchestrator beyond one host |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A container started with docker run -d my-nginx service nginx start exits immediately. Why, and what is the fix? Must-know
Answer
Answer: A container lives as long as its PID 1. service nginx start daemonises nginx and returns, so PID 1 exits and the container stops (the run reference describes exactly this case). Run the server in the foreground as PID 1, for example nginx -g 'daemon off;', preferably as the image's exec-form CMD. See docker run options.
2 — You ran docker compose down and up and your Postgres data is gone, although "it is in a volume". Name three ways this happens. Must-know
Answer
Answer: The data was in an anonymous volume (an image VOLUME or - /var/lib/postgresql without a name), which up does not re-attach; the volume was mounted at the wrong path (for example /var/lib/postgresql/data with a PostgreSQL 18+ image whose PGDATA is /var/lib/postgresql/18/docker, so the data lived in the container layer); or someone ran down -v or a volume prune. Fix: a named volume at the path the image documents, verified by a down/up round trip, and backups. See Persistence.
3 — docker stop api always takes exactly 10 seconds and the logs show no shutdown message. What is going on? Must-know
Answer
Answer: The application never received SIGTERM, so Docker waited the default stop timeout and sent SIGKILL (exit 137). Typical causes: a shell-form CMD/ENTRYPOINT making /bin/sh PID 1, a wrapper script without exec "$@", or an app without a SIGTERM handler. Use exec form or --init, handle SIGTERM with a drain shorter than the timeout, and raise --stop-timeout/stop_grace_period for long jobs. See Stop vs kill.
4 — Your app container cannot connect to db:5432 although both containers run. They were started with plain docker run. Why? Must-know
Answer
Answer: They are on the default bridge network, where there is no embedded DNS: containers reach each other only by IP (or the legacy --link). Create a user-defined network (docker network create app) and start both with --network app; names then resolve through 127.0.0.11. Compose does this automatically with <project>_default. See Networks.
5 — On a Linux CI runner the Laravel dev stack fails with "Permission denied" writing storage/logs, while it works on every developer's Mac. Explain and fix. Must-know
Answer
Answer: A bind mount exposes host files with their numeric owner. On macOS the VM's file sharing maps ownership, so any container UID can write; on Linux the checkout is owned by the runner's UID (say 1001) and php-fpm runs as www-data (UID 33), which may not write a 755 directory. Run the container as the host UID or build the dev image with www-data renumbered to HOST_UID/HOST_GID from .env; do not chmod 777. See Permissions.
6 — Your compose.yaml has depends_on: [mysql] and the app crashes on first boot with a connection error. What two changes make start-up reliable? Important
Answer
Answer: Give mysql a healthcheck (mysqladmin ping) and change the dependency to condition: service_healthy, so Compose starts the app only after MySQL answers. Second, make the app retry connections with back-off, because depends_on only applies at start-up and MySQL can restart later. Add docker compose up --wait in deploy scripts. See Start-up order.
7 — After a week on a small VM the disk is full and /var/lib/docker/containers is huge. What happened and what do you change? Important
Answer
Answer: The default json-file logging driver does not rotate (max-size defaults to unlimited), so container logs grew without bound. Set "log-driver": "local" (rotates 5 x 20 MB by default) or json-file with max-size/max-file in daemon.json, restart the daemon, and re-create the containers, because existing containers keep the options they were created with. See Logging.
8 — What is the difference between the project .env file and env_file: in Compose? Important
Answer
Answer: The project .env is read by Compose for interpolation of ${VAR} in the YAML (image tags, ports, paths); it does not reach containers by itself. env_file: lists files whose variables become the container's environment. Shell variables beat .env for interpolation; for the container, environment: beats env_file:, which beats the image ENV. See Env interpolation.
9 — A distroless service running as UID 65532 fails to read /run/secrets/db_password, and setting mode: 0444 on the secret changes nothing. Why? Important
Answer
Answer: With plain Docker Compose a file: secret is a bind mount of the host file, and the reference says uid, gid and mode are silently ignored for file sources. The container sees the host file's owner and mode (for example 0600 owned by the deploy user), which UID 65532 cannot read. Make the host file readable for that UID (mode or group), use an environment:-sourced secret where the attributes are honoured, or a real secret store. See Secrets and configs.
10 — Why should a production host never auto-load compose.override.yaml, and how do you prevent it? Important
Answer
Answer: The override typically carries development settings: bind-mounted source replacing the image's code, published database ports, dev images and tools. Compose loads it automatically next to compose.yaml unless you pass an explicit file list. Deploy with docker compose -f compose.yaml -f compose.prod.yaml up -d --wait (or COMPOSE_FILE), keep no override file on servers, and in the prod file reset dangerous inherited values with !reset/!override. See Production anti-patterns.
11 — You set --cpus=1 on a Go service running on a 16-core host. What does Go 1.25+ do with that, when, and what should you still set yourself? Good to know
Answer
Answer: Only if the module's language version is 1.25 or newer (or go.mod opts in with godebug containermaxprocs=1): then the runtime considers the cgroup quota and picks the minimum of CPUs, affinity and quota, but never less than 2 when the machine has 2+ CPUs, so GOMAXPROCS becomes 2, not 16 and not 1; it also follows later limit changes unless you set GOMAXPROCS yourself. With go 1.24 in go.mod the old default (16) stays. Memory is separate: set GOMEMLIMIT with 5-10% headroom below --memory so the GC reacts before an OOM kill (exit 137). See The Go angle.
12 — When would you choose Compose Watch rebuild over a bind mount with air for Go development? Good to know
Answer
Answer: When the bind mount is the problem: slow macOS file sharing, file events that do not cross the mount (Colima with sshfs/9p), or UID mismatches on Linux. Watch rebuild copies nothing into a running container; it rebuilds the image with BuildKit (cache mounts keep it fast) and replaces the container, at the cost of a container swap per change. Air with a bind mount gives the fastest loop where events and ownership work. See Watch.
13 — Your team is over Docker Desktop's free-use threshold. What are the alternatives on macOS and what changes for the Compose files? Good to know
Answer
Answer: Colima (open source, Lima-based, Docker or containerd runtime), Podman Desktop (open source, Podman machine, Compose through a provider), Rancher Desktop, or OrbStack (commercial licence per user, fast file sharing). The Compose files stay the same; what changes is the Docker context, file-sharing behaviour (mount type, inotify, paths outside $HOME on Colima), the VM's resources and licensing. See Desktop runtimes.
Glossary
| Term | Meaning |
|---|---|
docker run | docker create + docker start: a new container from an image with run-time options |
Detached mode (-d) | Run in the background and print the container ID |
-i / -t | Keep STDIN open / allocate a pseudo-TTY; -it for interactive shells |
--rm | Remove the container and its anonymous volumes when it exits |
--init / docker-init | tini-backed init as PID 1 that forwards signals and reaps zombies |
| PID 1 | The container's main process; the container lives as long as it does |
| Restart policy | no, on-failure[:N], always, unless-stopped: daemon behaviour when PID 1 exits |
| Restart back-off | 100 ms doubling to 1 minute between restarts; reset after 10 s of uptime |
live-restore | Daemon option that keeps containers running while dockerd restarts |
--env-file | File of VAR=value lines passed as container environment |
Publish (-p, ports:) | Map a host address and port to a container port |
Expose (EXPOSE, expose:) | Document a container port for other containers; publishes nothing |
| Default bridge | The bridge network containers join without --network; no name resolution |
| User-defined network | A network created by docker network create or Compose; isolated, with DNS |
| Embedded DNS | Docker's resolver at 127.0.0.11 on user-defined networks |
| Host network | The container shares the host's network stack; port publishing is ignored |
| None network | Only a loopback interface |
internal network | A network without external connectivity |
| cgroup | Kernel mechanism behind memory, CPU and PID limits |
--memory / mem_limit | Hard memory limit; reaching it triggers an OOM kill in the container |
--cpus | CFS quota in CPUs (1.5 = 150 ms per 100 ms period) |
--pids-limit | Maximum number of processes and threads in the container |
| ulimit | Per-process resource limits (nofile, nproc, core) set with --ulimit |
| OOMKilled / exit 137 | Killed by SIGKILL, from the OOM killer or after the stop timeout |
| Exit 143 | Terminated by SIGTERM (128 + 15) |
| Logging driver | Where container stdout/stderr go: json-file, local, journald, fluentd, ... |
| Log rotation | Size-bounded log files (max-size, max-file); default for local, off for json-file |
| Dual logging | Local cache that keeps docker logs working with remote drivers |
| Healthcheck | Command run in the container; status starting/healthy/unhealthy |
| Liveness / readiness | "Is the process alive" vs "can it serve traffic now" |
docker exec | Run an extra process inside a running container |
docker inspect | Full JSON of a container (state, config, mounts, networks) |
docker stats | Live CPU, memory, I/O and PID usage |
docker events | Stream of daemon events (die, oom, health_status, ...) |
| Stop timeout / grace period | Time between the stop signal and SIGKILL (10 s default on Linux) |
STOPSIGNAL / stop_signal | First signal docker stop sends; default SIGTERM |
| Writable layer | Per-container copy-on-write layer; deleted with the container |
| Named volume | Docker-managed storage with a name, independent of containers |
| Anonymous volume | Volume with a random name, not reused by compose up |
| Bind mount | A host path mounted into a container |
| tmpfs mount | In-memory filesystem, cleared when the container stops |
| Image mount | Another image's content mounted read-only (containerd store) |
volume-nocopy | Do not pre-populate an empty volume from the image |
volume-subpath | Mount only a subdirectory of a volume |
| Volume driver | Plugin or local options that store a volume elsewhere (NFS, CIFS, rclone) |
| UID/GID mapping | How container user numbers correspond to host numbers (none, rootless, userns-remap) |
| subuid / subgid | Ranges of subordinate IDs in /etc/subuid, /etc/subgid for user namespaces |
| Rootless Docker | Daemon and containers run as an unprivileged user in a user namespace |
userns-remap | Root daemon with containers in a remapped user namespace |
SELinux :z / :Z | Relabel a bind mount as shared / private |
| Prune | Commands that delete unused containers, images, networks, volumes or build cache |
| Docker Compose v2 / v5 | The Go docker compose plugin implementing the Compose Specification; v5 adds an SDK and builds via Bake |
| Compose Specification | The rolling, vendor-neutral Compose file format (compose-spec.io) |
compose.yaml | Default Compose file name; compose.override.yaml is auto-loaded next to it |
| Project name | Prefix and isolation unit for a Compose project's containers, networks and volumes |
| Service | A Compose component backed by one or more identical containers |
depends_on condition | service_started, service_healthy, service_completed_successfully |
| Profile | A label that keeps a service off unless enabled with --profile |
| Override file | A later Compose file merged onto earlier ones |
!reset / !override | Compose YAML tags to clear or replace an inherited value |
| Interpolation | Replacing ${VAR} in Compose files from the shell and .env |
Extension field (x-*) | Top-level fields Compose ignores; used with YAML anchors for reuse |
| Compose secret | A file mounted at /run/secrets/<name> for a service that is granted it |
| Compose config | A file mounted into a container (default /<name>), from file, env or inline content |
_FILE convention | Image entrypoints reading VAR_FILE to load VAR from a file |
develop.watch | Compose Watch rules: sync, rebuild, restart, sync+restart, sync+exec |
| Docker Bake | BuildKit's multi-target build front end; Compose v5 builds through it |
scale / replicas | Number of containers for a service (--scale, deploy.replicas) |
pre_start / post_start / pre_stop | Compose lifecycle hooks (init containers before start, commands after start and before stop) |
jobs | Experimental Compose top-level element for one-shot and scheduled tasks (Compose 5.8) |
| air | Live-reload tool for Go that rebuilds and restarts on file changes |
| Laravel Sail | Laravel's Compose file plus sail script for local development |
WWWUSER / WWWGROUP | Sail variables that align the container user with the host user |
| VirtioFS / gRPC FUSE / sshfs / 9p | File-sharing mechanisms between a macOS host and a container VM |
| Synchronized file shares | Docker Desktop feature caching host folders inside the VM |
| Docker Desktop / Colima / OrbStack / Podman Desktop | Tools that run a Linux VM and container engine on macOS/Windows |
| Docker context | Named client configuration for a daemon endpoint (unix://, ssh://, tcp://) |
DOCKER_HOST | Environment variable overriding the daemon endpoint |
| Kompose / Compose Bridge | Tools converting Compose files into Kubernetes manifests |
References
- Docker CLI reference:
docker container runhttps://docs.docker.com/reference/cli/docker/container/run/ — running containers guide https://docs.docker.com/engine/containers/run/ —stophttps://docs.docker.com/reference/cli/docker/container/stop/ —killhttps://docs.docker.com/reference/cli/docker/container/kill/ —exechttps://docs.docker.com/reference/cli/docker/container/exec/ —logshttps://docs.docker.com/reference/cli/docker/container/logs/ —inspecthttps://docs.docker.com/reference/cli/docker/inspect/ —statshttps://docs.docker.com/reference/cli/docker/container/stats/ —eventshttps://docs.docker.com/reference/cli/docker/system/events/ —system prunehttps://docs.docker.com/reference/cli/docker/system/prune/ —volume prunehttps://docs.docker.com/reference/cli/docker/volume/prune/ —dockerdhttps://docs.docker.com/reference/cli/dockerd/ - Docker storage: overview https://docs.docker.com/engine/storage/ — volumes https://docs.docker.com/engine/storage/volumes/ — bind mounts https://docs.docker.com/engine/storage/bind-mounts/ — tmpfs https://docs.docker.com/engine/storage/tmpfs/
- Docker logging: https://docs.docker.com/engine/logging/configure/ — json-file https://docs.docker.com/engine/logging/drivers/json-file/ — local https://docs.docker.com/engine/logging/drivers/local/ — dual logging https://docs.docker.com/engine/logging/dual-logging/
- Docker resource constraints: https://docs.docker.com/engine/containers/resource_constraints/ — restart policies https://docs.docker.com/engine/containers/start-containers-automatically/ — live restore https://docs.docker.com/engine/daemon/live-restore/
- Docker networking: overview https://docs.docker.com/engine/network/ — bridge https://docs.docker.com/engine/network/drivers/bridge/ — host https://docs.docker.com/engine/network/drivers/host/ — none https://docs.docker.com/engine/network/drivers/none/
- Docker security and remote access: rootless mode https://docs.docker.com/engine/security/rootless/ — UID/GID mapping https://docs.docker.com/engine/security/rootless/uid-gid-mapping/ — rootless tips https://docs.docker.com/engine/security/rootless/tips/ — userns-remap https://docs.docker.com/engine/security/userns-remap/ — Linux post-install (docker group) https://docs.docker.com/engine/install/linux-postinstall/ — contexts https://docs.docker.com/engine/manage-resources/contexts/
- Docker Engine 29 release notes: https://docs.docker.com/engine/release-notes/29/
- Docker Compose: history https://docs.docker.com/compose/intro/history/ — application model https://docs.docker.com/compose/intro/compose-application-model/ — services https://docs.docker.com/reference/compose-file/services/ — container specification https://docs.docker.com/reference/compose-file/container-spec/ — workload specification https://docs.docker.com/reference/compose-file/workload-spec/ — volumes https://docs.docker.com/reference/compose-file/volumes/ — networks https://docs.docker.com/reference/compose-file/networks/ — secrets https://docs.docker.com/reference/compose-file/secrets/ — configs https://docs.docker.com/reference/compose-file/configs/ — develop https://docs.docker.com/reference/compose-file/develop/ — build https://docs.docker.com/reference/compose-file/build/ — deploy https://docs.docker.com/reference/compose-file/deploy/ — interpolation https://docs.docker.com/reference/compose-file/interpolation/ — merge https://docs.docker.com/reference/compose-file/merge/ — extension fields https://docs.docker.com/reference/compose-file/extension/ — jobs https://docs.docker.com/reference/compose-file/jobs/
- Docker Compose how-tos: start-up order https://docs.docker.com/compose/how-tos/startup-order/ — watch https://docs.docker.com/compose/how-tos/file-watch/ — profiles https://docs.docker.com/compose/how-tos/profiles/ — merging files https://docs.docker.com/compose/how-tos/multiple-compose-files/merge/ — interpolation https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/ — env precedence https://docs.docker.com/compose/how-tos/environment-variables/envvars-precedence/ — secrets https://docs.docker.com/compose/how-tos/use-secrets/ — production https://docs.docker.com/compose/how-tos/production/ — project name https://docs.docker.com/compose/how-tos/project-name/ — networking https://docs.docker.com/compose/how-tos/networking/ — Compose Bridge https://docs.docker.com/compose/bridge/
- Docker Compose CLI:
uphttps://docs.docker.com/reference/cli/docker/compose/up/ —downhttps://docs.docker.com/reference/cli/docker/compose/down/ —exechttps://docs.docker.com/reference/cli/docker/compose/exec/ —runhttps://docs.docker.com/reference/cli/docker/compose/run/ — release notes https://docs.docker.com/compose/releases/release-notes/ — v5.0.0 release https://github.com/docker/compose/releases/tag/v5.0.0 - Compose Specification: https://compose-spec.io/ — spec https://github.com/compose-spec/compose-spec/blob/main/spec.md
- Docker Desktop: https://docs.docker.com/desktop/ — settings https://docs.docker.com/desktop/settings-and-maintenance/settings/ — synchronized file shares https://docs.docker.com/desktop/features/synchronized-file-sharing/ — licence https://docs.docker.com/subscription/desktop-license/ — Mac install https://docs.docker.com/desktop/setup/install/mac-install/
- Colima: https://github.com/abiosoft/colima — FAQ https://github.com/abiosoft/colima/blob/main/docs/FAQ.md — default config https://github.com/abiosoft/colima/blob/main/embedded/defaults/colima.yaml
- OrbStack: https://docs.orbstack.dev/ — Docker https://docs.orbstack.dev/docker/ — volumes and mounts https://docs.orbstack.dev/docker/file-sharing — licensing https://docs.orbstack.dev/licensing — vs Docker Desktop https://docs.orbstack.dev/compare/docker-desktop
- Podman Desktop: https://podman-desktop.io/docs/intro — Compose https://podman-desktop.io/docs/compose —
podman composehttps://docs.podman.io/en/latest/markdown/podman-compose.1.html - Official images: postgres https://github.com/docker-library/docs/tree/master/postgres — mysql https://github.com/docker-library/docs/tree/master/mysql — redis https://github.com/docker-library/docs/tree/master/redis
- Go 1.25 release notes (container-aware GOMAXPROCS): https://go.dev/doc/go1.25 — air: https://github.com/air-verse/air
- Laravel 13: Sail https://laravel.com/docs/13.x/sail — queues https://laravel.com/docs/13.x/queues — deployment https://laravel.com/docs/13.x/deployment — Sail source https://github.com/laravel/sail
- Kompose: https://github.com/kubernetes/kompose
- Go runtime
GOMAXPROCSdocumentation (defaults, language-version rule, minimum 2, rounding): https://github.com/golang/go/blob/master/src/runtime/debug.go — Go GC guide (memory limit in containers): https://go.dev/doc/gc-guide - Kubernetes pod lifecycle (restart back-off, 30 s grace period): https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
- Laravel 13: configuration (environment overrides .env) https://laravel.com/docs/13.x/configuration — scheduling (
onOneServer) https://laravel.com/docs/13.x/scheduling — installation https://laravel.com/docs/13.x/installation — skeletoncomposer.jsonhttps://github.com/laravel/laravel/blob/13.x/composer.json - Error-message sources: moby port allocator https://github.com/moby/moby/blob/master/daemon/libnetwork/portallocator/portallocator.go — Docker CLI streams https://github.com/docker/cli/blob/master/cli/streams/in.go — Compose dependency wait https://github.com/docker/compose/blob/main/pkg/compose/dependency_wait.go — compose-go template https://github.com/compose-spec/compose-go/blob/main/template/template.go
- Podman
run(--health-on-failure): https://docs.podman.io/en/latest/markdown/podman-run.1.html