Bookmarks
ReferenceDevOps & cloudVerified

Docker

Docker is a platform for building images and running applications in containers. Covers Dockerfiles, the build cache, volumes, networking, Compose and security.

checked 31 Oct · next check 7 Nov · 48 min read

Sections
13
Reading
48 min
Current version
29.9.2
Written from
docs.docker.com

Check status of the reference

Verified 31 Oct · next check 7 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Docker is and how it works

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

AspectContainerVirtual machine
OS kernelshared with the hosteach machine has its own
What’s insidethe process and the files the application needsa whole OS: kernel, drivers, programs
Isolationnamespaces of the host kernela separate OS with its own kernel
Overheadlow: the same resources fit more applicationshigh 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”.

Section sources

the section is written from these pages

Cheat sheet

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

TaskCommand
Pull an imagedocker pull nginx:1.30
List imagesdocker image ls
Build an image from the current directorydocker build -t myapp:1.0 .
Name an image for your registrydocker tag myapp:1.0 registry.example.com/team/myapp:1.0
Log in to a registrydocker login registry.example.com
Push an image to a registrydocker push registry.example.com/team/myapp:1.0
Show the image’s layersdocker image history myapp:1.0
Remove an imagedocker image rm myapp:1.0

Containers

TaskCommand
Run in the background with a portdocker run -d --name web -p 8080:80 nginx:1.30
Port reachable from this machine onlydocker run -d -p 127.0.0.1:8080:80 nginx:1.30
Throwaway container with a shelldocker run --rm -it ubuntu:26.04 bash
Running containersdocker ps
All containers, including stopped onesdocker ps -a
Stopdocker stop web
Start a stopped containerdocker start web
Restartdocker restart web
Remove a stopped containerdocker rm web
Remove even if runningdocker rm -f web
Enable automatic restartdocker update --restart unless-stopped web

Logs and debugging

TaskCommand
Follow the logsdocker logs -f web
Last 50 lines of the logsdocker logs -n 50 web
Shell in a running containerdocker exec -it web sh
All container settings as JSONdocker inspect web
Health check resultdocker inspect --format '{{.State.Health.Status}}' web
Is the daemon runningdocker info
Daemon logsudo journalctl -xu docker.service

Networks and volumes

TaskCommand
Create a networkdocker network create appnet
Run a container on a networkdocker run -d --name web --network appnet nginx:1.30
Connect a running containerdocker network connect appnet web
List networksdocker network ls
Create a volumedocker volume create pgdata
Run a database with a volumedocker run -d --name db -e POSTGRES_PASSWORD=change-me -v pgdata:/var/lib/postgresql postgres:18
Host directory, read-onlydocker run -d -v ./site:/usr/share/nginx/html:ro nginx:1.30
List volumesdocker volume ls

Compose

TaskCommand
Start the project in the backgrounddocker compose up -d
Rebuild images and restartdocker compose up -d --build
Service statusdocker compose ps
Follow the logs of all servicesdocker compose logs -f
Shell in a servicedocker compose exec web sh
Resolved configuration after interpolationdocker compose config
Pull new image versionsdocker compose pull
Stop and remove containers and networksdocker compose down

Cleanup

TaskCommand
How much space Docker usesdocker system df
Remove dangling imagesdocker image prune
Clear the build cachedocker builder prune
Remove unused anonymous volumesdocker volume prune
Remove stopped containers, unused networks, dangling images and build cachedocker system prune
The same, plus all unused images and anonymous volumesdocker system prune -a --volumes
Remove unused named volumes toodocker volume prune -a
Remove a Compose project with its volumesdocker compose down -v

Section sources

the section is written from these pages

Installation and first run

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.

bashon the host
sudo apt remove $(dpkg --get-selections docker.io docker-compose \  docker-compose-v2 docker-doc docker-buildx podman-docker \  containerd runc | cut -f1)

Ubuntu and Debian

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:

bashDebian
Suites: $(. /etc/os-release && echo "$VERSION_CODENAME")

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.

Section sources

the section is written from these pages

Images and registries

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.
ReferenceWhat it resolves to
nginxdocker.io/library/nginx:latest
nginx:1.30docker.io/library/nginx:1.30
registry.example.com:5000/team/myapp:1.0registry 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

TaskCommand
Pull an imagedocker image pull (docker pull)
List imagesdocker image ls (docker images)
Layers and the commands that created themdocker image history
All metadata as JSONdocker image inspect
Give an image a new namedocker image tag (docker tag)
Push to a registrydocker image push (docker push)
Remove an imagedocker image rm
Remove unused imagesdocker image prune
Save to a tar archive and load it backdocker 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.

Section sources

the section is written from these pages

Dockerfile instructions

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-slim WORKDIR /appENV FLASK_APP=app # dependencies first: this layer rarely changesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt COPY . . # the application process does not run as rootRUN useradd --no-log-init --uid 10001 appUSER app EXPOSE 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

InstructionWhat it doesWhen it applies
FROMStarts a build stage from a base imagebuild
WORKDIRWorking directory for the instructions that follow; created if it doesn’t existbuild and run
COPYCopies files from the build context or another stagebuild
ADDLike COPY, but also downloads from URLs and Git and extracts local tar archivesbuild
RUNRuns a command and saves the result as a new layerbuild
ENVEnvironment variable: available during the build and kept in the containerbuild and run
ARGBuild-only variable, set with --build-argbuild
USERUser for subsequent RUN instructions and for the container processbuild and run
EXPOSEDocuments the port the application listens on; does not publish ita hint for running
CMDDefault command when the container startsrun
ENTRYPOINTMakes the container run as a specific programrun
HEALTHCHECKCommand that checks whether the application is workingrun
LABELImage metadatabuild

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.

Dockerfiledocker run myappWith arguments
CMD ["flask", "run"]flask rundocker run myapp bash → bash
ENTRYPOINT ["flask"]flaskdocker run myapp run → flask run
ENTRYPOINT ["flask"] and CMD ["run"]flask rundocker 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.

dockerfileDockerfile
ARG APP_VERSION=devLABEL org.opencontainers.image.version=$APP_VERSIONENV APP_ENV=production
bashon the host
docker build --build-arg APP_VERSION=1.0 -t myapp:1.0 .

COPY or ADD

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.

dockerfileDockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \  CMD python -c "import urllib.request as u; u.urlopen('http://localhost:8000')"
OptionWhat it setsDefault
--intervalTime between checks30s
--timeoutHow long to wait for a single check30s
--start-periodStartup time during which failures don’t count0s
--start-intervalTime between checks during startup5s
--retriesConsecutive failures that make the container unhealthy3

.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.

Section sources

the section is written from these pages

Builds: cache, multi-stage and secrets

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
FROM python:3.15-slimWORKDIR /appCOPY requirements.txt .RUN pip install -r requirements.txtCOPY . .

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

FlagWhat it doesDefault
-t myapp:1.0Image name and tag; the flag can be repeated—
-f build.DockerfileA different DockerfileDockerfile in the context
--build-arg NAME=valueValue for an ARG—
--target buildBuild up to the given stage—
--platform linux/arm64Platform of the imagethe builder’s platform
--no-cacheBuild without the cache—
--pullAlways pull fresh base images—
--secret id=…Pass a build secret—
--pushPush 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”.

Section sources

the section is written from these pages

Containers: running and lifecycle

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.

FlagWhat it doesDefault
-dRun in the background and print the container IDin the foreground
--name webContainer namea random name
-p 8080:80Publish container port 80 on host port 8080no ports published
-e KEY=value, --env-file app.envEnvironment variablesfrom the image
-v, --mountMount a volume or a host directory—
--rmRemove the container and its anonymous volumes on exitthe container is kept
-itInteractive terminal—
--restartRestart policyno
-m 512m, --cpus 1.5Memory and CPU limitsno limits
--initAn 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

PolicyWhen Docker restarts the container
noNever; the default policy
on-failure[:N]When it exits with a non-zero code; N limits the number of attempts
alwaysAlways; a manually stopped container only after the daemon restarts
unless-stoppedLike 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

Section sources

the section is written from these pages

Networking and published ports

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

DriverUse
bridgeDefault: an isolated network for containers on one host
hostThe container uses the host’s network stack, with no network isolation
noneComplete network isolation
overlayA network spanning several Docker daemons in Swarm
ipvlanConnects containers to external VLANs
macvlanThe container appears as a separate device on the host’s network

Publishing ports

-p valueWhat it does
8080:80Port 8080 on all host addresses → container TCP port 80
127.0.0.1:8080:80The same, but the port is reachable only from the host itself
192.0.2.10:8080:80The port on one host address only
8080:80/udpUDP instead of TCP
8080:80/tcp and 8080:80/udpBoth 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

TaskCommand
Create a networkdocker network create appnet
List networksdocker network ls
Subnet and connected containersdocker network inspect appnet
Connect a running containerdocker network connect appnet web
Disconnect a containerdocker network disconnect appnet web
Remove a networkdocker network rm appnet
Remove unused networksdocker 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”.

Section sources

the section is written from these pages

Volumes, bind mounts and tmpfs

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

AspectVolumeBind mounttmpfs
Where the data livesin Docker’s directory on the host, usually /var/lib/docker/volumesin any host directoryin host memory
Managed byDocker, with docker volume commandsyou and any process on the hostthe host kernel
Survives container removalyesyesno
When to usedatabases, application datacode during development, config files from the hosttemporary 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 volumetype=volume,src=pgdata,dst=/datapgdata:/data
Anonymous volumetype=volume,dst=/data/data
Read-only volumetype=volume,src=pgdata,dst=/data,ropgdata:/data:ro
Host directorytype=bind,src=./site,dst=/srv./site:/srv
tmpfstype=tmpfs,dst=/tmpthe --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

TaskCommand
Create a volumedocker volume create pgdata
List volumesdocker volume ls
Where the data lives (the Mountpoint field)docker volume inspect pgdata
Remove a volumedocker volume rm pgdata
Remove unused anonymous volumesdocker volume prune
Remove all unused volumesdocker 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”.

Section sources

the section is written from these pages

Docker Compose

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.

yamlcompose.yaml
services:  web:    build: .    ports:      - "127.0.0.1:8000:8000"    environment:      DATABASE_URL: postgresql://app:${DB_PASSWORD}@db:5432/app    depends_on:      db:        condition: service_healthy    restart: unless-stopped   db:    image: postgres:18    environment:      POSTGRES_USER: app      POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}    volumes:      - pgdata:/var/lib/postgresql    healthcheck:      test: ["CMD", "pg_isready", "-U", "app"]      interval: 10s      retries: 5 volumes:  pgdata:
ini.env
DB_PASSWORD=change-me

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

TaskCommand
Build images and start in the backgrounddocker compose up -d --build
Service statusdocker compose ps
Follow a service’s logsdocker compose logs -f web
Run a command in a running servicedocker compose exec db psql -U app
Build imagesdocker compose build
Pull new image versionsdocker compose pull
Resolved configuration after interpolationdocker compose config
Stop and remove containers and networksdocker 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.

SyntaxResult
${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”.

Section sources

the section is written from these pages

Container security

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.

FlagEffect
--user 10001:10001The process does not run as root; USER in the Dockerfile does the same
--cap-drop ALLDrops all capabilities; add back the ones you need one at a time with --cap-add
--security-opt no-new-privilegessu, sudo and setuid programs cannot escalate privileges
--read-onlyRead-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.

Section sources

the section is written from these pages

Common errors and troubleshooting

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.

  1. docker info — checks that the daemon responds. If it doesn’t, see the Cannot connect to the Docker daemon error.
  2. docker ps -a — the container state; for an exited container, the STATUS column shows the exit code.
  3. docker logs -n 50 web — the last lines of the application’s output.
  4. docker inspect --format '{{.State.Health.Status}}' web — the health check result, if a check is defined.
  5. 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.

bashcheck
sudo systemctl is-active dockerenv | grep DOCKER_HOST
bashfix
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 codeMeaning
125Error in Docker itself, such as an unknown flag
126The container command cannot be invoked
127The command is not found in the image
otherThe 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.

bashcheck: the default network
docker network inspect bridge
bashfix
docker network create appnetdocker network connect appnet webdocker network connect appnet db

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.

json/etc/docker/daemon.json
{  "dns": ["192.0.2.53", "8.8.8.8"]}

Section sources

the section is written from these pages

Versions and what’s new

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.

BranchStatusFirst releaseLatest release
29current, receives releases29.0.0 — 10 November 202529.9.2 — 20 October 2026
28no releases since November 202528.0.0 — 19 February 202528.5.2 — 5 November 2025
27no releases since January 202527.0.1 — 24 June 202427.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

IDAffectedFixed in
CVE-2026-111943Registry TLS verification: chains through compromised eMudhra intermediate certificates are now rejected, so pull and push to such registries fail29.9.2
CVE-2026-95839, GHSA-hc94-p972-ch66containerd: crash and disk exhaustion when loading a crafted image29.9.1
CVE-2026-97032, CVE-2026-78659, CVE-2026-78663, CVE-2026-78669Daemon API over HTTP/2: denial of service29.9.0
CVE-2026-92543A spoofed DNS response disabled registry TLS verification or downgraded the connection to HTTP29.8.2
CVE-2026-93315, CVE-2026-93316, CVE-2026-93317, CVE-2026-93318, CVE-2026-93319, CVE-2026-93320, CVE-2026-93321, CVE-2026-93322, CVE-2026-93323, CVE-2026-93326BuildKit: build cache poisoning, daemon crash, source policy bypass29.8.2
CVE-2026-15793BuildKit: command injection via a Git bundle29.6.2
CVE-2026-41567, CVE-2026-41568, CVE-2026-42306docker cp: running container programs with host root privileges and writing to arbitrary locations on the host29.5.1
CVE-2026-31431Privilege escalation through the kernel crypto API: seccomp, AppArmor and SELinux profiles hardened29.4.2, 29.4.3
CVE-2026-34040, CVE-2026-33997Bypass of authorisation plugins and privilege checks during docker plugin install29.3.1
CVE-2025-31133, CVE-2025-52565, CVE-2025-52881runc: container escape through writes to /proc files28.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.

bashon the host
sudo apt updatesudo apt install docker-ce docker-ce-cli containerd.io \  docker-buildx-plugin docker-compose-plugin

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 1 entry

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.

  1. 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. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 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

Last check

3 Nov · Check · no changes · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Docker” topic
14 sections
Another reference · DevOps & cloud

Kubernetes

Verified 1 Nov
All references · 61