Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Docker CLI Cheatsheet

Related Posts

Table of Contents

Container Management

Run A Container (docker-run)

Below is an example for launching a new container from an image. If the image doesn't exist locally, then Docker will try to pull the image from the registry.

sudo docker run \
  --detach \
  --name my-container-name \
  --publish 80:80 \
  --publish 443:443 \
  -v "/path/on/host:/path/in/container" \
  -v "named-volume:/path/in/container" \
  --env FOO=bar \
  --env FOO2=bar2 \
  $REGISTRY/IMAGE-NAME:$TAG
  • Optionally add the --rm switch to have the container remove itself as soon as it stops running.
  • If a registry is not provided, the default registry is the docker-hub, for which one would have a vendor name. E.g. programster/dnsmasq
  • A $TAG is not required, and will default to latest.

Change/Disable Logging

One can change the logging driver at the point of running the container by adding the --log-driver parameter. For example, to simply disable logging, one could use:

sudo docker run \
  --log-driver=none \
  $REGISTRY/IMAGE-NAME:$TAG

Alternatively, if you do want to keep the default JSON logging driver, but prevent it from growing too large, then you could do something like the following, which will set the maximum size of the log file to 4MB before it is rotated, and keeping up to 3 log files at a time.

sudo docker run \
  --log-driver=json-file \
  --log-opt max-size=4m \
  --log-opt max-file=3 \
  $REGISTRY/IMAGE-NAME:$TAG

List Containers

List Running Containers

docker ps

List All Containers (Running or otherwise)

docker ps -a

Specify Table Columns

For a version that removes the ID and Command columns so it is much more likely to fit in your terminal window:

docker ps -a --format="table {{.Names}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}"

Enter A Running Container

docker exec -it $ID_OR_NAME /bin/bash

Sometimes the container won't have bash, so swap out for sh in such cases.

Execute Command In Running Container

This is actually the same as "entering the container", it's just that the command isn't /bin/bash, and in this case we don't need it to be interactive or allocate a TTY.

docker exec $ID_OR_NAME $MY_COMMAND

The cron service, and Jenkins do not run with a TTY, so if you ever run docker exec with -it , you will get this error message: "Error "The input device is not a TTY"

Remove stopped Containers

docker rm $(docker ps -a -q)

You may get the message

Error: failed to remove one or more containers

That just occurs when you have running containers (running containers get passed to the remove command but will fail to get removed.

Stop And Remove All Containers

docker stop `docker ps -aq`  
docker rm `docker ps -aq` 

Inspect Container

If you want to find out about running containers, then the following command is for you:

docker inspect $CONTAINER_ID

This will output a massive JSON structure with everything there is to know about the containers. I find this particularly useful for finding out what mounts/volumes there are.

Because the output is JSON, you can combine it with jq to filter out only the bits you care about. Below are some really useful examples.

Output the Environment Variables

docker inspect $CONTAINER_ID | jq '.[0].Config.Env'

Output the Mounts

docker inspect $CONTAINER_ID | jq '.[0].Mounts'

Output the Volumes

docker inspect $CONTAINER_ID | jq '.[0].Config.Volumes'

Output the Entrypoint

docker inspect $CONTAINER_ID | jq '.[0].Config.Entrypoint'

Get Running Statistics

The command below outputs statistics about all of your running containers. This is particularly useful if you are worried one of them may be eating too much memory.

docker stats

Example output:

CONTAINER ID   NAME             CPU %     MEM USAGE / LIMIT     MEM %     NET I/O           BLOCK I/O         PIDS
2e8080158360   docsify          0.01%     48.48MiB / 15.55GiB   0.30%     131kB / 7.24MB    7.77MB / 4.1kB    13
5e7ed4de3176   home-webserver   0.00%     16.05MiB / 15.55GiB   0.10%     53.9MB / 4.09GB   11.1GB / 4.1kB    5
9db0fc693f84   app              0.00%     41.46MiB / 15.55GiB   0.26%     23.4MB / 6.22MB   275MB / 42.7MB    2
fae6198902d0   coin-site-db     0.00%     31.74MiB / 15.55GiB   0.20%     1.95MB / 4.76MB   44.2MB / 60.7MB   7
50a381764f13   meilisearch      0.06%     12.19MiB / 15.55GiB   0.08%     5.51MB / 4.71MB   158MB / 3.67GB    9

Image Management

Build an Image docker build

Below is a really simple example that one may use to build an image from a Dockerfile in the same folder as where you are running the command from:

docker build .

Below is a more complicated/verbose example that one may use.

BUILD_CONTEXT_PATH="."

docker build \
  --no-cache \
  --file="$BUILD_CONTEXT_PATH/docker/Dockerfile-node-modules" \
  --tag="my-image-name" \
  --build-arg MY_VARIABLE=Susan \
  --build-arg MY_OTHER_VARIABLE=BoyleS \
  $BUILD_CONTEXT_PATH

Specifying No Cache

The --no-cache option tells the build to build everything without using any cache. Using this option can dramatically slow down your build, but is probably a good idea when using in your CI/CD pipeline, rather than local development.

Specifying The Dockerfile Path

The --file is usually not necessary, as would usually just have the build file called Dockerfile, but I wanted to show how to be able to perform a build from a different location for the build context.

If one uses a relative path, Docker will consider this path relative to the build context and not relative to where you are calling the build command from. Thus, it may be simpler to always to just use a $BUILD_CONTEXT_PATH variable to prevent mistakes.

Tagging

With regards to the --tag option. One could additionally specify the registry by specifying registry.mydomain.com/my-image-name, or specify a tag, not just the image name like so: my-image-name:ce-latest, or all three like so: registry.mydomain.com/my-image-name:ce-latest. If wanting to push to the Dockerhub registry, then your username would go where the registry name would go. E.g. programster/my-image-name:ce-latest.

Build Args

Please refer to [my other post on build arguments](https://blog.programster. org/docker-build-argumentsS).

List Images

One can use any of the following commands to list all Docker images that you have locally:

docker image list
docker image ls
docker images --all

Get Information About Specific Image

docker images ${IMAGE_NAME}

Tab completion works, so after typing docker images, one can press tab-tab to get a list of all the docker images, and if you partially complete the name of an image, only results that start with what you have already typed will appear.

Docker - Get Latest Built Image ID

docker images -q | sed -n 2p  

Remove "Dangling" Images

docker image prune

Alternatively...

docker rmi $(docker images --quiet --filter "dangling=true")  

shorthand:

docker rmi $(docker images -q --f "dangling=true")

This could be unsafe if you run it whilst docker images are being pulled.

Delete / Remove All Images

docker prune images --all

Alternatively...

docker rmi $(docker images -q)  

Alternatively....

IMAGES=`docker images | tail -n +2 | tr -s ' ' | cut -d ' ' -f3`
echo "${IMAGES}" | xargs -I %s docker rmi %s

You won't be able to remove images that running containers are using.

Save Image To File

The following command will save the image myDockerImageName with the tagged version of latest to the file called myCustomFileaname.tar.

docker save \
  --output myCustomFileaname.tar \
  myDockerImageName:latest

Load Image From File

docker load --input myCustomFileaname.tar

This will load the image with the name/tag it had from the machine it was saved with. It does not matter what the filename is.

Logs

View Container Logs / Output

You can view the logs by running:

docker logs $CONTAINER_ID_OR_NAME

Watch / Follow Logs

The example above will only output the logs it has so far. If you want to see the logs and watch/tail them for updates, then do the following:

docker logs --follow $CONTAINER_ID_OR_NAME

Specify Log Configuration

The following will result in Docker logging to a JSON file, with a max size of 10 MiB, and only keeping up to 3 of them. Thus your logs will never exceed 30 MiB.

docker run \
  --log-driver json-file \
  --log-opt max-size=10m \
  --log-opt max-file=3 \
  docker-image-name

Build Arguments

Please refer here.

Misc

Output Disk Usage

You can output the amount of storage being used by Docker in various ways with the following command:

docker system df

This will output something like

TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          441       1         91.92GB   91.89GB (99%)
Containers      1         1         421.4kB   0B (0%)
Local Volumes   50        0         4.651GB   4.651GB (100%)
Build Cache     5955      5161      86.63GB   9.664GB

If you want the output in JSON format, then you can use:

docker system df --format json

However, that will output multiple lines of JSON, rather than one JSON object. E.g. see below:

{"Active":"1","Reclaimable":"91.89GB (99%)","Size":"91.92GB","TotalCount":"441","Type":"Images"}
{"Active":"1","Reclaimable":"0B (0%)","Size":"421.4kB","TotalCount":"1","Type":"Containers"}
{"Active":"0","Reclaimable":"4.651GB (100%)","Size":"4.651GB","TotalCount":"50","Type":"Local Volumes"}
{"Active":"0","Reclaimable":"86.39GB","Size":"86.39GB","TotalCount":"5954","Type":"Build Cache"}

I'm pretty sure that one could probably convert the output of the original command into a better JSON format using the column command, but have not taken the time to figure out the exact way just yet.

Copy Files

One may need to copy files from a container to the host, such as the logs. For this use the docker cp command like so:

docker cp $CONTAINER_ID:/path/to/files/in/container /path/on/host

This also works in reverse, when one wishes to copy files into a container:

docker cp /path/on/host $CONTAINER_ID:/path/to/files/in/container

Push To Registry

If you just built a container that doesn't contain a registry name, you can push it to your own docker registry by tagging it first and then pushing it.

E.g. to push an image you just created called "bob" to your registry at "registry.mydomain.com:5000" you would use:

docker tag bob registry.mydomain.com:5000/bob
docker push registry.mydomain.com:5000/bob

You may need to use docker login registry.mydomain.com:5000 first for authentication.

Get the Storage Driver Being Used

Different distributions will use different storage drivers. For example, CentOS and Amazon linux will use the devicemapper driver, whereas Ubuntu will use aufs. To find out which storage driver you are using, run:

docker info | grep "Storage Driver"

Go here to get a list of the storage drivers you can use.

References

Last updated: 6th January 2025
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch