xavier collantes

Docker Commands Cheat Sheet

By Xavier Collantes

12/21/2024


Install Docker

To avoid needing sudo for every Docker command, create a linux group docker then add yourself with sudo usermod -aG docker $USER.

Dockerfile format

dockerfile
1# Comment
2
3# Defines variables for the whole file.
4ARG CHROME_VERSION 100
5
6# Image can be from DockerHub, another image locally on machine, or another
7# section of the same Dockerfile (multi-stage builds).
8FROM [image tag]:[version]
9
10# Root directory for rest of file. Sets the starting point for paths.
11WORKDIR /app
12
13# Variables set in the OS.
14ENV GOOGLE_BUCKET_NAME="gcp_bucketname"
15ENV PYTHONPATH="$PYTHONPATH:/application"
16
17ENV WITH_DEFAULT_1=${SOME_VAR:-DEFAULT}
18# SOME_VAR if set and non-empty, else DEFAULT
19ENV WITH_DEFAULT_2=${SOME_VAR-DEFAULT}  # SOME_VAR if set, else DEFAULT
20
21ENV WITH_DEFAULT_3=${SOME_VAR:?error}
22# SOME_VAR if set and non-empty, else exit program
23ENV WITH_DEFAULT_4=${SOME_VAR?error}  # SOME_VAR if set, else exit program
24
25# Use .dockerignore to specify files not to be copied.
26COPY [path on local machine] [path on container]
27COPY requirements.txt .
28COPY checkmate_state/ ./checkmate_state/
29
30# Define metadata for the container.
31LABEL version="1.0"
32
33# ADD is used for grabbing resources such as URLs.
34#
35# Example: Download Chrome browser file version.
36ADD https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/\
37    google-chrome-stable_${CHROME_VERSION}-1_amd64.deb \
38    /google-chrome-stable_${CHROME_VERSION}-1_amd64.deb
39
40# Container ports to be exposed to external machines.
41EXPOSE 8080 or EXPOSE 8080/udp
42
43# Mount point for a directory on the running machine.
44RUN mkdir /myvol
45RUN echo 'hello' >> /myvol/message.txt
46VOLUME /myvol  # VOLUME must come after the files are made
47
48# The USER field specifies which OS user the container operates as.
49RUN adduser sudo sam
50USER sam
51
52# Executes shell commands in a layer and saves results.
53# RUN works during the build stage, unlike CMD which only runs
54# when the container starts with the `docker run` command.
55RUN mkdir -p somedir/anotherone/another/ && \
56echo "new line"
57
58RUN apt update -y; \
59    apt install python3-pip -y; \
60    pip3 install --upgrade pip; \
61    python3 -m pip install --upgrade setuptools; \
62    pip3 install --no-cache-dir  --force-reinstall -Iv grpcio==1.36.1; \
63    pip3 install -r requirements.txt
64
65# https://docs.docker.com/engine/reference/builder/#understand-how-cmd-and-entrypoint-interact
66ENTRYPOINT ["/bin/bash", "-c", "somescript.sh myarg"]
67
68# Shell command is executed when `docker run` is called.
69CMD python3 -m mypythonmodule \
70    --some_arg myarg \
71    --another_arg ${GOOGLE_BUCKET_NAME}
72
snippet hosted withby Xavier
Docker image tags: Docker Hub: Debian Tags

Exec vs JSON Notation

Using CMD echo "hello" is different from CMD ["echo", "hello"]. If the JSON format is used, this bypasses /bin/bash -c. The working form is: CMD ["bash", "-c", "echo 'hello'"].
When running JSON style with a command that has arguments, include arguments with the command: CMD|ENTRYPOINT ["/bin/bash", "-c", "myscript.sh myarg ${myvararg}"].

Docker commands

Getting Started

  1. Define Dockerfile
  2. Build image from Dockerfile: docker build -t IMAGE_NAME .
  3. Run container from image: docker run -it IMAGE_NAME

Containers

See running containers: docker container ls. Add -a to include stopped containers.
Docker containers do not get cleaned up automatically, so stopped containers must be deleted manually using docker rm.
Build image: docker build -f [dockerfile] -t [image name] .. Name the image to avoid confusion using the format name:version.
Run Docker container: docker run -it -p [port mapping] IMAGE.
  • -i reads standard input even if container is detached.
  • -p optional port exposure.
View logs of running or stopped container: docker logs [container name].

Images

Create Docker image: docker create.
See images: docker images or docker image ls.
Remove images: docker rmi IMAGE.

Accessing Containers

NOTE: Only running containers can be "bashed into". A stopped container will not be accessible when you attempt to enter.
docker exec -it CONTAINER bash

Docker run

docker run [flags] IMAGE
  • --name Name for container. If not specified, Docker assigns a name.
  • -d Detached; run container not attached to terminal.
  • -t Use pseudo TTY.
  • -i Interactive mode; keeps terminal connected to container and STDIN open.
  • --rm Automatically remove container on exit.
  • --device CONTAINER_DEVICE:HOST_DEVICE[:mode] Run devices in container.
    • By default, container can read (r), write (w), and make nodes (m for mknod).
  • --privileged Give all device capabilities to container.
  • --cpu-quota Limit container CPU usage on host. Docker Docs: CPU Quota Constraint
Environment variables can be passed to the container at runtime in several ways:
  • -e VAR Use a defined variable from host OS.
  • --env KEY1=VALUE1 KEY2=VALUE2 Set specific environment variables.
  • --env-file env.list Specify file with each variable as key=value.
  • In Dockerfile: ENV key="value".

ENTRYPOINT

Uses CMD as an argument with ENTRYPOINT placed before CMD.
If you specify:
dockerfile
1ENTRYPOINT /bin/ping -c 3
2CMD <http://google.com>
3
snippet hosted withby Xavier
The result would be: /bin/ping -c 3 http://google.com.
When running docker run, CMD can be overridden by specifying arguments after the command: docker run CONTAINER_NAME http://docker.io.

Running Scripts From Docker Run

You can use JSON syntax without a Bash call for scripts with CMD arguments as parameters:
dockerfile
1ENTRYPOINT ["myscript.sh"]
2CMD ["my", "args"]
3
snippet hosted withby Xavier
To supply arguments during docker run, append them to the end: docker run -it my_image param1 param2
Alternatively, assign environment variables with default values in the docker run command:
Dockerfile: ENV param1="default1"
docker run -it -e param1=notdefault1 my_image

Using ENTRYPOINT With A Bash Call

If ENTRYPOINT is specified, the "bash" command is skipped, unlike CMD where the entry is put after a bash command. In ENTRYPOINT, bash must be called explicitly. Example: ENTRYPOINT ["/bin/bash", "-c", "myscript.sh"]. This is only needed if you want to invoke Bash.
When specifying Bash, /bin/bash -c can only take one argument. To provide arguments to the script, use ENTRYPOINT ["/bin/bash", "-c", "myscript.sh \"my string arg\"", "--"] since bash -c only takes one argument as a string.
The -- is added so Bash will not interpret the text after it as arguments for Bash.

Docker Optimization

Multi-stage

Use multi-stage builds to reduce layers in the build by utilizing intermediary builds and keeping only the needed layers.
dockerfile
1FROM node:16 AS myIntermediaryBuild
2WORKDIR /app
3COPY . .
4
5FROM node:latest
6COPY --from=myIntermediaryBuild /app /
7EXPOSE 8080
8RUN index.js
9
snippet hosted withby Xavier

Docker Debian

When using debian, Python will not be included by default.
dockerfile
1RUN apt-get update -y; \
2    apt-get install vim -y; \
3    apt-get install python3-pip -y; \
4
snippet hosted withby Xavier

Clean Up Unused Images And Containers

Leaving Docker images and stopped containers will take up vast memory on your machine if left unchecked. Regularly remove downloaded images and stopped containers.
Docker takes a conservative approach to cleaning up unused objects (often referred to as “garbage collection”), such as images, containers, volumes, and networks: these objects are generally not removed unless you explicitly ask Docker to do so.

Images

docker image prune
To remove all images which are not used by existing containers, use the -a flag: docker image prune -a.

Containers

docker container prune

Volumes

docker volume prune

Everything

docker system prune

Data Storage

Volumes and mounts connect files between the container and the host OS to persist data used by the container.

Volumes

The preferred way to persist data generated by containers. Bind mounts can also store data, but files are connected to the host OS.
Volumes are easier to migrate than bind mounts, work on both Linux and Windows, and can be shared among various containers.
Create: docker volume create [my-volume-name]
List: docker volume ls
Inspect: docker volume inspect [my-volume-name]
Remove: docker volume rm [my-volume-name]
Start container with specified volume:
Shell
1docker volume create myvolume
2docker run --mount source=myvolume,target=/dironcontainer ...
3
snippet hosted withby Xavier
  • source: Volume specified
  • target: Location to mount on container
Created volumes can only be included through the run command, not through a Dockerfile.

Bind Mounts

Instead of a dedicated volume for container storage, a bind mount uses the host OS file system.
docker run --mount type=bind,source="$(pwd)/dirhost,target=/dircontainer" ...

Tmpfs (Linux only)

Unlike volumes and bind mounts, tmpfs is temporary. Once the container stops, tmpfs is removed. This option is useful for sensitive data you do not want on the host OS.
docker run --mount type=tmpfs,destination=/dironcontainer,tmpfs-mode=0777 ...

Run Docker On Restart

docker run -d --restart [always|no|on-failure:#|unless-stopped] [container name]
  • no: Do not automatically restart the container (default).
  • on-failure[:max-retries]: Restart the container if it exits due to an error (non-zero exit code). Optionally limit restart attempts with :max-retries.
  • always: Always restart the container if it stops. If manually stopped, restart only when Docker daemon restarts or the container is manually restarted.
  • unless-stopped: Similar to always, except when the container is stopped (manually or otherwise), it does not restart even after Docker daemon restarts.

Run Multiple Processes In A Container

Shell
1#!/bin/bash
2
3# Start the first process
4./my_first_process &
5
6# Start the second process
7./my_second_process &
8
9# Wait for any process to exit
10wait -n
11
12# Exit with status of process that exited first
13exit $?
14
snippet hosted withby Xavier
Shell
1# syntax=docker/dockerfile:1
2FROM ubuntu:latest
3COPY my_first_process my_first_process
4COPY my_second_process my_second_process
5COPY my_wrapper_script.sh my_wrapper_script.sh
6CMD ./my_wrapper_script.sh
7
snippet hosted withby Xavier

Further Reading

Related Articles

Related by topics:

devops
infrastructure
cloud
aws
Docker Image Storage Options

Comparison of Docker Hub, AWS ECR, Google Artifact Registry with my experience.

By Xavier Collantes1/25/2025
docker
devops
infrastructure
+5

HomeFeedback