Skip to main content

Essential Docker Commands Cheatsheet

Pascal Spörri
Author
Pascal Spörri
Table of Contents
Frequently used Docker commands and practical patterns for development and debugging.

Command-Line Cheatsheet
#

Run an interactive container with environment variables and volume
#

docker run \
    -it \
    -e VAR_A=1 -e VAR_B=2 \
    -v "$PWD":/app \
    -w /app \
    ubuntu:22.04 bash

📝 Tip: Mounting the current directory into /app is useful for testing in a real file system context.


Build a Docker image
#

docker build -t my-image -f Dockerfile .

You can omit -f Dockerfile if your file is named Dockerfile.


List running containers
#

docker ps

To see all containers (running or stopped):

docker ps -a

Exec into a running container
#

docker exec -it <container_name_or_id> bash

For Alpine-based containers, use sh instead of bash.


Clean up stopped containers
#

docker container prune

Or delete exited containers only:

docker rm $(docker ps -q -f status=exited)

Prune unused images
#

docker image prune -a

⚠️ This deletes all unused images not referenced by any container.


Example Dockerfile
#

FROM ubuntu:22.04

# Set timezone
ENV TZ=Europe/Zurich
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# Enable multiarch and install essentials
RUN apt-get update && \
    apt-get install -y \
        build-essential \
        wget \
        curl \
        expect \
        sudo && \
    rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN useradd -ms /bin/bash user

🛠️ Consider using multi-stage builds or slimming down base images for production use.