Docker is a platform for building images and running applications in containers. Covers Dockerfiles, the build cache, volumes, networking, Compose and security.
Docker is a platform for building and running applications in containers. A container is an isolated process that shares the host’s kernel. Its filesystem comes from an image: a read-only template with the application and everything it needs.
Use Docker when an application has to behave the same on a developer’s laptop, in CI and on a server: you build the image once and run it anywhere Docker runs. Each component — the web application, the database, the cache — runs in its own container, independent of what is installed on the host. A container won’t do if the application needs its own kernel or a different OS: all containers on a host share one kernel, so use a virtual machine.
Docker has a client–server architecture. The docker command and Docker Compose are clients: they send requests to the dockerd daemon over a REST API, usually through a Unix socket. The daemon manages images, containers, networks and volumes and exchanges images with a registry. It runs the containers themselves through the containerd and runc runtimes. The client and the daemon can run on different machines.
The default registry is Docker Hub; a private registry works the same way, by its address.
Docker objects
Image — a read-only template for containers; you can start any number of containers from one image.
Container — a running instance of an image. Anything it writes outside persistent storage is lost when the container is removed.
Network — connects containers to each other and to the outside world.
Volume — data storage that outlives the container.
How a container differs from a virtual machine
Aspect
Container
Virtual machine
OS kernel
shared with the host
each machine has its own
What’s inside
the process and the files the application needs
a whole OS: kernel, drivers, programs
Isolation
namespaces of the host kernel
a separate OS with its own kernel
Overhead
low: the same resources fit more applications
high if the machine exists for a single application
Choose a container to package an application and run it the same way everywhere, and a virtual machine when you need your own kernel or a different OS. The two are often combined: a cloud provider gives you a virtual machine that runs several containers.
Prerequisites
The Linux command line: files, permissions, processes — see the Linux reference.
The shell, environment variables and quoting — see the Bash reference.
Ports and addresses — see the TCP/IP and DNS reference, section “Ports and sockets”.
Everyday commands for images, containers, logs, networks, volumes, Compose and cleanup. Replace the names in the examples (web, pgdata, myapp:1.0) with your own. Flags and pitfalls are covered in the sections on images, containers, networking, volumes and Compose.
Images
Task
Command
Pull an image
docker pull nginx:1.30
List images
docker image ls
Build an image from the current directory
docker build -t myapp:1.0 .
Name an image for your registry
docker tag myapp:1.0 registry.example.com/team/myapp:1.0
Log in to a registry
docker login registry.example.com
Push an image to a registry
docker push registry.example.com/team/myapp:1.0
Show the image’s layers
docker image history myapp:1.0
Remove an image
docker image rm myapp:1.0
Containers
Task
Command
Run in the background with a port
docker run -d --name web -p 8080:80 nginx:1.30
Port reachable from this machine only
docker run -d -p 127.0.0.1:8080:80 nginx:1.30
Throwaway container with a shell
docker run --rm -it ubuntu:26.04 bash
Running containers
docker ps
All containers, including stopped ones
docker ps -a
Stop
docker stop web
Start a stopped container
docker start web
Restart
docker restart web
Remove a stopped container
docker rm web
Remove even if running
docker rm -f web
Enable automatic restart
docker update --restart unless-stopped web
Logs and debugging
Task
Command
Follow the logs
docker logs -f web
Last 50 lines of the logs
docker logs -n 50 web
Shell in a running container
docker exec -it web sh
All container settings as JSON
docker inspect web
Health check result
docker inspect --format '{{.State.Health.Status}}' web
Is the daemon running
docker info
Daemon log
sudo journalctl -xu docker.service
Networks and volumes
Task
Command
Create a network
docker network create appnet
Run a container on a network
docker run -d --name web --network appnet nginx:1.30
Connect a running container
docker network connect appnet web
List networks
docker network ls
Create a volume
docker volume create pgdata
Run a database with a volume
docker run -d --name db -e POSTGRES_PASSWORD=change-me -v pgdata:/var/lib/postgresql postgres:18
Host directory, read-only
docker run -d -v ./site:/usr/share/nginx/html:ro nginx:1.30
List volumes
docker volume ls
Compose
Task
Command
Start the project in the background
docker compose up -d
Rebuild images and restart
docker compose up -d --build
Service status
docker compose ps
Follow the logs of all services
docker compose logs -f
Shell in a service
docker compose exec web sh
Resolved configuration after interpolation
docker compose config
Pull new image versions
docker compose pull
Stop and remove containers and networks
docker compose down
Cleanup
Task
Command
How much space Docker uses
docker system df
Remove dangling images
docker image prune
Clear the build cache
docker builder prune
Remove unused anonymous volumes
docker volume prune
Remove stopped containers, unused networks, dangling images and build cache
docker system prune
The same, plus all unused images and anonymous volumes
On Linux, install Docker Engine from the official download.docker.com repository, which then also delivers updates. On macOS and Windows, install Docker Desktop. Verify the installation with docker version and docker run hello-world.
Requirements
You need a 64-bit version of Ubuntu 26.10, 26.04 LTS, 24.04 LTS or 22.04 LTS, or of Debian 13 or 12. First remove any unofficial Docker packages that came with the distribution, as well as separately installed containerd and runc: Docker Engine ships its own versions in the containerd.io package. Images, containers and volumes in /var/lib/docker are preserved.
Add the Docker repository and install the packages:
bashon the host, Ubuntu
sudo apt updatesudo apt install ca-certificates curl# the key the repository is signed withsudo install -m 0755 -d /etc/apt/keyringssudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg \ -o /etc/apt/keyrings/docker.ascsudo chmod a+r /etc/apt/keyrings/docker.asc# repository of the stable channelsudo tee /etc/apt/sources.list.d/docker.sources <<EOFTypes: debURIs: https://download.docker.com/linux/ubuntuSuites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")Components: stableArchitectures: $(dpkg --print-architecture)Signed-By: /etc/apt/keyrings/docker.ascEOFsudo apt updatesudo apt install docker-ce docker-ce-cli containerd.io \ docker-buildx-plugin docker-compose-plugin
On Debian the commands are the same except in three places: the key is downloaded from https://download.docker.com/linux/debian/gpg, the URIs line is https://download.docker.com/linux/debian, and the Suites line takes the release codename like this:
The docker-buildx-plugin and docker-compose-plugin packages add the docker buildx and docker compose commands. To upgrade, run the same apt install command after apt update.
macOS and Windows
Install Docker Desktop, a GUI application that includes Docker Engine, the CLI, Docker Build, Docker Compose and Kubernetes. On Windows it runs on WSL 2 or Hyper-V. Docker Desktop is also available for Linux; on a server without a graphical interface, install Docker Engine from the repository.
The get.docker.com script
bashon the host
curl -fsSL https://get.docker.com -o get-docker.sh# show the steps without changing anythingsudo sh ./get-docker.sh --dry-runsudo sh ./get-docker.sh
The test.docker.com script sets up the test channel, which carries beta versions and release candidates in addition to stable releases. Use it only on machines meant for testing.
Verifying the installation
bashon the host
sudo systemctl status dockersudo docker versionsudo docker run hello-world
textexample output
Client: Docker Engine - Community ...Server: Docker Engine - Community Engine: ... containerd: ... runc: ...
docker version prints two sections: Client is the CLI itself, and Server is Docker Engine with the containerd and runc it uses. hello-world pulls a test image, prints a confirmation message and exits. On Debian and Ubuntu the docker service starts automatically at boot once installed; on other distributions with systemd, enable docker.service and containerd.service with systemctl enable.
Running Docker without sudo
The daemon socket is owned by root, and the package creates a docker group with no members, so right after installation the commands work only with sudo. Add yourself to the group and log in again:
bashon the host
sudo usermod -aG docker $USER# apply the group in this shell without logging outnewgrp dockerdocker run hello-world
A member of the docker group gets root privileges on the host — see “Container security”.
Container logs and disk space
The default logging driver, json-file, writes container logs to files on the host, and over time they can fill the disk. Enable log rotation for it or switch to the local driver, which rotates logs by itself.
An image is an immutable template for a container: the application files, libraries and startup settings, stacked in layers. Images are stored and distributed through a registry; by default Docker pulls them from Docker Hub. The name nginx:1.30 means the nginx repository and the 1.30 tag.
Each layer is a set of file changes: what was added, modified or deleted. Once created, a layer never changes; a new version is a new image or new layers on top of the old ones. When a container starts, Docker stacks the layers into a single filesystem and adds a separate writable container layer on top. That is why one image can run any number of containers, and identical layers of different images are stored on disk only once.
Changes made inside a container go to its writable layer and are deleted together with the container.
Parts of an image name
The full image reference is [HOST[:PORT]/]NAMESPACE/REPOSITORY[:TAG]. Docker fills in whatever the reference leaves out:
HOST — the registry address; defaults to docker.io, which is Docker Hub.
NAMESPACE — a user or organisation; defaults to library, the namespace of official images.
TAG — the version or variant of the image; defaults to latest.
Instead of a tag, you can give a digest, @sha256:…, an immutable identifier of the content.
Reference
What it resolves to
nginx
docker.io/library/nginx:latest
nginx:1.30
docker.io/library/nginx:1.30
registry.example.com:5000/team/myapp:1.0
registry registry.example.com, port 5000, namespace team, repository myapp, tag 1.0
A tag is a mutable pointer: the publisher rebuilds the image with fixes, and the same nginx:1.30 starts pointing to new layers. docker pull with the same tag downloads the fresh build. A digest always points to the same content, but an image pinned by digest does not get security updates on its own: you have to change the digest by hand.
Pull, tag and push an image
bashon the host
# pull an image from Docker Hubdocker pull nginx:1.30# give your image a name with the registry addressdocker tag myapp:1.0 registry.example.com/team/myapp:1.0docker login registry.example.comdocker push registry.example.com/team/myapp:1.0
To push an image anywhere other than Docker Hub, its name must include the registry address. docker tag creates another name for the same image: both names share one ID, and no copy is made on disk. docker login stores the registry credentials. After push and pull, Docker prints the image digest.
Image commands
Task
Command
Pull an image
docker image pull (docker pull)
List images
docker image ls (docker images)
Layers and the commands that created them
docker image history
All metadata as JSON
docker image inspect
Give an image a new name
docker image tag (docker tag)
Push to a registry
docker image push (docker push)
Remove an image
docker image rm
Remove unused images
docker image prune
Save to a tar archive and load it back
docker image save, docker image load
Images for another platform
The --platform flag sets the platform — operating system and CPU architecture — whose variant of the image to pull, for example linux/arm64 for an ARM server. The flag works if the daemon supports multiple platforms:
bashon the host
docker pull --platform linux/arm64 nginx:1.30
Which image to start from
Docker Hub runs trusted content programmes. Docker Official Images are a curated set of repositories that most users start from. Docker Hardened Images are minimal images with almost no known vulnerabilities, free under the Apache 2.0 licence. Docker Verified Publisher images come from commercial publishers verified by Docker.
A Dockerfile is a text file with the instructions Docker follows to build an image. It says which image to start from, which files to copy, which commands to run and what to start in the container. The instructions run in order, from top to bottom.
Name the file Dockerfile, with no extension, and docker build finds it on its own. The first line is the # syntax=docker/dockerfile:1 directive: before building, BuildKit fetches the latest stable release of version 1 of the syntax. Then FROM sets the base image, and all the other instructions run in it.
dockerfileDockerfile
# syntax=docker/dockerfile:1FROM python:3.15-slimWORKDIR /appENV FLASK_APP=app# dependencies first: this layer rarely changesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .# the application process does not run as rootRUN useradd --no-log-init --uid 10001 appUSER appEXPOSE 8000CMD ["flask", "run", "--host", "0.0.0.0", "--port", "8000"]
requirements.txt is copied and the dependencies are installed before the code, so editing the code does not trigger another package download. The reason is explained in “Builds: cache, multi-stage and secrets”.
Core instructions
Instruction
What it does
When it applies
FROM
Starts a build stage from a base image
build
WORKDIR
Working directory for the instructions that follow; created if it doesn’t exist
build and run
COPY
Copies files from the build context or another stage
build
ADD
Like COPY, but also downloads from URLs and Git and extracts local tar archives
build
RUN
Runs a command and saves the result as a new layer
build
ENV
Environment variable: available during the build and kept in the container
build and run
ARG
Build-only variable, set with --build-arg
build
USER
User for subsequent RUN instructions and for the container process
build and run
EXPOSE
Documents the port the application listens on; does not publish it
a hint for running
CMD
Default command when the container starts
run
ENTRYPOINT
Makes the container run as a specific program
run
HEALTHCHECK
Command that checks whether the application is working
run
LABEL
Image metadata
build
Shell form and exec form
RUN, CMD and ENTRYPOINT can be written in two forms. The exec form is a JSON array in double quotes: the program is run directly, without a shell, so variables such as $HOME are not expanded. The shell form is a plain string run by /bin/sh -c: variables, && and backslash line continuations work.
Use the exec form for CMD and ENTRYPOINT. In the shell form the main process (PID 1) is the shell, not your program. The program never receives the SIGTERM signal from docker stop, and when the timeout expires, Docker kills the container with SIGKILL.
dockerfiletwo forms of one instruction
# exec form: the program itself receives signalsENTRYPOINT ["/usr/local/bin/myapp", "--port", "8000"]# shell form: PID 1 is /bin/sh, the signal is lostENTRYPOINT /usr/local/bin/myapp --port 8000
CMD and ENTRYPOINT
CMD sets the default command, and any arguments to docker run replace it. ENTRYPOINT sets a program that always runs: docker run arguments are appended to it, and CMD then holds the default arguments. If CMD appears more than once, the last one takes effect; ENTRYPOINT is overridden with the docker run --entrypoint flag.
Dockerfile
docker run myapp
With arguments
CMD ["flask", "run"]
flask run
docker run myapp bash → bash
ENTRYPOINT ["flask"]
flask
docker run myapp run → flask run
ENTRYPOINT ["flask"] and CMD ["run"]
flask run
docker run myapp --version → flask --version
ARG and ENV
ARG is a build parameter: its value is passed with docker build --build-arg and does not exist in the final container. ENV stays in the image and is visible to the application; override it at run time with docker run --env. Write ENV KEY=value: the form without the equals sign is deprecated.
Copy files from the build context with COPY. Use ADD when a file has to be downloaded over HTTPS or from a Git repository: it can verify a checksum (--checksum) and works with the cache more precisely than RUN wget. ADD also extracts local tar archives by itself, which can come as a surprise.
Health checks
HEALTHCHECK tells Docker how to confirm that the application is actually working, not just running. The container status starts as starting, becomes healthy after a successful check and unhealthy after several consecutive failures. The command’s exit code: 0 means healthy, 1 means unhealthy.
Consecutive failures that make the container unhealthy
3
.dockerignore
A .dockerignore file at the root of the build context excludes files from the context. This keeps .git, local environments and files with secrets out of the image and stops the build from wasting time on them. The syntax is similar to .gitignore.
text.dockerignore
.git.venv__pycache__*.md.env
Best practices
Use an official or verified minimal base image and pin a branch tag: python:3.15-slim, not python.
Combine apt-get update and apt-get install in one RUN and remove /var/lib/apt/lists/*: a separate RUN apt-get update comes back stale from the cache.
Run the application as a regular user with USER unless it needs root; set the UID explicitly.
Set WORKDIR to an absolute path instead of using RUN cd ….
One container, one concern: the web application, the database and the cache are separate images.
Rebuild images regularly with the --pull flag to pick up the patched base image.
docker build -t myapp:1.0 . builds an image from the Dockerfile in the current directory; the dot is the build context. A cache-friendly instruction order makes builds fast, a multi-stage build keeps the image small, and secrets are passed with --secret so that they don’t stay in the layers.
docker build is docker buildx build: BuildKit runs the build. The smaller the context, the less data is sent to the builder and the less often the cache is invalidated, so exclude anything unneeded with .dockerignore.
How the build cache works
Each Dockerfile instruction produces a layer. On a rebuild, Docker takes a layer from the build cache if neither the instruction nor the files it uses have changed. As soon as one layer changes, every layer after it is rebuilt, even if nothing in them has changed.
Hence the rule: put what rarely changes (the base image, system packages, dependencies) first and what changes often (the code) last. The most common mistake is COPY . . before installing dependencies: then every code edit reinstalls all the packages.
A rebuild after editing one source file.dockerfileDockerfile
The RUN cache compares only the command text: a cached RUN apt-get update will not fetch a fresh package list. --no-cache rebuilds everything, and --pull forces a fresh download of the base image.
The cache is stored in the builder (BuildKit) that runs the build, and other builders cannot see it. On CI runners that are created from scratch for every job, export the cache to external storage with --cache-to and import it with --cache-from.
Cache mounts
RUN --mount=type=cache gives the command a directory that persists between builds. If the install layer does get rebuilt, the package manager downloads only new and changed packages. The directory is mounted only while the command runs and does not end up in the image.
dockerfileDockerfile
RUN --mount=type=cache,target=/root/.cache/pip \ pip install -r requirements.txt
Multi-stage builds
A Dockerfile can contain several FROM instructions, and each one starts a new stage. The first stage builds the program with all its tools; the last one takes only the result with COPY --from. Compilers and intermediate files stay out of the final image.
dockerfileDockerfile
# syntax=docker/dockerfile:1FROM golang:1.27 AS buildWORKDIR /srcCOPY go.mod go.sum ./RUN go mod downloadCOPY . .RUN CGO_ENABLED=0 go build -o /bin/app ./cmd/app# final image: just the binaryFROM scratchCOPY --from=build /bin/app /bin/appUSER 10001ENTRYPOINT ["/bin/app"]
Name stages with AS so that COPY --from does not depend on their order. The --target flag stops the build at a given stage, for example to debug the build stage. BuildKit builds only the stages that the target depends on.
bashon the host
docker build --target build -t myapp:build .
Build secrets
A build secret is a password or token needed only while the image is being built. Build arguments and environment variables are unsuitable for this: they remain in the final image. Pass the secret with the --secret flag and mount it into a single command with RUN --mount=type=secret — as a file in /run/secrets/ by default, or as an environment variable with the env option.
bashon the host
# the value comes from a host environment variabledocker build --secret id=pip_index,env=PIP_INDEX_URL \ -t myapp:1.0 .
dockerfileDockerfile
# only this command sees the secret; no layer keeps itRUN --mount=type=secret,id=pip_index,env=PIP_INDEX_URL \ pip install -r requirements.txt
docker build flags
Flag
What it does
Default
-t myapp:1.0
Image name and tag; the flag can be repeated
—
-f build.Dockerfile
A different Dockerfile
Dockerfile in the context
--build-arg NAME=value
Value for an ARG
—
--target build
Build up to the given stage
—
--platform linux/arm64
Platform of the image
the builder’s platform
--no-cache
Build without the cache
—
--pull
Always pull fresh base images
—
--secret id=…
Pass a build secret
—
--push
Push the result to a registry
—
Building and publishing images in a CI pipeline is covered in the CI/CD reference, section “Building and publishing images”.
docker run creates a container from an image and starts it; if the image is not on the machine, Docker pulls it first. A stopped container stays on disk with all its changes until it is removed.
bashon the host
docker run -d \--name web \ -p 8080:80 \--restart unless-stopped \ nginx:1.30
The web container runs in the background, answers on host port 8080 and comes back up after a crash or a server reboot. The name replaces the long ID in every command: docker logs web, docker stop web.
Flag
What it does
Default
-d
Run in the background and print the container ID
in the foreground
--name web
Container name
a random name
-p 8080:80
Publish container port 80 on host port 8080
no ports published
-e KEY=value, --env-file app.env
Environment variables
from the image
-v, --mount
Mount a volume or a host directory
—
--rm
Remove the container and its anonymous volumes on exit
the container is kept
-it
Interactive terminal
—
--restart
Restart policy
no
-m 512m, --cpus 1.5
Memory and CPU limits
no limits
--init
An init process as PID 1: forwards signals and reaps exited processes
—
Container states
The state of a container is shown in the STATUS column of docker ps -a. The main path is created → running → exited; a running container can be paused (paused). There are also restarting (being restarted by its policy), removing (being removed) and dead (only partly removed; all you can do is remove it).
A non-zero exit code means failure; this is what the on-failure policy reacts to.
docker run creates and starts a container in one command. A stopped container keeps its filesystem: docker start runs it again with all its changes, and docker rm deletes it along with them.
Stopping and signals
docker stop sends SIGTERM to the container’s main process and waits. If the process has not exited within the timeout (10 seconds by default for Linux containers), Docker sends SIGKILL. The -t (--timeout) flag sets the timeout; the first signal is set by the STOPSIGNAL instruction in the Dockerfile or the --stop-signal flag when the container is created.
bashon the host
# give the application 30 seconds to shut down cleanlydocker stop -t 30 webdocker start webdocker rm web
A container runs as long as its main process (PID 1) runs. If PID 1 is a shell, the shell receives the signal instead of the application, and the stop ends with SIGKILL — see “Dockerfile instructions”. The --init flag makes PID 1 a small init process, docker-init, which forwards signals to the application and reaps exited child processes.
Commands in a running container
docker exec starts another process in a running container, such as a shell for debugging. It takes the name or ID of the container, not the image name.
bashon the host
docker exec -it web sh
Restart policies
Policy
When Docker restarts the container
no
Never; the default policy
on-failure[:N]
When it exits with a non-zero code; N limits the number of attempts
always
Always; a manually stopped container only after the daemon restarts
unless-stopped
Like always, but a manually stopped container stays down even after the daemon restarts
A restart policy takes effect only after the container has been running for at least 10 seconds, so a container that fails right away does not loop forever. Docker waits longer between each attempt: 100 ms, 200 ms, 400 ms and so on, up to a minute. To change the policy of an existing container, run docker update --restart unless-stopped web.
Memory and CPU
Without limits, a container can take all of the host’s memory and CPU. -m (--memory) sets a hard memory limit, with a minimum of 6m; --cpus sets how many CPUs the container may use, as a fractional number.
bashon the host
docker run -d --name api \ -m 512m \--cpus 1.5 \ myapp:1.0
Containers on the same user-defined network find each other by name, and from outside the host only published ports are reachable. -p 8080:80 publishes container port 80 on host port 8080: host first, container second.
On first start, Docker creates the default bridge network, and every container started without --network joins it. There, containers see each other only by IP address. On a user-defined network, Docker’s embedded DNS server lets the web container reach the database by the name db. Your own network also isolates the project from other containers.
This is how a user-defined bridge network works; on the default network, the name db does not resolve.bashon the host
docker network create appnetdocker run -d --name db \--network appnet \ -e POSTGRES_PASSWORD=change-me \ postgres:18docker run -d --name web \--network appnet \ -p 8080:80 \ nginx:1.30
The database port is not published: web connects to db:5432 inside the network, and other machines cannot reach the database. Within one network, containers are open to each other on all ports.
Network drivers
Driver
Use
bridge
Default: an isolated network for containers on one host
host
The container uses the host’s network stack, with no network isolation
none
Complete network isolation
overlay
A network spanning several Docker daemons in Swarm
ipvlan
Connects containers to external VLANs
macvlan
The container appears as a separate device on the host’s network
Publishing ports
-p value
What it does
8080:80
Port 8080 on all host addresses → container TCP port 80
127.0.0.1:8080:80
The same, but the port is reachable only from the host itself
192.0.2.10:8080:80
The port on one host address only
8080:80/udp
UDP instead of TCP
8080:80/tcp and 8080:80/udp
Both protocols — two -p flags
Do not change the firewall rules that Docker creates: bridge networks depend on them. The EXPOSE instruction in a Dockerfile does not publish a port — see “Dockerfile instructions”.
Managing networks
Task
Command
Create a network
docker network create appnet
List networks
docker network ls
Subnet and connected containers
docker network inspect appnet
Connect a running container
docker network connect appnet web
Disconnect a container
docker network disconnect appnet web
Remove a network
docker network rm appnet
Remove unused networks
docker network prune
A container can be connected to several networks at once. For example, a frontend can join a network with outside access and an internal network of backend services created with --internal. User-defined networks can be connected and disconnected on the fly; to take a container off the default network, you have to recreate it.
Addresses, DNS and IPv6
Docker picks the subnet for a new network from the default pools: /16 networks from 172.17.0.0/16 to 172.31.0.0/16 and /20 networks from 192.168.0.0/16. If they overlap with your network, set the subnet with --subnet or the pools with default-address-pools in /etc/docker/daemon.json. The --ipv6 flag enables IPv6 for a network.
The embedded DNS server of user-defined networks listens on 127.0.0.11 and forwards external queries to the host’s DNS servers. Containers on the default bridge network get a copy of the host’s /etc/resolv.conf.
NAT, ports and addresses are covered in the TCP/IP and DNS reference; Services and Ingress in the Kubernetes reference, section “Services, Ingress and Gateway API”.
A volume is data storage managed by Docker that survives container removal. Volumes suit databases and anything you can’t lose when a container is recreated; a bind mount mounts a host directory, and tmpfs mounts memory.
Everything a container writes to its own filesystem goes into its writable layer and disappears with the container. Data that must survive recreation goes into a mount: inside the container it looks like an ordinary directory or file.
Volumes and bind mounts keep data on the host’s disk; tmpfs keeps it only in memory.
Volume, bind mount or tmpfs
Aspect
Volume
Bind mount
tmpfs
Where the data lives
in Docker’s directory on the host, usually /var/lib/docker/volumes
in any host directory
in host memory
Managed by
Docker, with docker volume commands
you and any process on the host
the host kernel
Survives container removal
yes
yes
no
When to use
databases, application data
code during development, config files from the host
temporary data
Choose a volume by default: it is easier to back up and migrate, works with both Linux and Windows containers and does not depend on the host’s directory layout. Use a bind mount when the files must be accessible both from the host and from the container.
bashon the host
docker volume create pgdata# the directory postgres:18 declares as a volumedocker run -d --name db \ -e POSTGRES_PASSWORD=change-me \--mount type=volume,src=pgdata,dst=/var/lib/postgresql \ postgres:18
--mount and the short -v form do the same thing: -v pgdata:/var/lib/postgresql. The documentation recommends --mount: it is more explicit and supports all the options.
What to mount
--mount
-v
Named volume
type=volume,src=pgdata,dst=/data
pgdata:/data
Anonymous volume
type=volume,dst=/data
/data
Read-only volume
type=volume,src=pgdata,dst=/data,ro
pgdata:/data:ro
Host directory
type=bind,src=./site,dst=/srv
./site:/srv
tmpfs
type=tmpfs,dst=/tmp
the --tmpfs /tmp flag
Named and anonymous volumes
An anonymous volume gets a random name. Like a named volume, it remains after the container is removed — unless the container was started with --rm, in which case Docker removes its anonymous volumes along with it. Every new container creates a new anonymous volume for itself, so keep data you need in a named volume.
If you mount an empty volume at a directory that already has files in the image, Docker copies them into the volume. A non-empty volume, by contrast, hides what the image has in that directory.
Volume commands
Task
Command
Create a volume
docker volume create pgdata
List volumes
docker volume ls
Where the data lives (the Mountpoint field)
docker volume inspect pgdata
Remove a volume
docker volume rm pgdata
Remove unused anonymous volumes
docker volume prune
Remove all unused volumes
docker volume prune -a
Backing up a volume
A temporary container makes the backup: it mounts the volume and the current host directory and packs the data with tar. Back up the volume of a stopped container so the files don’t change during archiving.
bashbackup, on the host
docker stop dbdocker run --rm \ -v pgdata:/data:ro \ -v "$(pwd)":/backup \ alpine:3.24 tar czf /backup/pgdata.tar.gz -C /data .docker start db
bashrestore, on the host
docker volume create pgdata-restoreddocker run --rm \ -v pgdata-restored:/data \ -v "$(pwd)":/backup \ alpine:3.24 tar xzf /backup/pgdata.tar.gz -C /data
Bind mounts
A bind mount mounts a host directory as is, and by default the container can modify and delete the host’s files. Mount only the directory you need and, where possible, read-only. If the host path does not exist, -v creates the directory, while --mount returns the error bind source path does not exist — or creates the directory if you add the bind-create-src option.
bashon the host
# static site from the host, read-onlydocker run -d -p 8080:80 \--mount type=bind,src=./site,dst=/usr/share/nginx/html,ro \ nginx:1.30
tmpfs
tmpfs stores files in host memory and works only on Linux. The data is lost when the container stops and counts towards its --memory limit. The kernel can move it to swap, so tmpfs does not guarantee that a secret never reaches the disk.
bashon the host
docker run -d --tmpfs /tmp:size=64m myapp:1.0
Volumes in a cluster, including PersistentVolumes, are covered in the Kubernetes reference, section “Storage: volumes and PersistentVolumes”.
Docker Compose describes a multi-container application in a single compose.yaml file and manages it with the docker compose command. docker compose up -d creates the networks and volumes and starts all services; docker compose down stops and removes them.
In Compose, the parts of an application are services: each one runs one or more identical containers from the same image. Services communicate over networks, keep data in volumes and receive configuration and secrets as files through configs and secrets. Together they form a project, named by default after the directory with compose.yaml; the name becomes the prefix of container, network and volume names.
The file defines no networks: Compose connects the services to the project’s default network, and web reaches the database by the service name db. depends_on with the service_healthy condition starts web only after the db health check passes; the short form only waits for the container to start, not for the database to be ready. The default file name is compose.yaml; Compose also finds the older docker-compose.yml.
Commands
Task
Command
Build images and start in the background
docker compose up -d --build
Service status
docker compose ps
Follow a service’s logs
docker compose logs -f web
Run a command in a running service
docker compose exec db psql -U app
Build images
docker compose build
Pull new image versions
docker compose pull
Resolved configuration after interpolation
docker compose config
Stop and remove containers and networks
docker compose down
docker compose down removes the service containers, the networks defined in the file and the default network; volumes are kept. On the next up, anonymous volumes are not attached to the new containers, so keep data in named volumes.
Variables and the .env file
Compose substitutes ${VAR} in unquoted and double-quoted values of the file: this is interpolation. Shell environment variables take precedence, then the file given with the --env-file flag. Without that flag, Compose reads .env in the project directory.
Syntax
Result
${VAR}
the value of VAR
${VAR:-default}
default if VAR is unset or empty
${VAR:?message}
an error with the message if VAR is unset or empty
environment sets container variables directly in the file, and env_file loads a file of variables; if both set the same variable, environment wins. docker compose config shows the resolved file after interpolation: use it to check the configuration before starting.
Profiles and multiple files
A service with profiles: [debug] starts only when that profile is enabled; services without profiles always start.
bashon the host
docker compose --profile debug up -d
Compose merges multiple files in the order of the -f flags: each file adds to and overrides the ones before it. This keeps the common part in compose.yaml and the production differences in a separate file. Paths in the files are relative to the directory of the first file.
bashon the host
docker compose -f compose.yaml -f compose.prod.yaml up -d
Choosing between Compose and Kubernetes is covered in the Kubernetes reference, section “What Kubernetes is and how it works”.
The main threats are access to the Docker daemon, which equals root on the host, excess container privileges and ports exposed to the outside. A container is isolated by kernel namespaces and cgroups, but it shares the kernel with the host, so every weakening of isolation puts the whole server at risk.
Access to the daemon
By default the daemon listens on a Unix socket, not a TCP port. Do not expose the API over TCP without TLS: with such a configuration the daemon refuses to start. To manage a remote server, SSH is simpler:
bashon your machine
# commands go to the remote daemon over SSHdocker context create prod \--docker host=ssh://deploy@203.0.113.10docker context use proddocker ps
Privileges inside the container
Docker starts containers with a reduced set of kernel capabilities, but root in a container still runs on the kernel it shares with the host. Run the application as a regular user and drop the privileges it doesn’t need.
Flag
Effect
--user 10001:10001
The process does not run as root; USER in the Dockerfile does the same
--cap-drop ALL
Drops all capabilities; add back the ones you need one at a time with --cap-add
--security-opt no-new-privileges
su, sudo and setuid programs cannot escalate privileges
--read-only
Read-only root filesystem; writes go only to volumes and tmpfs
without --privileged
--privileged grants all capabilities, disables seccomp and AppArmor and exposes all host devices
bashdon’t do this
docker run -d --privileged \ -v /var/run/docker.sock:/var/run/docker.sock \ myapp:1.0
bashdo this instead
docker run -d \--user 10001:10001 \--cap-drop ALL \--security-opt no-new-privileges \--read-only \--tmpfs /tmp \ -p 127.0.0.1:8000:8000 \ myapp:1.0
Published ports
A port published without an address (-p 8080:80) is open on all host interfaces, including to the internet. ufw rules don’t block it: Docker manages its own iptables rules. If something is needed only on this server, such as a database or an application behind a reverse proxy, publish it on 127.0.0.1.
Rootless mode and user namespaces
In rootless mode, the daemon and the containers run as a regular user inside a user namespace. A vulnerability in the daemon or the runtime then does not give an attacker root on the host. You need newuidmap and newgidmap from the uidmap package and at least 65,536 subordinate UIDs and GIDs for the user in /etc/subuid and /etc/subgid.
bashon the host
# as a regular user, without sudodockerd-rootless-setuptool.sh installsystemctl --user start docker.service
If the daemon has to run as root, enable userns-remap: root inside a container then maps to an unprivileged host UID from the range in /etc/subuid. The value default creates the dockremap user for this. The containerd image store is not available with userns-remap — see “Versions and what’s new”.
json/etc/docker/daemon.json
{ "userns-remap": "default"}
Images and secrets
Use official or verified base images and pin the tag — see “Images and registries”.
Pass build secrets with --secret, not through ARG and ENV — see “Builds: cache, multi-stage and secrets”.
Mount host directories read-only unless the container needs to write to them.
Pod Security and RBAC are covered in the Kubernetes reference, section “Cluster security”; protecting the server itself, in the Linux server hardening reference.
Work from the daemon towards the application: check whether the daemon responds, what state the container is in and which code it exited with, and what the application wrote to its output. If the daemon itself does not start, read its log in systemd.
docker info — checks that the daemon responds. If it doesn’t, see the Cannot connect to the Docker daemon error.
docker ps -a — the container state; for an exited container, the STATUS column shows the exit code.
docker logs -n 50 web — the last lines of the application’s output.
docker inspect --format '{{.State.Health.Status}}' web — the health check result, if a check is defined.
sudo journalctl -xu docker.service — the daemon log, if the daemon won’t start or behaves oddly.
Cannot connect to the Docker daemon
Cause: the daemon is not running, or the client is talking to a daemon on another host — for example, because the DOCKER_HOST variable is set.
sudo systemctl start docker# if DOCKER_HOST was set by mistakeunset DOCKER_HOST
docker commands only work with sudo
Cause: the user is not in the docker group. Only members of this group can reach the daemon socket without sudo, and membership gives root privileges on the host — see “Container security”.
bashcheck
id -nG
bashfix
sudo usermod -aG docker $USER# apply the group without logging outnewgrp docker
port is already allocated
Cause: the host port is already taken by another container or program. The full message is Bind for 0.0.0.0:8080 failed: port is already allocated; another variant of the same error is address is already in use.
bashcheck: the PORTS column
docker ps
bashfix
# free the port or publish on another onedocker stop old-webdocker run -d --name web \ -p 8081:80 \ nginx:1.30
Container won’t start or exits immediately
Cause: the main process finished or crashed, and a container lives only as long as its main process runs. If the container could not be started at all, the exit code of the docker run command itself tells you so.
bashcheck
docker ps -adocker logs web
docker run exit code
Meaning
125
Error in Docker itself, such as an unknown flag
126
The container command cannot be invoked
127
The command is not found in the image
other
The code the container command exited with
Look for the cause in the last lines of docker logs.
The program in the container must run in the foreground and not detach into the background.
Check the image’s CMD and ENTRYPOINT and the docker run arguments: exit code 127 means the command is missing from the image.
Containers can’t find each other by name
Cause: the containers were started without --network and ended up on the default bridge network. Containers can reach each other by name only on a user-defined network.
the following directives are specified both as a flag and in the configuration file
Cause: the same daemon option is set both as a dockerd startup flag and in /etc/docker/daemon.json, and the daemon does not start. Most often it is hosts: on Debian and Ubuntu, systemd always starts dockerd with the -H flag.
bashcheck
sudo journalctl -xu docker.service
Fix: keep the option in one place. If the address is to be set in daemon.json, create /etc/systemd/system/docker.service.d/docker.conf to remove the -H flag from the start command, then restart the daemon with sudo systemctl daemon-reload and sudo systemctl restart docker:
inidocker.conf
[Service]ExecStart=ExecStart=/usr/bin/dockerd
Out of disk space
Cause: images, stopped containers, volumes and build cache pile up on the host’s disk. Check how much space each type of object takes and how much can be freed (RECLAIMABLE):
bashcheck
docker system df# details for every image, container and volumedocker system df -v
textexample output
TYPE TOTAL ACTIVE SIZE RECLAIMABLEImages 5 2 16.43 MB 11.63 MB (70%)Containers 2 0 212 B 212 B (100%)Local Volumes 2 1 36 B 0 B (0%)
Fix: the cleanup commands are collected in the cheat sheet, under “Cleanup”. Delete volumes with data only by hand, by name.
DNS resolver found in resolv.conf and containers can't use it
Cause: the host’s /etc/resolv.conf points to a local DNS server, such as dnsmasq on 127.0.0.1. A container has its own network stack, and for the container this address is the container itself. Docker substitutes public DNS servers, and names from your internal network stop resolving.
bashcheck
ps aux | grep dnsmasq
Fix: set DNS servers for containers in the daemon configuration and restart the daemon with sudo systemctl restart docker.
This reference covers Docker Engine 29. The latest release is 29.9.2, from 20 October 2026. Releases are published in the stable and test channels, and patch releases are always backward compatible with their major and minor version.
Branch
Status
First release
Latest release
29
current, receives releases
29.0.0 — 10 November 2025
29.9.2 — 20 October 2026
28
no releases since November 2025
28.0.0 — 19 February 2025
28.5.2 — 5 November 2025
27
no releases since January 2025
27.0.1 — 24 June 2024
27.5.1 — 22 January 2025
Docker does not publish support periods for its branches: Docker Engine is an open source project maintained by the Moby maintainers and the community. The table shows that the previous branch stops receiving releases around the time the next one comes out. Branch 29 has had a minor release almost every month, so update within the branch regularly.
What changed in 29
Images and registries: the containerd image store is now the default for new installations. This does not apply to daemons with userns-remap: the containerd store is not yet available with it.
Images and registries: by default docker image ls shows a new view — like --tree, but collapsed — and hides untagged images unless --all is given.
Networking and published ports: an experimental nftables firewall backend has been added — the firewall-backend daemon option set to nftables. In this mode Docker does not enable IP forwarding itself.
Containers: with containerd 2.1.5, the default open file limit in a container is 1024 instead of 1048576. If an application needs more, set --ulimit or default-ulimits in daemon.json.
Containers: a new --umask flag for container processes (since 29.8) and the default-stop-timeout daemon option, the default stop timeout (since 29.7).
Volumes, bind mounts and tmpfs: the bind-create-src option of --mount creates a missing host directory (since 29.3); type=image mounts are no longer experimental (since 29.7).
Container security: in rootless mode the default network is gvisor-tap-vsock, and slirp4netns is no longer installed from Docker’s packages (since 29.5).
What Docker is and how it works: in 29.0 the daemon stopped accepting clients with an API version below 1.44 (Docker 25). In 29.3 the minimum went back down to 1.40 (Docker 19.03).
Deprecated and removed
cgroup v1 is deprecated as of 29.0. Support will remain until at least May 2029, but move to cgroup v2; docker info shows the version in the Cgroup Version line.
Docker Content Trust was removed from the CLI in 29.0; it can be built as a separate plugin.
Environment variables of legacy --link links have been deprecated since 28.4, are no longer set by default as of 29.0 and will be removed in 30.0. Use user-defined networks instead of links.
The --time flag of docker stop and docker restart has been deprecated since 28.0; use --timeout (-t).
The --pause flag of docker commit was deprecated in 29.0 and will be removed in 30.0; instead of --pause=false, use --no-pause.
In Dockerfiles, the ENV name value form without an equals sign (since 20.10) and the MAINTAINER instruction (since 1.13) are deprecated: use ENV name=value and LABEL.
As of 29.0, Debian armhf packages are built for ARMv7 and do not work on ARMv6; packages for 32-bit Raspbian are no longer published.
Security updates
ID
Affected
Fixed in
CVE-2026-111943
Registry TLS verification: chains through compromised eMudhra intermediate certificates are now rejected, so pull and push to such registries fail
29.9.2
CVE-2026-95839, GHSA-hc94-p972-ch66
containerd: crash and disk exhaustion when loading a crafted image
docker cp: running container programs with host root privileges and writing to arbitrary locations on the host
29.5.1
CVE-2026-31431
Privilege escalation through the kernel crypto API: seccomp, AppArmor and SELinux profiles hardened
29.4.2, 29.4.3
CVE-2026-34040, CVE-2026-33997
Bypass of authorisation plugins and privilege checks during docker plugin install
29.3.1
CVE-2025-31133, CVE-2025-52565, CVE-2025-52881
runc: container escape through writes to /proc files
28.5.2 and 29.0.0 (runc 1.3.3)
Upgrading
New releases of a branch install over the existing ones with the same package installation command as in “Installation and first run”. Before moving to a new major version, read its release notes: 29.0, for example, contained breaking changes.
Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.
Reference updated
Weekly check
How the reference is checked
Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.
1. Freshness
Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.
2. Errors
Every section is read again: wrong facts, outdated APIs and flags, broken examples.
3. Links — by an HTTP request
Every source link must respond. A broken link is a reason to recheck the section.
No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.
Statuses
Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review