Docker cheat sheet (cheatsheet)

This is the beginning of a Docker cheat sheet. I couldn’t find any out here that I liked, so I’m starting to create my own, which will hopefully be organized the way I like it.

This content is cross-posted at My Valley Programming Docker cheat sheet.

Docker Basics

Recommended as a first command on a Docker system:

docker version     # should show Client and Server sections

Docker Lifecycle

This section mostly comes from (https://github.com/wsargent/docker-cheat-sheet):

docker create     creates a container but does not start it
docker rename     allows the container to be renamed
docker run        creates and starts a container in one operation
docker rm         deletes a container
docker update     updates a container's resource limits

Docker Build

Build an image using a Dockerfile in the current directory:

docker build -t scala-webserver-1 .

Other build commands:

docker build [url]      # create an image from a Dockerfile at a URL
docker build -t [url]   # build an image from a Dockerfile and tag it

docker load [tafile]    # TODO (more on this)

I needed to use this command when building a Linux distro on macOS (which uses an ARM chip):

docker build --platform linux/amd64 -t scala-webserver-1 .

TODO: There is also a docker create.

Example Dockerfile:

FROM openjdk:11
WORKDIR /home
COPY target/scala-3.1.0/WebServerDocker3-assembly-0.1.0.jar WebServerDocker3-assembly-0.1.0.jar
#CMD java -jar ManualDockerfile2-assembly-0.1.0.jar
EXPOSE 5150
CMD ["java", "-jar", "WebServerDocker3-assembly-0.1.0.jar"]

Can also expose multiple ports:

EXPOSE 5150 5151

Docker Images

List images:

docker image ls
docker images
docker images -a
docker images -f dangling=true

Pull and push images from a registry:

docker pull [image]
docker pull alpine
docker pull alpine:latest

docker push [image]

Remove images:

docker rmi [image]
docker rmi alpine:latest

docker rmi $(docker images -q)
docker rmi $(docker images -a -q)
docker rmi $(docker images -aq)
docker image prune

Other image commands:

docker history [image]   # show the history of an image

Docker Run (run an image)

Start a container with an interactive shell:

docker run -it alpine /bin/sh
docker run -it rhel7/rhel bash

docker exec -it <container-name> /bin/sh
docker run -it --rm --name my-running-app my-java-app

# example:
$ docker run -it debian:stable /bin/bash
Unable to find image 'debian:stable' locally
stable: Pulling from library/debian
d39780c72a13: Pull complete 
Digest: sha256:e8795576943b7bb2ecf2126c3b7f467da64c84f3c4d63f75c24fb91502ab8487
Status: Downloaded newer image for debian:stable
root@ef74a0677a41:/# 

Run an image, exposing its port 5150 as port 8080 of the container:

docker run -p 8080:5150 scala-webserver-1

> curl http://localhost:8080
Have a nice day!

More run commands:

docker run [image]        # start a container
docker run --rm [image]   # run a container, remove it when it stops
docker run -td [image]    # TODO
docker run -it [image]    # start a container, run a command in it, connect to it (TODO)

An example from https://design.jboss.org/redhatdeveloper/marketing/docker_cheatsheet/cheatsheet/images/docker_cheatsheet_r3v2.pdf:

docker run -d \
    -p 8000:8000 \
    --name=pythonweb \
    -v `pwd`/www:/var/www/html \
    -w /var/www/html \
    rhel7/rhel \
    /bin/python \
    -m SimpleHTTPServer 8000

Docker Containers

List active/running containers:

docker container ls
docker ps

List active/running and stopped containers:

docker container ls -a
docker ps -a

List all containers:

$ docker container ls -a
CONTAINER ID   IMAGE               COMMAND                  CREATED         STATUS                        PORTS     NAMES
3fd5b267c069   scala-webserver-1   "java -jar WebServer…"   3 minutes ago   Exited (130) 26 seconds ago             ecstatic_shamir
2835d9c80513   scala-hello-1       "java -jar ManualDoc…"   24 hours ago    Exited (0) 24 hours ago                 busy_sammet

# list by status
docker ps -a -f status=exited
docker ps -a -f status=exited -f status=created

# list by pattern
docker ps -a | grep "pattern"

Start, stop, and restart containers:

docker start [container]

# more 'start' options:
docker start [options] [container]
    -a, --attach        # attach stdout/stderr
    -i, --interactive   # attach stdin

docker stop [container]
docker stop -t5 [container]   # stop with a timeout

docker restart [container]

docker pause [container]      # pause processes in a running container
docker unpause [container]

docker attach [container]     # attach STDIN, STDOUT, STDERR to a running container
docker wait [container]       # block a container until (TODO)

docker kill [container]       # send SIGKILL to a container

# kill all running containers:
docker kill $(docker ps -q)

Other container commands:

docker events [container]     # list the events from a running container

docker logs [container]       # list the logs from a container
docker logs -f [container]

docker top [container]        # show running processes in a container

docker diff [container]
docker port [container]
docker stats [container]

docker export ...             # export container’s filesystem as a tar archive
docker exec ...               # run a command in a running container
docker pause ...              # pause all processes in a running container

Information commands:

  • diff
  • events
  • inspect
  • logs
  • port
  • ps
  • stats
  • top

Remove a container:

$ docker container rm 3fd5b267
3fd5b267

Remove multiple/all containers:

# remove all stopped containers:
docker rm $(docker ps -aq)

docker rm $(docker ps --filter status=exited -q)
docker ps --filter status=exited -q | xargs docker rm

Stop all running containers:

# stop
docker stop $(docker ps -a -q)
docker stop $(docker ps -aq)

# remove
docker rm $(docker ps -a -q)
docker rm $(docker ps -a -f status=exited -q)
docker rm $(docker ps -a -f status=exited -f status=created -q)

# remove by pattern
docker ps -a | grep "pattern" | awk '{print $1}' | xargs docker rm

Docker Networks

List networks:

docker network ls
docker network inspect [network]

# connect a container to a network
docker network connect [network] [container]

“Dangling” resources

This section needs more work, but here are some initial examples:

docker system df          # show space used by docker objects

# remove all "dangling" resources (images, containers, volumes, networks)
docker system prune       # not tagged or associated with a container
docker system prune -a    # stopped containers and unused images

TODO: “Dangling” may mean “not associated with a container,” but I need to research that for a more precise definition.

Docker pruning commands:

docker image prune      # remove unused, dangling images
docker image prune -a   # remove images not used in containers

docker system prune     # prune everything (the entire system)

docker container prune
docker image prune
docker network prune
docker system prune
docker volume prune

Dockerfile examples

From https://hub.docker.com/r/adoptopenjdk/openjdk11:

# Dockerfile:
    FROM adoptopenjdk/openjdk11:ubi
    RUN mkdir /opt/app
    COPY japp.jar /opt/app
    CMD ["java", "-jar", "/opt/app/japp.jar"]

# You can build and run the Docker image as shown in the following example:
    $ docker build -t japp .
    $ docker run -it --rm japp

From https://hub.docker.com/_/openjdk:

# Dockerfile:
    FROM openjdk:11
    COPY . /usr/src/myapp
    WORKDIR /usr/src/myapp
    RUN javac Main.java
    CMD ["java", "Main"]

# build and run the Docker image:
    $ docker build -t my-java-app .
    $ docker run -it --rm --name my-running-app my-java-app

This snyk.io page has a good Dockerfile example, including best practices, including this:

FROM adoptopenjdk/openjdk11:jre-11.0.9.1_1-alpine@sha256:b6ab0.....
RUN apk add dumb-init
RUN mkdir /app
RUN addgroup --system javauser && adduser -S -s /bin/false -G javauser javauser
COPY --from=build /project/target/java-code-workshop-0.0.1-SNAPSHOT.jar /app/java-application.jar
WORKDIR /app
RUN chown -R javauser:javauser /app
USER javauser
CMD "dumb-init" "java" "-jar" "java-application.jar"

Docker Volumes

TODO: I haven’t worked with these much yet, but this is what I know:

  • high level:
    • create a volume
    • create a container
    • mount the volume into the container
docker volume prune    # delete all volumes

Create a new volume named vol01:

docker volume create vol01

See your volumes:

docker volume ls

Inspect them:

docker volume inspect vol01

# shows json output
# `mountpoint` tells you where on the host the volume is surfaced
# volumes with the `local` driver get their own directory under /var/lib/docker/volumes

Delete them:

# [1]
docker volume rm <volume-name>

# [2]
docker volume prune
# delete all volumens that are not mounted into a container (or service)
# neither command will delete a volume that’s in use

Example

Goal: create a new standalone container and mount a volume called als_vol

Linux:

docker container run -dit --name container_and_vol \
    --mount source=als_vol,target=/vol \
    alpine

Note: Docker can use an existing volume, and will also create one if you specify a volume that doesn’t exist. In this case, als_vol doesn’t exist, so Docker creates it and mounts it into the new container:

$ docker volume ls
DRIVER    VOLUME NAME
local     als_vol

Now use it:

docker container exec -it container_and_vol sh

echo "Hello" > /vol/file1
ls -l /vol
cat /vol/file1

Delete the container:

docker container rm container_and_vol -f

The volume still exists:

$ docker volume ls
DRIVER    VOLUME NAME
local     als_vol

On a Linux system you can see the Docker volume like this:

$ ls -l /var/lib/docker/volumes/als_vol/_data

TODO: On macOS you need to do something like this, but in January, 2022 this doesn’t work as-is:

screen ~/Library/Containers/com.docker.docker/Data/vms/0/tty
ls -l /var/lib/docker

NOTE: For this section I followed the example in the excellent book, Docker Deep Dive.

Dockerfile commands/arguments

This is a list of commands you can use in a Docker Dockerfile:

#             Comments begin with '#'

ADD           Copy new files, directories, or remote file URLs from into the filesystem of the container

CMD           Allowed only once; if given multiple times, only the last one takes effect.
              The intended command for the image.
              Doesn’t do anything during 'build' time.

COPY          Copy files or directories from a source into the filesystem of the container
              COPY readme.txt /home/al

ENTRYPOINT    TODO: A container that will run as an executable? Or, the primary command of your Docker image?

ENV           Set environment variables.
              ENV CONF_FILE=application.conf HEAP_SIZE=2G

EXPOSE        Tells the container runtime that the container listens on these network ports at runtime
              EXPOSE 5150
              EXPOSE 5150 5151

FROM          Sets the base image (ubuntu, openjdk:11, alpine, etc.)

LABEL         Adds metadata (a non-executable instruction)
              LABEL description="Updating the foo and bar"
              LABEL version="0.15"

MAINTAINER    Sets the author field of the generated images

RUN           Execute commands in a new layer on top of the current image and commit the results.
              Runs during 'build' time.
              Strongly consider using '&&': RUN apt-get update && update apt-get install –y php

USER          Sets the username or UID to use when running the image and commands
              USER alvin

VOLUME        Creates a mount point (path) to external volumes (on the native host or other containers)

WORKDIR       Sets the working directory for any subsequent RUN, CMD, ENTRYPOINT, COPY, and ADD commands.
              If it’s a relative path, it’s relative to the previous WORKDIR.
              WORKDIR /home/alvin
              WORKDIR foo           # results in "/home/alvin/foo"

# NOTE: I haven’t used these yet:
ARG           Defines a variable that users can pass at build-time to the builder  using --build-arg
ONBUILD       Adds an instruction to be executed later, when the image is used as the base for another build
STOPSIGNAL    Sets the system call signal that will be sent to the container to exit

Here’s an interesting Dockerfile example from Accelerating Development Velocity with Docker:

CMD         "Hello, world!"
ENTRYPOINT  echo

The initial definitions in that list came from this PDF: https://design.jboss.org/redhatdeveloper/marketing/dockercheatsheet/cheatsheet/images/dockercheatsheet_r3v2.pdf

I also added to them based on my own knowledge, and these books:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

Docker on macOS

This section is TODO/TBD.

Where are Docker images on macOS?

  • used to be here: /Users/al/Library/Containers/com.docker.docker/Data/vms/0/data/Docker.raw