Docker CLI Cheat Sheet

List running and stopped containers

See all running containers (includes port information, id and name)

docker ps

See all containers including stopped containers

docker ps -a

Docker images

List all images on your machine

docker images

Remove an image with the container ID of e9dc2cdd84f9

docker image rm e9dc2cdd84f9

Get a shell on a running container

Get the name or ID of the container you wish to get a shell session by running docker ps

# docker ps
CONTAINER ID   IMAGE         COMMAND                 CREATED        STATUS        PORTS                                                                     NAMES
5c229f1c57d8   nginx:nginx   "/docker-entrypoint.…"  8 seconds ago  Up 3 seconds  0.0.0.0:80->80/tcp, :::80->80/tcp, 0.0.0.0:443->443/tcp, :::443->443/tcp  Nginx

Run the execute command with the CONTINAER ID and the -it interactive flag.

docker exec -it 5c229f1c57d8 bash

Or you can use the NAME of the container

docker exec -it Nginx bash

You can log in as root by specifying the user

docker exec -it --user root 5c229f1c57d8 bash

If you get this error CI runtime exec failed: exec failed: unable to start container process: exec: "bash": executable file not found in $PATH: unknown then it means that bash is not installed on the container. Common docker container images such as alpine does not come with bash. You can use sh instead

docker exec -it --user root 5c229f1c57d8 sh

Docker Compose

Building

Build your project

docker compose build

Build your project without using any local cache

docker compose build --no-cache

Starting and stopping containers

Start your project in the foreground

docker compose start

Stop docker compose containers running in the foregoround

docker compose stop

Start the project and follow all the containers logs in your terminal

docker compose up

Another way to stop all your compose containers running

docker compose down

Freeing up disk space from Docker

Remove dangling images (untagged images that display <none> for the name)

docker image prune

Remove dangling images and unused images (not assigned or used in a container)

docker image prune -a

Remove all stopped containers, dangling images, networks and build cache

docker system prune

Remove all stopped containers, dangling images, networks and build cache and unused images

docker system prune -a