tips
192 tips Docker
One command, setting or habit at a time about Docker: what it does, the line to copy and a caveat or two.
Compose 57
-
Shows create, start and die events of the project's containers live, optionally as JSON.
docker compose events -
Lists the volumes of a Compose project, per service if you like, with a custom format.
docker compose volumes -
Write an override file that pins every service image to its current digest.
docker compose config --lock-image-digests -o compose.digests.yaml -
Drop a published port or replace a whole list from an override file.
ports: !reset [] -
Preview which containers and networks a Compose command would create, stop or remove.
docker compose --dry-run up -d -
Make a script wait for a one-shot service to finish before it continues.
docker compose wait migrate -
Order an optional service first when it exists, without failing when it does not.
required: false -
Ask for a specific image architecture when the default one does not exist.
platform: linux/amd64 -
Mount a secret as a file under /run/secrets instead of exposing it in the environment.
services: -
Pick the set of Compose files once through an environment variable.
docker compose config --services -
Use up -d after editing compose.yaml, because restart keeps the old settings.
docker compose up -d -
Throw away and recreate a service's containers when a fresh start is the fix.
docker compose up -d --force-recreate web -
See which variables a project expects, which are required and their defaults.
docker compose config --variables -
Put a short config file inside the Compose file instead of next to it.
content: | -
Share a volume between projects and keep Compose from ever removing it.
external: true -
Point Compose at a project folder from anywhere, handy in cron jobs and scripts.
docker compose --project-directory /srv/app ps -
Run the same Compose file with a different set of variables per environment.
TAG=1.27-alpine -
Open a shell in the second or third copy of a scaled Compose service.
docker compose exec --index 2 worker sh -
Keep local changes in a second file that Compose merges on top automatically.
services: -
Pick stop for a pause and down for a clean slate.
docker compose stop -
Set memory and CPU limits per service in the Compose file, no Swarm needed.
services: -
Tag the image Compose builds so you can push, reuse or roll it back.
build: . -
Fix permissions or seed a file each time the container starts, without a custom image.
services: -
Turn off an image's own health check when it does not fit your setup.
disable: true -
Writes a literal dollar sign in a compose file, so the container shell expands the variable.
services: -
Lets one compose service inherit another and override only a few keys.
services: -
Gives a compose stack a fixed project name instead of the folder name.
name: storefront -
Makes a compose service wait until another one has finished its job with exit code 0.
condition: service_completed_successfully -
Lets a compose service load an optional env file that may not exist.
required: false -
Starts a one-off compose container with its published ports mapped to the host.
docker compose run --rm --service-ports web -
Starts a chosen number of copies of one compose service.
docker compose up -d --scale worker=3 -
Restarts a compose service whenever Compose updates the service it depends on.
restart: true -
Prints the host address and port a compose service publishes for a container port.
services: -
Removes containers left behind by services you deleted or renamed in the compose file.
docker compose down --remove-orphans -
Prints compose logs without the service-name prefix, so the lines can be copied cleanly.
docker compose logs --no-log-prefix --no-color --tail 100 app -
Runs a stack in the foreground and exits with the exit code of the service you name.
docker compose up --exit-code-from tests --build -
Lists only the compose services in one state, such as exited or restarting.
docker compose ps --all --status=exited -
Combines several compose files in order, so a small file can override parts of the base file.
docker compose -f compose.yaml -f compose.prod.yaml up -d -
Pulls other compose files into your main one so a big stack can be split into smaller files.
include: -
Tells Compose how often to check the registry for a newer image, such as every 12 hours.
pull_policy: every_12h -
Shows which images the containers of a Compose project use, as a table, JSON or only IDs.
docker compose images -
Stops and removes a Compose project and deletes images that have no custom tag.
docker compose down --rmi local -
Lets a container finish its shutdown work before Docker kills it after the default 10 seconds.
services: -
Recreates only the Compose service you name, without starting or touching the services it depends on.
docker compose up -d --no-deps web -
Copies a file between your host and a Compose service, without looking up the container name.
docker compose cp web:/etc/nginx/nginx.conf ./nginx.conf -
Lists the Compose projects running on this host, so you can find one without remembering its folder.
docker compose ls -
Starts the stack and waits until the containers are running, or healthy when they have a healthcheck.
docker compose up -d --wait -
When I need to run one command with a service’s settings, volumes and environment, I want a throwaway container, not a new service in the compose file. That is what…
docker compose run --rm app ls -la /data -
Shows only what your Docker Compose stack logged in the last few minutes.
docker compose logs --since 10m -f -n 50 sonarr -
Gives your prompt back only when every container in the stack is really up and healthy.
docker compose up --wait -
Prints the compose file as Docker really reads it, so you can find the mistake.
docker compose config -
Stops Compose with your own error message when a needed variable is empty or missing.
services: -
Runs a command in a service without a terminal, so output can be piped or redirected cleanly.
docker compose exec -T db pg_dump -U postgres mydb > backup.sql -
Runs a small init process first so signals are forwarded and finished child processes are cleaned up.
docker run --init myimage -
Makes a container wait until its dependency passes its healthcheck before it starts.
services: -
Keeps optional services such as admin tools switched off until you ask for them by name.
services: -
Copies your changed source files into a running container, or rebuilds it, without a manual rebuild.
- action: sync
Images and volumes 31
-
Registers a trigger that runs inside the next image build that uses yours as its base.
ONBUILD RUN /usr/local/bin/python-build --dir /app/src -
Overrides the default shell for shell-form RUN, CMD and ENTRYPOINT lines in the rest of the Dockerfile.
SHELL ["/bin/bash", "-c"] -
Saves the current state of a container as a new image, with optional Dockerfile-style changes.
docker commit <container> myname/testimage:version3 -
Builds a fresh image from a root filesystem archive, from a file, a URL or stdin.
docker import /path/to/exampleimage.tgz -
Builds an image from a Dockerfile passed through a pipe or a here-document, with or without a context.
docker build -t myimage:latest - <<EOF -
ARG values are for the build and ENV values persist in containers, so they do different jobs.
ARG NODE_ENV=production -
Switches the build output from the redrawing view to plain text that you can scroll and copy.
docker build --progress=plain -t myimage . -
Mounts only a subdirectory of a named volume, so several containers can share one volume without seeing each other.
docker run --rm --mount src=logs,dst=/logs alpine mkdir -p /logs/app1 /logs/app2 -
Asks a registry over its HTTP API which repositories it holds.
curl http://localhost:5000/v2/_catalog -
Copy files into their own independent layer so base image updates do not force a recopy.
COPY . . -
Copy a default config file out of an image without starting the app.
docker create --name tmp nginx:alpine -
Know which unused volumes a prune removes, and when it removes your data too.
docker volume prune -a -
List only the images whose name or tag matches a pattern.
docker image ls --filter 'reference=nginx' -
Keep the old image under a second tag so you can go back after a bad update.
docker tag example/app:latest example/app:rollback -
List build cache entries with size and last use before you prune them.
docker buildx du -
Know why a volume starts with default files while a bind mount starts empty.
docker run --rm -v /etc/nginx nginx:alpine ls /etc/nginx -
Change the base image tag from the build command, and reuse the value inside the stage.
ARG PY_VERSION=3.13 -
Build and push an image that runs natively on amd64 and arm64.
docker buildx build \ -
Give copied files to the app user in the same step that copies them.
COPY --chown=app:app . . -
Write multi-line shell steps in a Dockerfile without backslashes and ampersands.
RUN <<EOF -
Builds a multi-stage Dockerfile only up to the stage you name, for debugging or testing.
FROM golang:1.26 AS build -
Passes a private value to one Dockerfile step as a temporary file that never lands in the image.
docker build --secret id=token,src=$HOME/.build-token -t example/app:1.0 . -
Writes the full filesystem of a container, running or stopped, to a tar file.
docker export red_panda > latest.tar -
Creates a Docker volume that mounts a share from your NAS over NFS, no plugin needed.
docker volume create --driver local \ -
Lists the CPU platforms of a container image before you pull it.
docker buildx imagetools inspect alpine -
Exports an image to a compressed archive that you can copy elsewhere and load again.
docker save myapp:1.2 | gzip > myapp.tar.gz -
Starts a throwaway shell in an image so you can check what files and tools it really contains.
docker run --rm -it --entrypoint sh nginx:stable -
Shows how much disk space Docker uses before you delete anything with prune.
docker system df -
Keeps unneeded and sensitive files out of the build context so builds run faster.
.git -
Archives the contents of a container's volume into a tar file on the host.
docker run --rm \ -
Removes only unused images older than a set age instead of every unused image.
docker image prune -a --filter "until=240h"
Containers 27
-
Writes the ID of the container you start into a file, so a script can find it later.
docker run -d --cidfile /tmp/app.cid nginx -
Run a one-off container as yourself so the files it writes are yours.
docker run --rm --user "$(id -u):$(id -g)" \ -
Docker sets a sysctl so container users can bind ports below 1024.
docker run --rm alpine cat /proc/sys/net/ipv4/ip_unprivileged_port_start -
Give a container a fixed hostname so apps do not see a new machine after updates.
docker run --rm alpine hostname -
Detach from a container's console without stopping the process inside it.
docker attach mc-server -
Fix container logs in UTC when setting TZ seemingly does nothing.
docker run --rm -e TZ=Europe/Amsterdam alpine date -
Pass an NVIDIA GPU into a container for transcoding or machine learning.
docker run --rm --gpus all ubuntu nvidia-smi -
Pass a secret from your shell into a container without typing it on the command line.
docker run --rm -e API_KEY example/app:1.0 -
Use the mount syntax to catch a typo in a bind mount path before it costs you data.
docker run --rm --mount type=bind,src=/srv/apps/data,dst=/data alpine ls /data -
Mount config folders read-only so a container can read but never change them.
docker run -d --name web \ -
Pick the restart policy that respects a container you stopped on purpose.
docker run -d --name web --restart unless-stopped nginx:alpine -
Sets a hard ceiling on the CPU a container may use, in whole or fractional cores.
docker run -d --name encoder --cpus="1.5" example/app:1.0 -
Makes docker run check the registry for a newer image first instead of using the cached one.
docker run --rm --pull always example/app:latest -
Suspends every process in a container in place, until you unpause it.
docker pause my-app -
Sends any signal, such as HUP, to a container's main process without stopping the container.
docker kill --signal=HUP my-proxy -
Sets the soft and hard limit for open files of a single container.
docker run --ulimit nofile=1024:1024 --rm debian sh -c "ulimit -n" -
Reads container environment variables from a file instead of a long row of -e flags.
DB_HOST=192.168.1.10 -
Runs a command inside a running container as a chosen user and from a chosen folder.
docker exec -it -u 1000:1000 -w /config mycontainer ls -l -
Restarts a container only after errors, and stops trying after a set number of attempts.
docker run -d --name worker --restart=on-failure:5 example/worker:1.0 -
Sets memory plus swap together for a container, or turns swap off for it completely.
docker run -d --name app --memory=512m --memory-swap=512m example/app:1.0 -
Removes only stopped containers older than a given age or with a given label.
docker container prune --filter "until=24h" -
Sets the signal docker stop sends first, and shows how the grace period before SIGKILL works.
docker run -d --stop-signal=SIGQUIT <image> -
Lets a slow-starting container report healthy sooner by probing more often during startup.
HEALTHCHECK --interval=30s --start-period=60s --start-interval=5s \ -
Adds a small init process that forwards signals and cleans up zombie processes.
docker run --init --rm -it my-image -
Changes the name of an existing container while it keeps running, with no new container needed.
docker rename quirky_wozniak web-test -
Changes the restart policy of a container that is already running, without recreating it.
docker update --restart=unless-stopped mycontainer -
Copies files out of or into a container, even a stopped one, without starting it.
docker cp mycontainer:/etc/app/config.yml ./config.yml
Inspect and logs 21
-
Find out whether exit code 137 came from the memory limit.
docker inspect --format '{{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}' myapp -
Use the host's ss, tcpdump or curl as if they ran inside a container.
sudo nsenter -t "$pid" -n ss -tlnp -
See the complete start command and full IDs that docker ps normally cuts off.
docker ps --no-trunc --format 'table {{.Names}}\t{{.Command}}' -
Get a container's IP addresses per network without scrolling through JSON.
docker inspect --format '{{range $k, $v := .NetworkSettings.Networks}}{{$k}}={{$v.IPAddress}} {{end}}' myapp -
Read an image's default ports, user, environment and stop signal without starting it.
docker image inspect --format '{{json .Config.ExposedPorts}}' nginx:alpine -
Make grep see the error lines a container writes to stderr.
docker logs myapp 2>&1 | grep -i error -
Switch to Docker's local log driver for smaller logs that rotate on their own.
docker run -d --log-driver local --name web nginx:alpine -
Waits for a container to stop, then prints its exit code, which is handy in scripts.
docker wait nightly-job -
Shows only the stats columns you choose, such as name, CPU and memory, in one snapshot.
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" -
Explains what exit codes 125, 126 and 127 mean when docker run fails to start a command.
docker run busybox foo; echo $? -
Rotates a container's json-file log by size and keeps a fixed number of old files.
docker run -d --log-opt max-size=10m --log-opt max-file=3 <image> -
Adds a size column that shows how much data each container wrote on top of its image.
docker container ls -s -
Lists the processes running in a container without opening a shell inside it.
docker top mycontainer -
Lists every layer of an image with the full command that created it and its size.
docker history --no-trunc nginx:latest -
Prints the health status of a container, so you can tell a stuck app from one that is working.
docker inspect --format '{{.State.Health.Status}}' mycontainer -
Shows only the last few minutes of a container's log and follows new lines.
docker logs --since 10m -f container-name -
Prints one table with CPU and memory per container, then gives you your prompt back.
docker stats --no-stream -
Lists every file a container added, changed or deleted compared to its image.
docker diff mycontainer -
Lists running containers with only the columns you choose, such as name and status.
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' -
Streams a line every time a container exits, with its exit code, so restarts are easy to spot.
docker events --filter 'event=die' --filter 'type=container' -
Prints a single field of a container, such as its mounts, instead of the whole inspect output.
docker inspect --format '{{.State.Status}}' mycontainer
Networks 18
-
Removes unused Docker networks, optionally only old ones or only ones without a label.
docker network prune -
Give a container its own address and MAC on the physical network.
docker network create -d macvlan \ -
Pin a container's address when a firewall rule or old client needs a fixed IP.
docker network create --subnet 192.0.2.0/24 lan -
Tell Docker which IP ranges it may use for new networks.
"default-address-pools": [ -
Let one service share the network stack of another, such as a VPN container.
services: -
Keep a database or backend on a network that cannot reach the outside world.
docker network create --internal backend -
With host networking the app's own port is the port, and -p does nothing.
docker run --rm --network host -p 8080:80 nginx:alpine -
Cut a one-off container off from every network, with only loopback inside.
docker run --rm --network none \ -
A Docker setting in Unraid that decides whether the host and WireGuard clients can reach containers with custom IPs.
-
Stops macvlan call traces by moving Unraid's custom Docker networks to ipvlan.
Advanced view > Docker custom network type: ipvlan -
Gives a container a fixed name for the Docker host, so it can reach services running there.
- "host.docker.internal=host-gateway" -
Runs a throwaway toolbox container that shares the network of a container you want to debug.
docker run --rm -it --network container:sonarr nicolaka/netshoot -
Attaches an existing container to another Docker network without recreating it.
docker network connect proxy-net app -
Route a single Docker container through your VPN provider using Unraid's built-in WireGuard.
--dns=8.8.8.8 -
Prints the subnet, gateway and attached containers of a Docker network, and --format picks out single fields.
docker network inspect bridge -
Prints the host address and port mapped to each published port of a container.
docker port mycontainer -
Shows why a container name only works as a hostname on a user-defined Docker network.
docker network create mynet -
Stops Unraid from removing the Docker networks you created yourself when the Docker service restarts.
Unraid and Docker 10
-
Where the process limit of containers lives in Unraid, and how to change it for one container.
--pids-limit=4096 -
The Unraid setting that decides how long a container gets to shut down cleanly.
time docker stop my-database -
Finds which container or volume is filling up Unraid's docker.img.
docker system df -v -
Reinstalls all your old Docker containers with their saved settings after you recreate docker.img.
Apps > Previous Apps > tick the ones you want > Install -
Stops or starts a chosen Docker container at a fixed time using the User Scripts plugin.
docker stop "container-name" -
Explains the choice between a vDisk image and a plain folder for the place Docker keeps its data.
-
Delays the next container's start so a database or VPN is ready before the apps that need it.
Advanced View > AutoStart > wait (seconds) -
Lets a share that lives on one pool bypass the user share filesystem for faster file access.
-
Caps how much memory one Docker container may use, so it cannot starve the rest of the server.
--memory=2g --memory-swap=2g -
Explains the difference between pinning and isolating CPU cores on Unraid's CPU Pinning page.
Access and security 9
-
Logs in to a registry with a password read from standard input, not typed in the command.
cat ~/my_token.txt | docker login --username myname --password-stdin -
Changes a namespaced kernel setting inside a single container, without touching the host's settings.
docker run --rm --sysctl net.ipv4.ip_forward=1 alpine cat /proc/sys/net/ipv4/ip_forward -
Know that :ro on docker.sock still lets a container control Docker fully.
- /var/run/docker.sock:/var/run/docker.sock:ro -
Restrict who may reach published container ports with rules Docker will not overwrite.
sudo iptables -I DOCKER-USER -i eth0 ! -s 192.0.2.0/24 -j DROP -
Treat membership of the docker group like sudo without a password.
sudo usermod -aG docker "$USER" -
Removes every Linux capability from a container so you only add back what the app really needs.
docker run -d --name web --cap-drop ALL --cap-add NET_BIND_SERVICE -p 8080:80 nginx -
Gives a container access to one host device, like a USB stick, without using privileged mode.
docker run -d --name zigbee --device=/dev/ttyUSB0:/dev/ttyUSB0 example/zigbee:1.0 -
Caps how many processes a container may start, so a runaway or fork bomb stays inside it.
docker run -d --pids-limit 200 --name web nginx -
Creates a named context for a remote Docker host, so docker commands run there through SSH.
docker context create remote --docker "host=ssh://[email protected]"
Nginx Proxy Manager 7
-
Add global nginx settings to Nginx Proxy Manager that survive updates.
docker compose restart npm -
Shows how to upgrade Nginx Proxy Manager on purpose, with a pinned image version.
image: 'jc21/nginx-proxy-manager:2.17.0' -
Adds a Docker health check so Nginx Proxy Manager shows healthy or unhealthy in docker ps.
healthcheck: -
Stops Nginx Proxy Manager downloading CDN IP ranges at startup, which helps when internet access is limited.
environment: -
Stops Nginx Proxy Manager from using IPv6 on a host that has IPv6 turned off.
environment: -
Lets Nginx Proxy Manager reach other containers by name, so they need no published host ports.
docker network create scoobydoo -
Creates the first Nginx Proxy Manager admin from your compose file, so there is no setup screen.
environment:
Filtering 3
-
Use the labels Compose adds to find containers by project or service anywhere.
docker ps --filter label=com.docker.compose.project=media \ -
List unhealthy containers in one line, handy for scripts and alerts.
docker ps --filter health=unhealthy --format '{{.Names}}' -
Sends Docker container logs to the systemd journal and filters them by container name.
sudo journalctl -b CONTAINER_NAME=webserver
Apps and containers 2
-
Explains the Healthy, Unhealthy and No health check labels in Unraid's Docker tab.
-
Make a container see a disk outside the array by picking a Slave access mode.
Protocols and network 2
-
Add /udp to a port mapping for services that speak UDP.
docker run -d --name dns \ -
Sends HTTP requests to a local Unix socket, like the Docker Engine API, with plain curl.
curl -s --unix-socket /var/run/docker.sock \
Stacks 2
-
Outputs the final Compose file after merging and variable substitution, before you deploy it to a swarm.
docker stack config -c docker-compose.yml -c docker-compose.prod.yml -
Shows the command to add a worker or manager node to a swarm, and can replace the token.
docker swarm join-token worker
System 2
-
Spot missing kernel features that silently disable memory limits or networking.
docker info --format '{{json .Warnings}}' -
Whether the array starts by itself after a reboot decides if your server comes back.
Nothing in this filter yet.