Docker: cheat sheet of common commands
Docker cheat sheet: containers, images, networks, volumes, ports, Dockerfile, Compose, cleanup and security.
A memo of the Docker commands most useful day to day: container and image lifecycle, networks, volumes, ports, Dockerfile, Compose, cleanup and a few security rules. For more detail see the official documentation and the community cheat sheet this memo is based on.
Version
docker version
docker version --format '{{.Server.Version}}'
docker version --format '{{json .}}'
Containers
Lifecycle
| Command | Purpose |
|---|---|
docker create |
creates a container without starting it |
docker run |
creates and starts a container |
docker rename |
renames a container |
docker rm |
deletes a container (-v: also removes its anonymous volumes) |
docker update |
changes resource limits |
docker start / stop / restart |
starts, stops, restarts |
docker pause / unpause |
freezes / resumes the processes |
docker kill |
sends SIGKILL |
docker wait |
blocks until the container stops |
docker attach |
connects to a running container (detach with Ctrl+p then Ctrl+q) |
Common docker run options:
docker run -d --name web -p 8080:80 nginx # background, name, host:container port mapping
docker run -td IMAGE # pseudo-TTY + detached: keeps a container alive
docker run --rm IMAGE # throwaway container, removed when it stops
docker run -v /srv/data:/data IMAGE # mount a host directory
docker run --hostname srv IMAGE # set the hostname
docker run --add-host name:192.0.2.10 IMAGE # static DNS entry
docker run -it --entrypoint bash IMAGE # override the entrypoint
docker run --log-driver=syslog IMAGE # logging driver
Without extra options, a container whose main process exits stops immediately; giving it a name with --name lets you manage it by that name afterwards.
Resource limits
docker run -it -c 512 IMAGE # cpu-shares: 1024 = default weight, 512 = half the priority
docker run -it --cpuset-cpus=0,4,6 IMAGE # restrict to specific cores
docker run -it -m 300M ubuntu /bin/bash # memory limit
docker run --pids-limit=64 IMAGE # limit the number of processes (guards against fork bombs)
cpu-shares is a relative weight, not a cap. With --cpuset-cpus the container still sees all CPUs but only uses the listed ones.
Capabilities and devices
docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse IMAGE # mount a FUSE filesystem
docker run -it --device=/dev/ttyUSB0 debian bash # a single device
docker run -it --privileged -v /dev/bus/usb:/dev/bus/usb debian bash # all devices (avoid)
--cap-add / --cap-drop adjust Linux capabilities; prefer this fine-grained control over --privileged.
Information
| Command | Purpose |
|---|---|
docker ps / docker ps -a |
running containers / all containers |
docker logs |
container logs |
docker inspect |
full details (including the IP address) |
docker events |
event stream |
docker port |
published ports |
docker top |
processes in the container |
docker stats (--all) |
CPU, memory and network usage |
docker diff |
files changed in the container |
Copy, export, execute
docker cp web:/index.html ./index.html # container -> host
docker cp ./index.html web:/index.html # host -> container
docker export web | gzip > web.tar.gz # container filesystem
docker exec -it web /bin/bash # open a shell in a running container
Images
| Command | Purpose |
|---|---|
docker images |
lists images |
docker build -t name . |
builds an image from a Dockerfile |
docker commit |
creates an image from a container (a Dockerfile is preferable) |
docker tag SRC DEST |
adds a name/tag |
docker history |
layer history |
docker rmi |
removes an image |
docker save / docker load |
image tar archive (keeps history and tags) |
docker export / docker import |
tar archive of a container filesystem |
docker save my_image:my_tag | gzip > my_image.tar.gz
docker load < my_image.tar.gz
docker export my_container | gzip > my_container.tar.gz
cat my_container.tar.gz | docker import - my_image:my_tag
load restores the image with its history; import creates an image without history, hence a smaller one.
Networks
docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 mynet
docker run --rm -it --net mynet --ip 203.0.113.2 nginx
docker network ls
docker network inspect mynet
docker network connect mynet CONTAINER
docker network disconnect mynet CONTAINER
docker network rm mynet
User-defined networks let containers talk to each other by name without publishing ports; they replace the legacy --link.
Registry
docker login, logout, search, pull and push handle authentication and image transfer to and from a registry. A private registry can be hosted with the distribution project.
Volumes
docker volume create data
docker volume ls
docker volume inspect data
docker volume rm data
docker run --volumes-from CONTAINER IMAGE # reuse the volumes of another container
A volume is a filesystem independent of any container, handy for keeping state between throwaway containers. You can also mount a single file, for example to inject a configuration:
docker run --rm httpd cat /usr/local/apache2/conf/httpd.conf > httpd.conf
# edit httpd.conf, then:
docker run --rm -it -v "$PWD/httpd.conf:/usr/local/apache2/conf/httpd.conf:ro" -p 8080:80 httpd
Publishing ports
docker run -p 8080:80 --name web -t IMAGE
docker port web 80
EXPOSE in a Dockerfile only documents the listening port; only -p (or -P for all exposed ports) publishes it on the host.
Dockerfile
A Dockerfile describes how docker build builds an image. Main instructions:
| Instruction | Purpose |
|---|---|
FROM |
base image |
RUN |
runs a command in a new layer |
CMD |
default command of the container |
ENTRYPOINT |
main executable of the container |
EXPOSE |
documents listening ports (does not publish them) |
ENV / ARG |
environment variable / build-time variable |
COPY / ADD |
copies files; prefer COPY (ADD invalidates the cache) |
VOLUME |
mount point |
USER / WORKDIR |
user and working directory |
LABEL |
metadata (replaces the deprecated MAINTAINER) |
ONBUILD |
trigger for derived builds |
STOPSIGNAL |
stop signal |
COPY copies as root regardless of USER; use --chown=user:group to change ownership. A .dockerignore file excludes items from the build context. See the official best practices.
Reducing size: clean APT in the same RUN layer as the install, otherwise earlier layers keep the files.
RUN apt-get update && apt-get install -y PACKAGE \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
Dockerfile on the command line (heredoc):
docker build -t htop - << EOF
FROM alpine
RUN apk --no-cache add htop
EOF
Docker Compose
docker-compose -f docker-compose.yml up # start the services (-d for background)
docker-compose stop # stop
docker-compose down # remove the containers (--volumes: and the volumes)
Cleanup
Since Docker 1.13:
docker system df # space used by Docker objects
docker system prune
docker container prune
docker image prune # -a: all unused images
docker volume prune
docker network prune
Older commands that are still useful:
docker kill $(docker ps -q) # kill all running containers
docker rm -f $(docker ps -qa) # remove all containers (even running)
docker rm -v $(docker ps -a -q -f status=exited) # remove stopped containers
docker rmi $(docker images -q -f dangling=true) # dangling images
docker rmi $(docker images -q) # all images
docker volume rm $(docker volume ls -q -f dangling=true) # dangling volumes
Tips
# IP address of a container
docker inspect -f '{{ .NetworkSettings.IPAddress }}' NAME
# Port mapping
docker inspect -f '{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' NAME
# Environment variables of an image
docker run --rm ubuntu env
# Containers created from an image
docker ps -a -f ancestor=ubuntu
# Usage of all running containers
docker stats $(docker ps -q)
# Flatten an image
ID=$(docker run -d image-name /bin/bash)
docker export $ID | docker import - flat-image-name
Security
- Docker runs as root: being in the
dockergroup is effectively root access on the host. - For better isolation, run Docker inside a virtual machine and harden the host.
- Avoid running the process as root inside the container:
RUN groupadd -r user && useradd -r -g user user
USER user
- Useful runtime options:
docker run --read-only IMAGE # read-only filesystem
docker run -v "$(pwd)/secrets:/secrets:ro" debian # read-only volume
docker run --security-opt=no-new-privileges IMAGE # prevent gaining new privileges
docker run --pids-limit=64 IMAGE # limit the number of processes
- Verify an image by its digest:
docker pull debian@sha256:<DIGEST>. - Do not expose image ids to the outside world.
- docker-bench-security audits a Docker installation.
Notes
- Several cleanup commands assume a POSIX shell (
$(...),awk,grep); they delete without confirmation, so use them with care. --linkis legacy; prefer user-defined networks.