Docker commands

Docker CLI commands checked against the Docker Docs command reference, one literal command line per row: running and inspecting containers, images, builds with Buildx, volumes, networks, Compose, cleanup and contexts. Swarm, Scout and other plugin commands are left out. Most container and image commands have a short form such as docker ps and a long form such as docker container ls; both are listed. Example names like mycontainer or nginx come from the reference.

386 commands in 19 sections. Checked row by row against Docker Docs: docker CLI reference on . Edited by Jay.

Running containers 37

CommandWhat it does
docker runRun a new containerCreates a container from an image and starts it; a missing image is pulled first.
docker run -it IMAGE shOpen a shell in a new containerWorks when the image has sh on its PATH; -i keeps input open and -t gives it a terminal.
docker run -it debianRun interactivelyWith no command given, the image default starts, attached to a terminal you can type into.
docker run -d IMAGE_NAMERun in the backgroundDetached mode prints the ID of the new container and hands the prompt back.
docker run -d -p 80:80 my_image nginx -g 'daemon off;'Run a detached web serverA detached container stops when its root process returns, so the server is kept in the foreground.
docker run --name test -d nginx:alpineRun with a chosen nameLater commands can address the container as test; without --name the daemon invents a random one.
docker run -d -p 8080:80 nginxPublish a portRequests to port 8080 on the host are forwarded to port 80 inside the container.
docker run -p 127.0.0.1:80:8080/tcp nginx:alpinePublish on one host addressMaps container port 8080 to TCP port 80 on 127.0.0.1 only; with no address every interface is used.
docker run -P nginx:alpinePublish all exposed portsEach port the image marks as exposed gets a random free port on the host.
docker run --expose 80 nginx:alpineExpose a port without publishingMarks port 80 as exposed for -P and other containers; nothing is opened on the host.
docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bashSet environment variablesThree ways at once: a name passed through from the shell, a name=value pair and a file of variables.
docker run -e "deep=purple" -e today --rm alpine envPass a host variable throughA name with no value, here today, takes whatever that variable holds on the host.
docker run --env-file env.list ubuntu env | grep -E 'VAR|USER'Load variables from a fileLines are VARIABLE=value or a bare name read from the local environment; lines starting with # are skipped.
docker run -v ./content:/content -w /content -i -t ubuntu pwdBind-mount a host folderMounts the content folder at /content and works from there; relative host paths need Engine 23 or newer.
docker run -t -i --mount type=bind,src=/data,dst=/data busybox shMount with --mount syntaxSame job as -v written as key=value fields; the reference recommends this form.
docker run -d -v hello:/world busybox ls /worldMount a named volumeThe volume hello, created beforehand, appears inside the container at /world.
docker run -w /path/to/dir/ ubuntu pwdSet the working directoryThe command runs in that directory, which is created inside the container when it is missing.
docker run --read-only -v /icanwrite busybox touch /icanwrite/hereRead-only root filesystemWriting then works only under the volumes you mount, here /icanwrite.
docker run -d --tmpfs /run:rw,noexec,nosuid,size=65536k my_imageMount an in-memory tmpfsThe text after the colon uses the same option names as the Linux tmpfs mount.
docker run --rm -v /foo -v awesome:/bar busybox topRemove the container on exitOn exit the container and its anonymous volume /foo are deleted; the named volume awesome survives.
echo hello | docker run --rm -i busybox catPipe input into a containerWith -i and no -t, standard input stays open so the container can sit in a shell pipeline.
docker run -itd --network=my-net busyboxRun on a chosen networkOn a user-created bridge network, containers can reach each other by container name.
docker run --restart=always redisRestart automaticallyDocker starts the container again whenever it exits; the default policy is no.
docker run --restart=on-failure:10 redisRestart on failure, with a limitRestarts only after a non-zero exit status and gives up after ten failures in a row.
docker run -d --name redis --restart unless-stopped redisRestart unless stopped by handComes back after a crash or a daemon restart, but stays down once you stop it yourself.
docker run -it -m 300M ubuntu:24.04 /bin/bashLimit memoryCaps the processes in the container at 300M of memory.
docker run -it --cpus=".5" ubuntu /bin/bashLimit CPU timeOn a one-CPU host this holds the container to at most half of the CPU every second.
docker run -it --rm --gpus all ubuntu nvidia-smiGive access to NVIDIA GPUsNeeds the NVIDIA container runtime on the host; a device= value picks single GPUs instead of all.
docker run -it --entrypoint /bin/bash example/redisOverride the entrypointStarts Bash in place of the binary the image is set up to launch.
docker run --pull=never hello-worldRun without pullingFails with an error when the image is not in the local cache, where the default would download it.
docker run --add-host=my-hostname=8.8.8.8 --rm -it alpineAdd a hosts-file entryWrites the name and its address into /etc/hosts inside the container.
docker run -l my-label --label com.example.foo=bar ubuntu bashLabel a containerLabels are metadata that filters such as docker ps --filter label= can match.
docker run -t -i --privileged ubuntu bashRun with full privilegesTurns on all kernel capabilities and host device access; the reference says to use it with caution.
docker createCreate without startingPrepares a container from an image and prints its ID; it stays in the created state until started.
docker container create -i -t --name mycontainer alpineCreate an interactive containerSets up a terminal-ready container for later; nothing runs yet.
docker container start --attach -i mycontainerStart and attachTogether with the create line above, this equals one docker run -it.
docker startStart stopped containersTakes one or more names or IDs; -a attaches the output and -i the input.

Listing containers and reading logs 29

CommandWhat it does
docker psList running containersOnly running containers appear by default, which is why an exited one seems to be missing.
docker ps -aList all containersAdds stopped and exited containers to the list.
docker ps --no-truncShow untruncated outputPrints full container IDs and complete commands in place of the shortened columns.
docker ps --sizeShow disk use per containerAdds a SIZE column with two on-disk figures for each container; -s is the short flag.
docker ps --filter status=runningFilter by statusOther values include created, restarting, paused, exited and dead.
docker ps -a --filter 'exited=0'Filter by exit codeFinds containers that finished successfully; any other code, such as 137, works the same way.
docker ps --filter "name=nostalgic"Filter by nameMatches every container whose name contains the given text.
docker ps --filter ancestor=ubuntuFilter by imageLists containers started from that image; with no tag written, latest is assumed.
docker ps --filter "label=color=blue"Filter by labelGive a label key alone to match any value, or key=value for an exact match.
docker ps --format "{{.ID}}: {{.Command}}"Print chosen fieldsA Go template replaces the table; start it with the word table to keep column headers.
docker ps --format jsonOutput as JSON
docker ps -q --filter ancestor=nginx:alpinePrint container IDs onlyThe quiet flag leaves just the IDs, ready to feed into another command.
docker logsShow container logsPrints what the container has logged up to now and returns.
docker logs -f CONTAINER_NAMEFollow the logsKeeps the command attached and prints new STDOUT and STDERR lines as the container writes them.
docker logs -n 5 0246aa4d1448Show the last linesPrints only the final five lines; the long flag is --tail.
docker logs --timestampsPrefix lines with timestampsEach entry starts with an RFC 3339 timestamp with nanoseconds.
docker logs -f --until=2s testShow logs up to a timeStops at entries older than two seconds; --since sets the opposite boundary.
docker inspectInspect any objectReturns low-level details of containers, images, networks or volumes as a JSON array.
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $INSTANCE_IDGet a container IP addressA Go template pulls one value out of the JSON, here the address on each network.
docker inspect --format='{{.LogPath}}' $INSTANCE_IDFind the log file path
docker inspect --type=volume myvolumeInspect by object typeSettles which object is meant when a container and a volume share one name.
docker inspect --size mycontainerInclude container sizeAdds SizeRootFs and SizeRw, the total size and the size of the writable layer.
docker statsLive resource usageStreams CPU, memory, network and block I/O figures for every running container.
docker stats awesome_brattain 67b2525d8ad1Watch selected containersNames and IDs can be mixed; stopped containers return no data.
docker stats nginx --no-stream --format "{{ json . }}"One-off stats as JSONTakes a single sample and exits, so the result can go straight into a script.
docker topList processes in a containerAnything after the container name is handed to ps as options.
docker portShow port mappingsLists which host ports are bound to the ports of one container.
docker port test 7890/tcpLook up one port mappingAnswers with the host address bound to that container port and protocol.
docker diffList changed filesMarks each path A for added, D for deleted or C for changed since the container was created.

Commands and files inside containers 17

CommandWhat it does
docker execRun a command in a containerNeeds a running container; the extra process ends when the main process does.
docker exec -it mycontainer shOpen a shell in a containerStarts a new interactive shell session next to the main process.
docker exec -d mycontainer touch /tmp/execWorksRun a command in the backgroundWith -d the command is started inside the container and the prompt comes straight back.
docker exec -e VAR_A=1 -e VAR_B=2 mycontainer envRun with extra variablesThe variables exist only for this one process, not for others in the container.
docker exec -it -w /root mycontainer pwdRun in another directoryWithout -w the command starts in the working directory set when the container was created.
docker exec -it my_container sh -c "echo a && echo b"Run chained commandsA chained or quoted command must go through a shell, because exec expects one executable.
docker attachAttach to a running containerConnects the terminal to the main process; Ctrl-p Ctrl-q detaches again if it was started with -i and -t.
docker attach topdemoAttach by nameShows what the main process prints from now on, which can look like a hang when it is silent.
docker cpCopy files to or from a containerOne side is CONTAINER:PATH, the other a local path; the container may be running or stopped.
docker cp ./some_file CONTAINER:/workCopy a file into a container
docker cp CONTAINER:/var/logs/ /tmp/app_logsCopy a folder out of a container
docker cp CONTAINER:/var/logs/app.log - | tar x -O | grep "ERROR"Stream a file to stdoutA dash as destination makes cp write a tar stream, which tar then unpacks to the pipe.
docker exportExport a container filesystemWrites a tar archive of the filesystem to STDOUT; data in mounted volumes is left out.
docker export --output="latest.tar" red_pandaExport to a tar fileSame result as redirecting the output with > latest.tar.
docker commitSave a container as an imageTurns the file changes and settings of a container into a new image; volume data is not included.
docker commit c3f279d17e0a svendowideit/testimage:version3Commit with a repository tagThe container is paused while the image is written unless pausing is switched off.
docker commit --change "ENV DEBUG=true" c3f279d17e0a svendowideit/testimage:version3Commit with a Dockerfile changeApplies a Dockerfile instruction such as ENV, CMD or EXPOSE to the image being created.

Stopping and removing containers 18

CommandWhat it does
docker stopStop running containersSends SIGTERM first and SIGKILL after a grace period, 10 seconds by default on Linux.
docker restartRestart containersStops and starts each listed container; -t sets how long to wait before killing it.
docker killKill running containersSends SIGKILL to the main process at once, with no grace period.
docker kill --signal=SIGHUP my_containerSend another signalThe signal can be a name with or without the SIG prefix, or its number.
docker pausePause containersSuspends every process in the container; on Linux this uses the freezer cgroup, so the processes do not notice.
docker unpauseResume paused containersLets the suspended processes of the listed containers carry on.
docker waitWait for containers to stopBlocks the shell until the container exits, then prints its exit code.
docker renameRename a containerTakes the current name or ID first and the new name second.
docker updateChange container limitsAdjusts CPU, memory and restart settings on existing containers; not supported for Windows containers.
docker update --cpu-shares 512 -m 300M abebf7571666 hopeful_morseUpdate several containersSets a CPU weight and a memory limit on two containers in one call.
docker update --restart unless-stopped redisChange the restart policyWorks on a container that is already running, without recreating it.
docker update --restart unless-stopped $(docker ps -q)Set a policy on every containerThe inner command supplies the IDs of all running containers.
docker rmRemove containersDeletes stopped containers by name or ID; a running one needs --force.
docker rm --force redisForce-remove a running containerThe main process receives SIGKILL and the container is then deleted.
docker rm --volumes redisRemove with anonymous volumesVolumes that were given a name are kept; -v is the short flag.
docker rm $(docker ps --filter status=exited -q)Remove all exited containersThe inner ps prints the IDs of exited containers and rm deletes them; the syntax depends on the shell.
docker ps --filter status=exited -q | xargs docker rmRemove exited containers with xargs
docker container prune --force --filter "until=5m"Prune older stopped containersDeletes stopped containers created more than five minutes ago and skips the confirmation prompt.

Container commands in long form 25

The long docker container forms and the short top-level commands run the same code: docker container ls, docker container list, docker container ps and docker ps are one command.

CommandWhat it does
docker container runRun a new containerFull name of docker run; takes the image, then an optional command and its arguments.
docker container createCreate without startingShares most options with run, which itself performs a create before starting.
docker container startStart stopped containersBrings existing containers back up with the configuration they were created with.
docker container stopStop running containersThe first signal can be changed with -s, and the wait before the kill with -t.
docker container restartRestart containersAccepts the same -s signal and -t timeout flags as stop.
docker container killKill running containersWith -s a different signal is sent, which may leave the container running.
docker container pausePause containersOn Windows only Hyper-V containers can be paused.
docker container unpauseResume paused containersReverses pause through the same freezer cgroup on Linux.
docker container waitWait for containers to stopSeveral containers can be listed; one exit code is printed for each.
docker container rmRemove containersAlso spelled docker container remove; -f removes a running container and -v its anonymous volumes.
docker container pruneRemove all stopped containersAsks for confirmation first, then reports the deleted IDs and the space reclaimed.
docker container renameRename a containerThe container keeps its ID; only the name other commands refer to is replaced.
docker container updateChange container limitsA container started with --rm cannot have its restart policy changed.
docker container lsList containersThree other spellings do the same job: container list, container ps and plain docker ps.
docker container inspectInspect containersLike docker inspect but limited to containers; -s adds total file sizes.
docker container logsShow container logsTakes exactly one container; --since and --until narrow the time range.
docker container statsLive resource usageWith -a, stopped containers are listed too, and --no-stream prints a single reading.
docker container topList processes in a containerShows the processes running inside one container, seen from the host.
docker container portShow port mappingsAn optional port and protocol after the name narrows the answer to one mapping.
docker container diffList changed filesThe container can be named by full ID, short ID or name.
docker container execRun a command in a containerFails with an error while the container is paused.
docker container attachAttach to a running containerSeveral terminals can attach to the same container at once; --no-stdin attaches output only.
docker container cpCopy files to or from a containerContainer paths are taken relative to its root directory, so the leading slash is optional.
docker container exportExport a container filesystemThe -o flag writes the archive to a file without shell redirection.
docker container commitSave a container as an imageFlags -a and -m record an author and a commit message with the image.

Pulling and listing images 18

CommandWhat it does
docker pullPull an imageFetches from Docker Hub unless the name starts with a registry host; with no tag written, latest is used.
docker image pull debian:bookwormPull a specific tagLayers already stored for another tag of the repository are reused, so only the missing parts download.
docker pull ubuntu@sha256:2e863c44b718727c860746568e1d54afd13b2fa71b160f5cd9058fc436217b30Pull by digestA digest pins one exact image version, so later updates of the tag are not picked up.
docker image pull myregistry.local:5000/testing/test-imagePull from another registryRegistry host and port go in front of the repository path, with no https:// prefix.
docker image pull --all-tags ubuntuPull every tag of a repositoryWithout the flag only one image is fetched, the one tagged latest.
docker pull --platform=linux/riscv64 alpine:latestPull for another platformFetches the variant built for that OS and architecture instead of the one matching the host.
docker imagesList local imagesShows repository, tag, ID, age and size; intermediate layers and untagged images stay hidden unless -a is added.
docker images java:8List by repository and tagThe name has to match exactly: docker images jav would not list the java image.
docker images --no-truncShow full image IDsPrints the whole sha256 identifier where the table normally shows twelve characters.
docker images --digestsShow image digestsAdds a DIGEST column with the content-addressable identifier that v2 registries assign.
docker images --filter "dangling=true"List dangling imagesShows untagged leftovers, typically what remains after a rebuild took over the repo:tag.
docker images --filter "label=com.example.version"Filter images by labelMatches any image carrying that label key; append =value to require a particular value.
docker images --filter "before=image1"Filter by creation orderKeeps images created earlier than image1; the since filter gives the later ones.
docker images --filter=reference='busy*:*libc'Filter by name patternWildcards work in both the repository part and the tag part of the pattern.
docker images --format "{{.ID}}: {{.Repository}}"Print chosen image fieldsA Go template replaces the table; other placeholders include .Tag, .Digest, .CreatedSince and .Size.
docker image ls --treeShow platform variants as a treeExperimental view that nests the per-platform entries under each multi-platform image.
docker historyShow image layer historyOne line per layer, with the instruction that made it, its age and its size.
docker history --format "{{.ID}}: {{.CreatedSince}}" busyboxPrint chosen history fieldsPlaceholders such as .CreatedBy, .Size and .Comment select what each line contains.

Tagging, saving and removing images 18

CommandWhat it does
docker tagTag an imageGives an existing image a further name; the source may be an ID, a name or a name with tag.
docker tag httpd fedora/httpd:version1.0Tag by image nameNames the local httpd image version1.0 in the fedora repository.
docker tag 0e5574283393 myregistryhost:5000/fedora/httpd:version1.0Tag for a private registryThe registry host and port must be part of the name before the image can be pushed there.
docker rmiRemove imagesRemoving by tag only drops that tag while other tags still point at the image; registries are not touched.
docker rmi -f fd484f19954fForce-remove by image IDNeeded when one ID carries several tags: all of them are untagged and the image is deleted.
docker rmi $(docker images -f "dangling=true" -q)Remove dangling imagesThe inner command supplies the IDs of all untagged images.
docker image prune -aRemove every unused imageGoes beyond dangling images and also deletes tagged ones that no container refers to.
docker image prune -a --force --filter "until=240h"Prune images older than a cutoffSkips the confirmation and removes only unused images created more than 240 hours ago.
docker image prune --filter="label=deprecated"Prune images by labelLimits the cleanup to images carrying that label; label!= inverts the test.
docker saveSave images to a tar fileWrites to STDOUT unless -o names a file; all parent layers and tags go into the archive.
docker save -o fedora-latest.tar fedora:latestSave one tag to a fileNaming repo:tag stores just that image; the bare repository name would store every tag.
docker save myimage:latest | gzip > myimage_latest.tar.gzSave as a gzip archiveThe tar stream on STDOUT is piped through gzip before it reaches the disk.
docker loadLoad images from a tar archiveReads STDIN unless -i names a file; images and their tags are restored, compressed archives included.
docker load --input fedora.tarLoad from a file
docker load < busybox.tar.gzLoad from standard inputShell redirection feeds the archive in; gzip, bzip2, xz and zstd files are unpacked on the fly.
docker importImport a tarball as an imageTurns a filesystem archive from a file, a URL or STDIN into a new image.
docker import https://example.com/exampleimage.tgzImport from a URLThe result is an untagged image; add a repository name as last argument to tag it.
cat exampleimage.tgz | docker import - exampleimagelocal:newImport from a pipeThe dash stands for STDIN, and the last argument tags the new image.

Image commands in long form 12

CommandWhat it does
docker image lsList local imagesAlso spelled docker image list or docker images; an optional repository name narrows the list.
docker image pullPull an imageThe argument is a name with an optional tag or digest; -q hides the progress output.
docker image pushPush an imageTakes one name with an optional tag; -a pushes all tags of the repository.
docker image buildBuild an imageOne of the spellings of docker build; -t names the result and -f picks the Dockerfile.
docker image tagTag an imageSource comes first and the new name second; each may carry its own tag.
docker image inspectInspect imagesPrints the stored configuration and metadata as JSON; -f extracts single values with a template.
docker image historyShow image layer historyWith --no-trunc the full creating command of every layer is printed, and -q leaves only IDs.
docker image saveSave images to a tar fileSeveral images can be listed; --platform limits the archive to chosen platform variants.
docker image loadLoad images from a tar archiveTakes no positional argument: the archive arrives on STDIN or through -i.
docker image importImport a tarball as an imageFlag -c applies Dockerfile instructions to the result and -m stores a commit message.
docker image rmRemove imagesAlso spelled docker image remove or docker rmi; an image used by a running container needs -f.
docker image pruneRemove dangling imagesAsks before deleting; untagged images go by default, and -a widens that to all unused ones.

Registry login, search and push 14

CommandWhat it does
docker loginLog in to a registryWith no server named it signs in to Docker Hub, by default through a device-code page in the browser.
docker login registry.example.comLog in to a self-hosted registryAdd a port after the host when the registry does not listen on 443 or 80.
docker login -u mobyLog in with a usernameThe password or access token is then typed at an interactive prompt.
cat ~/my_password.txt | docker login --username foo --password-stdinLog in without a promptTaking the password from STDIN keeps it out of the shell history and log files.
docker logoutLog out of a registryWhen no server is given, the default registry of the daemon is the one signed out of.
docker logout localhost:8080Log out of one registry
docker searchSearch Docker HubLists matching repositories with their description, star count and an official marker.
docker search --filter is-official=true --filter stars=3 busyboxSearch official images onlyFilters add up: here only official images with at least three stars come back.
docker search --filter=stars=3 --no-trunc busyboxShow full descriptionsStops the DESCRIPTION column from being cut short.
docker search --format "{{.Name}}: {{.StarCount}}" nginxPrint chosen search fieldsThe template can also use .Description, .IsOfficial and the word table for column headers.
docker pushPush an imageUploads to Docker Hub or the registry named in the image name; five layers are sent in parallel by default.
docker image tag rhel-httpd:latest registry-host:5000/myadmin/rhel-httpd:latestTag before pushingThe new name carries the registry host, which decides where the push will go.
docker image push registry-host:5000/myadmin/rhel-httpd:latestPush to a self-hosted registry
docker image push --all-tags registry-host:5000/myname/myimagePush every tagSends all local tags of that repository in one command.

Building images 21

docker build, docker image build and docker builder build are aliases of docker buildx build, so the same options apply to all four spellings.

CommandWhat it does
docker buildBuild an imageAlias of docker buildx build; the last argument is the build context: a path, a URL or a dash.
docker build -t IMAGE_NAME .Build and tag from this folderThe dot makes the current directory the build context, where the Dockerfile is looked for.
docker buildx build -t docker/fedora-jboss:latest -t docker/fedora-jboss:v2.1 .Apply several tagsRepeat -t to give one build result more than one repository name or version.
docker buildx build -f path/to/Dockerfile .Use another DockerfileWithout -f, the file named Dockerfile at the root of the context is read.
docker buildx build --build-arg HTTP_PROXY=http://10.20.30.2:1234 --build-arg FTP_PROXY=http://40.50.60.5:4567 .Set build argumentsEach flag fills one ARG of the Dockerfile; unlike ENV, the values do not stay in the image.
docker buildx build -t mybuildimage --target build-env .Build up to one stageIn a multi-stage Dockerfile the named stage becomes the result and the ones after it are skipped.
docker buildx build --platform=linux/amd64,linux/arm64,linux/arm/v7 .Build for several platformsThe default image store cannot load a multi-platform result, so push it or switch to the containerd store.
docker buildx build --load --progress=plain .Show plain build outputPrints the raw output of every step as plain text; --load puts the result into the local image list.
--no-cacheBuild without the cacheA docker build flag: every instruction runs again, ignoring layers cached by earlier builds.
--pullAlways pull base imagesA docker build flag: the registry is asked for newer versions of each image the Dockerfile references.
docker buildx build --no-cache-filter install .Skip the cache for one stageOnly the stage called install is rebuilt from scratch; several names are separated by commas.
docker buildx build -o outdir .Export files instead of an imageThe local exporter writes the files of the build result into that folder on the client.
docker buildx build -t TAG --annotation "foo=bar" --push .Build, annotate and pushThe --push flag sends the result straight to the registry named in the tag.
docker buildx build --secret id=aws,src=$HOME/.aws/credentials .Pass a secret fileA RUN step reads it through a type=secret mount, which keeps credentials out of the image layers.
docker buildx build --ssh default=$SSH_AUTH_SOCK .Forward the SSH agentRUN steps with a type=ssh mount can then reach private repositories with your keys.
docker buildx build --cache-from=type=registry,ref=user/app .Reuse cache from a registryImports build cache that an earlier build exported to that registry reference.
docker buildx build --cache-to=type=inline .Embed cache metadata in the image
docker buildx build -q --check https://github.com/docker/docs.gitRun build checks onlyEvaluates the checks for the Dockerfile, here in a Git repository, without executing the build.
docker builder pruneClear the build cacheFrees cache only; containers, networks and images stay, unlike with docker system prune.
docker builder prune -aClear all unused build cacheWithout -a only dangling cache records are removed.
docker initScaffold Docker files for a projectAsks a few questions, then writes a Dockerfile, compose.yaml, .dockerignore and README.Docker.md.

Buildx builders and cache 31

CommandWhat it does
docker buildx buildStart a BuildKit buildThe long form behind docker build; docker buildx b is a further short spelling.
docker buildx bakeBuild targets from a fileRuns the targets defined in an HCL, JSON or Compose file, in parallel.
docker buildx bake -f docker-bake.dev.hcl db webapp-releaseBake chosen targetsNames the definition file with -f, then lists just the targets to build.
docker buildx bake -f docker-bake.hcl --print dbPreview a bake targetShows the resolved build options for the target as JSON and builds nothing.
docker buildx bake --list=targetsList bake targetsReads the bake file and prints what can be built; --list=variables shows its variables.
docker buildx bake --set *.platform=linux/arm64Override a target valueThe part before the first dot is a target pattern, so * applies the change to every target.
docker buildx createCreate a builderMakes an isolated builder for a Docker context or endpoint; with no argument the current configuration is used.
docker buildx create --use --name mybuild node-amd64Create and select a builderGives the builder a name and, through --use, makes it the current one straight away.
docker buildx create --name eager_beaver --append mycontext2Add a node to a builderWith --append the named builder gains a node instead of being replaced.
docker buildx lsList buildersShows every builder with its nodes, driver, status and platforms; an asterisk marks the current one.
docker buildx inspectInspect a builderReports on the current builder, or on the one whose name is given.
docker buildx inspect --bootstrapBoot and inspect a builderMakes sure the builder has started before its details are printed.
docker buildx useSwitch the current builderLater build commands run on the named builder; a context name selects the default builder of that context.
docker buildx stopStop a builderHalts the current or named builder, but the next buildx build may start it again.
docker buildx rmRemove buildersDeletes the current or named builder; trying it on the default builder does nothing.
docker buildx rm --all-inactiveRemove inactive buildersAsks for confirmation first unless --force is added.
docker buildx duShow build cache disk usageLists build cache records with their size, last access time and whether they are reclaimable.
docker buildx du --verboseShow detailed cache recordsSame as --format=pretty: every record is printed as a block of fields.
docker buildx pruneRemove build cacheEmpties the cache of the selected builder after a confirmation prompt.
docker buildx prune --filter "until=24h"Prune cache by last useKeeps the records used within the last 24 hours and removes the rest.
docker buildx imagetoolsWork with registry imagesSubcommand group for manifest lists: useful for checking multi-platform images and attestations.
docker buildx imagetools inspectInspect an image in a registry
docker buildx imagetools createCombine images into a new one
docker buildx historyWork with build recordsSubcommand group; its ls, inspect, logs and rm subcommands list, examine and delete past builds.
docker buildx history lsList build records
docker buildx history logsPrint the log of a build
docker buildx policyWork with build policiesSubcommand group with eval, which evaluates a policy for a source, and test, which runs policy tests.
docker buildx debugStart the build debugger
docker buildx dapStart a DAP debugger
docker buildx dial-stdioProxy stdio to a builderMeant for tools that talk to the builder through the BuildKit API, not for people.
docker buildx versionShow the Buildx versionPrints the module path, the version number and the commit it was built from.

Volumes 16

CommandWhat it does
docker volume createCreate a volumeDocker invents a random name when none is given; the local driver is the default.
docker volume create my-volCreate a named volume
docker volume create the-doctor --label is-timelord=yesCreate a labelled volumeA label is metadata that volume ls and volume prune filters can select on.
docker volume lsList volumesLists every volume Docker knows with its driver; -q prints names only.
docker volume ls -f dangling=trueList unused volumesDangling here means no container references the volume.
docker volume ls -f name=roseFilter volumes by nameMatches every volume whose name contains the given text.
docker volume ls --filter label=is-timelord=yesFilter volumes by labelUse the key alone to match any value, or key=value for one value.
docker volume ls --format "{{.Name}}: {{.Driver}}"Print chosen volume fieldsA Go template replaces the table; .Mountpoint, .Labels and .Scope are among the placeholders.
docker volume inspectInspect volumesReturns a JSON array with driver, labels, mount point and scope for each volume named.
docker volume inspect --format '{{ .Mountpoint }}' myvolumeFind where a volume is storedPrints only the host path the volume data lives under.
docker volume rmRemove volumesFails for a volume that a container still uses.
docker volume pruneRemove unused volumesBy default only anonymous volumes that no container references are deleted.
docker volume prune -aPrune named volumes tooExtends the cleanup from anonymous volumes to every unused volume, so check for data you still need.
docker volume prune --filter "label!=keep"Prune volumes except labelled onesSpares any volume that carries the label keep.
docker volume updateUpdate a cluster volumeApplies to Swarm cluster volumes only, for example to change their availability.
docker run --rm --volumes-from dbstore -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdataBack up a volumeA throwaway container mounts the volumes of dbstore plus the current folder and writes a tar file there.

Networks 19

CommandWhat it does
docker network createCreate a networkMakes a bridge network unless another driver is chosen with -d.
docker network create -d bridge my-bridge-networkCreate a bridge networkA bridge network is isolated to one Docker host; spanning several hosts takes an overlay network.
docker network create --driver=bridge --subnet=192.168.0.0/16 br0Create a network with a subnetSets the address range yourself instead of letting the daemon pick a free one.
docker network create --ipv6 --subnet 2001:db8:1234::/64 my-netCreate an IPv6 bridge network
docker network lsList networksShows ID, name, driver and scope of every network the daemon knows.
docker network ls --filter driver=bridgeFilter networks by driverFinds the networks managed by one driver, here bridge.
docker network ls --filter type=customList user-defined networksThe value builtin lists the predefined networks instead.
docker network ls --no-truncShow full network IDs
docker network inspectInspect networksPrints the details of each named network as JSON; -f pulls out single values with a template.
docker network inspect bridgeInspect the default bridgeShows which containers sit on the default network and the IP address each one received.
docker network connectConnect a containerTakes the network first and the container second; the container can then talk to others on it.
docker network connect multi-host-network container1Attach a running containerWorks on a container that is already running.
docker network connect --ip 10.10.36.122 multi-host-network container2Connect with a fixed IP addressAssigns that address to the interface the container gets on this network.
docker network connect --alias db --alias mysql multi-host-network container2Connect with network aliasesOther containers on that network can then reach it under the extra names.
docker network disconnectDisconnect a containerThe container has to be running; -f forces the disconnect.
docker network rmRemove networksEvery container must be disconnected from the network before it can be deleted.
docker network rm 3695c422697f my-networkRemove several networksIDs and names can be mixed; a failure on one does not stop the others.
docker network pruneRemove unused networksDeletes the networks that no container references, after asking for confirmation.
docker network prune --force --filter until=5mPrune older unused networksNo prompt, and only networks created more than five minutes ago are affected.

Compose project lifecycle 35

Without -f, Compose searches the working directory and then its parent directories for compose.yaml or docker-compose.yaml.

CommandWhat it does
docker composeRun a Compose subcommandParent command of everything below; global options such as -f, -p and --profile go before the subcommand.
docker compose upStart a Compose projectBuilds, creates and starts the services, then stays attached to their combined output until interrupted.
docker compose up -dStart in the backgroundDetached mode gives the prompt back and leaves the containers running.
docker compose up --buildRebuild images, then startService images are built first instead of reusing the ones that already exist.
docker compose up --force-recreateRecreate all containersReplaces every container even when nothing in its configuration or image is different.
docker compose up --watchStart with file watchServices with watch rules are synced or rebuilt whenever their source files are saved.
docker compose --dry-run up --build -dPreview a command in dry runPrints each step Compose would take and leaves the stack untouched; read-only commands like ps do not support it.
docker compose downStop and remove a projectRemoves the containers and networks that up made; volumes are kept.
docker compose down -vRemove a project with its volumesAlso deletes the named volumes declared in the Compose file, so their data is gone.
docker compose down --remove-orphansRemove orphan containers tooClears containers left over from services that the Compose file no longer defines.
docker compose down --rmi localRemove the service images tooThe value local spares images with a custom tag, while all deletes every image the services use.
docker compose stopStop servicesContainers are halted but kept, so docker compose start can bring them back.
docker compose stop phpmyadminStop one serviceNaming a service limits the command to it and leaves the rest of the project running.
docker compose startStart existing servicesOnly starts containers that already exist; it never creates new ones.
docker compose start --waitStart and wait until healthyReturns once the services report running or healthy and implies detached mode.
docker compose restartRestart servicesEdits to the Compose file are not applied by a restart; that takes docker compose up.
docker compose pausePause servicesFreezes the running containers of the services until unpause is called.
docker compose unpauseResume paused servicesLets containers that were frozen with pause continue.
docker compose killForce-stop servicesSends SIGKILL to the running containers instead of waiting for a clean shutdown.
docker compose kill -s SIGINTSend another signal to services
docker compose rmRemove stopped service containersAsks first unless -f is given; -s stops running containers beforehand and -v drops their anonymous volumes.
docker compose createCreate service containersPrepares the containers without starting them; --build builds the images first.
docker compose buildBuild service imagesRun it after changing a Dockerfile or build folder; images are tagged project-service by default.
docker compose build --no-cacheRebuild services without cacheEvery build step runs again instead of reusing cached layers.
docker compose pullPull service imagesDownloads the images the services refer to but starts nothing.
docker compose pull dbPull the image of one service
docker compose pull --ignore-buildablePull only prebuilt imagesSkips services that have a build section, whose images would be built locally anyway.
docker compose pushPush service imagesUploads images you built locally to the registry and repository named in each image field.
docker compose scaleScale servicesTakes SERVICE=REPLICAS pairs; --no-deps keeps linked services from being started.
docker compose waitWait for services to stopBlocks until the containers of the listed services exit; --down-project then takes the project down.
docker compose watchWatch files and update servicesDedicated watch command that keeps sync and rebuild events apart from the application logs.
docker compose -f compose.yaml -f compose.admin.yaml run backup_dbCombine several Compose filesFiles are merged in the order given, later ones overriding and extending earlier ones.
docker compose -f ~/sandbox/rails/compose.yaml pull dbUse a Compose file elsewhereLets you run the command from any directory instead of the project folder.
docker compose -p my_project ps -aSet the project nameOverrides the default name, which comes from the directory holding the Compose file.
docker compose --profile debug upEnable a profileAdds the services assigned to the debug profile to those that have no profile at all.

Compose logs, shells and one-off commands 34

CommandWhat it does
docker compose psList project containersShows each container of the project with its service, current status and ports.
docker compose ps --allList stopped containers tooIncludes exited containers and the ones left behind by docker compose run.
docker compose ps --status=runningFilter containers by statusOther accepted states include paused, restarting and exited.
docker compose ps --format jsonList containers as JSON
docker compose logsShow service logsPrints the output of all services, or only of those named; --no-log-prefix drops the name before each line.
docker compose logs -fFollow the logs of all servicesKeeps streaming new lines until you press Ctrl+C.
docker compose logs -f webFollow one service
docker compose logs --since 42mShow recent logs onlyAccepts a relative age like 42m or an absolute timestamp.
docker compose logs --tailShow the last log linesGive the number of lines wanted per container; the default is all.
docker compose execRun a command in a serviceThe Compose counterpart of docker exec: needs a running service container and allocates a TTY by default.
docker compose exec web shOpen a shell in a serviceNo -it flags are needed, because exec is interactive with a terminal by default.
docker compose exec redis redis-cli GET hitsRun one command in a serviceExecutes inside the redis container that is already up; no new container is started.
docker compose runRun a one-time commandStarts a new container for the service with your command in place of the configured one.
docker compose run web bashShell in a fresh service containerService ports are not published for run containers, which avoids clashes with the running service.
docker compose run --rm web python manage.py db upgradeRun a task and clean upThe container is deleted when the command finishes, even if the service has a restart policy.
docker compose run --no-deps web python manage.py shellRun without linked servicesStops Compose from starting the services this one is linked to.
docker compose run --service-ports web python manage.py shellRun with service ports mappedPublishes the ports from the service definition, which run otherwise leaves closed.
docker compose run -e DEBUG=1 web python console.pyRun with an environment variableThe value applies to this one run and takes priority over the .env file.
docker compose topList processes per servicePrints the processes running in each container of the project.
docker compose statsLive resource usage per serviceStreams usage figures for the project containers; --no-stream prints one reading and exits.
docker compose eventsStream container eventsReports events for every container in the project as they happen.
docker compose events --jsonStream events as JSONEach event becomes one JSON object on its own line.
docker compose imagesList images used by servicesCovers the images of containers that have been created; -q prints IDs only.
docker compose volumesList project volumesService names narrow the list, and -q prints volume names only.
docker compose portShow a service port mappingGive the private port to get the public one back; --protocol switches from tcp to udp.
docker compose lsList Compose projectsOnly running projects appear unless -a is added.
docker compose ls -aList stopped projects too
docker compose configRender the resolved Compose fileMerges all -f files, fills in variables and prints the result; the project need not be running.
docker compose config --imagesList the image names in a projectPrints one image name per line instead of the whole configuration.
docker compose versionShow the Compose versionThe --short flag reduces the output to the bare version number.
docker compose attachAttach to a service containerConnects your terminal to the main process of one service; --index picks a replica.
docker compose cpCopy files to or from a serviceOne side is SERVICE:PATH and the other a local path or a dash; --index picks a replica.
docker compose exportExport a service filesystemWrites a tar archive to STDOUT, or to the file given with -o.
docker compose commitSave a service container as an imageThe optional last argument names the repository and tag of the new image.

Compose conversion, publishing and alpha commands 7

CommandWhat it does
docker compose convertRender the canonical Compose modelKept as a migration aid from docker-compose; docker compose config is declared as its alias.
docker compose bridgeConvert Compose files to another modelParent command of the bridge tools; the conversion itself is docker compose bridge convert.
docker compose bridge convertGenerate Kubernetes manifestsWrites Kubernetes resources or Helm charts into the out directory unless -o names another.
docker compose publishPublish a Compose applicationPushes the Compose file to an OCI registry under the given repository and tag.
docker compose alpha dry-runDry-run a command (experimental)The global --dry-run flag of docker compose covers the same need.
docker compose alpha scaleScale services (alpha)
docker compose alpha watchWatch files (alpha)

System information and cleanup 13

docker system prune leaves volumes alone unless --volumes is added, and even then it only removes anonymous volumes.

CommandWhat it does
docker infoShow daemon and host detailsReports the kernel version, how many containers and images exist and other facts about the installation.
docker system infoShow system informationLong form of docker info; -f formats the result with a template or as JSON.
docker info --format '{{json .}}'Print system info as JSON
docker system dfShow Docker disk usageSummarises the space held by images, containers and local volumes, with the reclaimable share of each.
docker system df -vShow disk usage in detailBreaks the summary down to single images, containers and volumes.
docker system eventsStream daemon eventsPrints container, image, volume and network events as they happen; docker events is the short alias.
docker events --since '10m'Show recent events firstStarts with the events of the last ten minutes; with no --since only new events appear.
docker events --filter 'container=test' --filter 'event=stop'Filter the event streamFilters on different keys must all match, here one container and one event type.
docker system pruneClean up unused objectsAfter a prompt, deletes stopped containers, unused networks, dangling images and unused build cache; volumes stay.
docker system prune -aPrune all unused images tooWidens the image cleanup from dangling ones to every image that is not in use.
docker system prune --volumesPrune anonymous volumes tooAdds anonymous volumes that no container uses to the cleanup; named volumes are kept.
docker system prune -a --volumesPrune everything unusedThe widest cleanup: all unused images plus anonymous volumes, on top of the default set.
docker system prune --filter "until=24h"Prune objects older than a dayOnly objects created more than 24 hours ago are removed.

Contexts and remote daemons 14

CommandWhat it does
docker context createCreate a contextA context records how to reach one daemon, so the CLI can switch between engines.
docker context create --docker host=unix:///var/run/docker.sock my-contextCreate a context for an endpointThe --docker option sets the daemon address the new context will connect to.
docker context create --from existing-context my-contextCopy an existing contextWithout --from the new context is based on the one currently in use.
docker context lsList contextsAn asterisk marks the context that is active right now.
docker context showPrint the current contextThe answer reflects DOCKER_CONTEXT or the --context option when either is set.
docker context useSwitch the default contextSaved in the CLI config file, so the change holds for every shell and session.
docker context use defaultReturn to the default context
docker --context my-context psUse a context for one commandAffects only this invocation and leaves the default context as it was.
docker context inspectInspect contextsShows the endpoint and metadata of the named contexts; -f formats the output.
docker context updateUpdate a contextChanges the description or the Docker endpoint of an existing context.
docker context exportExport a contextWrites a file named after the context with the extension .dockercontext unless another name is given.
docker context export my-context -Export a context to stdout
docker context importImport a contextReads a file made by context export; a hyphen as filename takes it from stdin.
docker context rmRemove contextsSeveral names can be listed; a context that is in use needs -f.

Versions, help and other tools 8

CommandWhat it does
docker versionShow client and server versionsLists the version of each Docker component, whereas docker --version prints only the CLI version.
docker --versionShow the CLI versionA single line about the CLI itself, where docker version details every component.
docker version --format '{{.Server.Version}}'Get the server version onlyA template picks single values out of the version data, handy in scripts.
docker run --helpShow help for a commandAny command followed by --help prints its usage line and options.
docker -H ssh://[email protected] psUse a remote daemon over SSHThe -H flag points this one command at another daemon socket; tcp:// addresses work the same way.
docker passManage keychain secretsKeeps secrets in the OS keychain for injection into containers; its subcommands are set, get, ls, rm and run.
docker pass set GH_TOKEN=123456789Store a secret in the keychainA container can then receive it through an se:// reference in an -e option.
docker dhiManage Docker Hardened ImagesPlugin for browsing the hardened image catalog, mirroring images to an organisation and handling customizations.

Notes

The daily loop is four commands

Most Docker days are docker run, docker ps, docker logs and docker exec. docker run creates and starts a container from an image; docker ps shows what's running and docker ps -a adds the stopped ones — which matters because a crashed container disappears from the plain list and beginners conclude it never started. docker logs -f CONTAINER_NAME follows output, and docker exec -it mycontainer sh drops you inside a running container (sh rather than bash, because minimal images often lack bash).

Compose is the default, and it's a space now

Since Compose v2 the command is docker compose — a space, not the old hyphenated docker-compose binary. docker compose up -d starts the stack detached, docker compose logs -f tails every service together, and docker compose down stops and removes containers and networks (volumes survive unless you run docker compose down -v). The pairing worth internalizing: edit a Dockerfile → docker compose build → docker compose up -d recreates only what changed.

Cleanup, with one warning label

Docker hoards: stopped containers, dangling images, and build cache accumulate for weeks until the disk fills. docker system prune clears stopped containers, unused networks, dangling images and unused build cache in one shot — but read its prompt before confirming, and know that docker system prune -a also removes every image that no container uses, which means long re-pulls later. Volumes are skipped unless you add --volumes, as in docker system prune -a --volumes, and even then only anonymous ones go. docker stats and docker volume ls answer the two questions that precede most cleanups: what's eating resources, and what data would I lose?

Questions

What is the difference between docker run and docker exec?

run creates a new container from an image and starts it; exec runs an extra process (usually a shell) inside a container that's already running.

Why doesn't docker ps show my container?

Plain ps lists running containers only. If it exited or crashed, docker ps -a shows it with its exit status, and docker logs <id> shows why.

Is it docker compose or docker-compose?

docker compose (space) is the current v2 syntax built into the CLI. The hyphenated docker-compose is the legacy v1 binary; commands are otherwise near-identical.

Does docker compose down delete my data?

It removes containers and networks but keeps named volumes. Add -v only when you deliberately want volumes gone too.

Is docker system prune safe?

It removes stopped containers, unused networks, dangling images and unused build cache — running containers are untouched, and volumes are left alone unless you add --volumes. The riskier variant is prune -a, which also deletes every image that no container uses.

How do I clean up Docker disk space?

Run docker system prune. After a confirmation prompt it removes stopped containers, networks that no container uses, dangling images and unused build cache. docker system prune -a also removes every image that has no container associated with it, so those images have to be pulled or built again later.

Volumes are kept unless you add --volumes, which prunes anonymous volumes as well. To see where the space went before deleting anything, run docker system df, which lists the space used by images, containers and local volumes and how much of it is reclaimable.

How do I open a shell inside a running Docker container?

Run docker exec -it mycontainer bash, replacing mycontainer with the container name or ID that docker ps shows. The -i flag keeps standard input open and -t allocates a terminal, which together give an interactive shell.

If the image has no bash, run docker exec -it mycontainer sh instead. The command works only on a running container; start a stopped one first with docker start. The shell opens in the container's default working directory; -w sets another one and -u runs it as a different user.

Sources and checks

132 more source pages

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.