# Docker Commands Master Cheat Sheet

## Why You Need a Docker Cheat Sheet

Docker lets you package an application with everything it needs and run it the same way on your laptop, a CI server, or production. The idea is simple, but the command line is not: dozens of subcommands, hundreds of flags, and a few commands that can quietly delete data you wanted to keep.

This guide covers the commands you will actually use, with short examples you can paste straight into your terminal. It also includes the parts most cheat sheets skip: how to reclaim disk space, how to debug a container that will not start, and which habits keep you out of trouble.

**Golden rule:** when you are unsure, look before you act.

```bash
docker ps -a            # what containers exist?
docker images           # what images do I have?
docker system df        # how much disk is Docker using?
docker <command> --help # flags for any command
```

## The Mental Model in 30 Seconds

Almost every Docker mistake comes from mixing up these five things:

```rust
Dockerfile  --build-->  Image  --run-->  Container
                          ^                  |
                          |                  +-- uses --> Volumes (persistent data)
                  push / pull                +-- uses --> Networks (communication)
                          |
                      Registry (Docker Hub, GHCR, ECR)
```

-   **Image:** a read-only blueprint, built from a Dockerfile.
    
-   **Container:** a running (or stopped) instance of an image.
    
-   **Volume:** storage that outlives any single container.
    
-   **Network:** how containers talk to each other and the outside world.
    
-   **Registry:** where images are stored and shared.
    

**The one idea to remember:** containers are disposable, volumes are not. Anything written inside a container's filesystem disappears when you remove the container, unless it lives on a volume.

## 1\. Setup and Sanity Checks

```bash
docker --version                     # client version
docker compose version               # Compose plugin version
docker info                          # detailed system information
docker run hello-world               # verify the whole pipeline works
```

On Linux, if you must type `sudo` before every command, add yourself to the docker group:

```bash
sudo usermod -aG docker $USER        # log out and back in afterward
```

Be aware that membership in the `docker` group is effectively root access on that machine, so only grant it to people you trust.

## 2\. Working with Images

```bash
docker pull nginx:1.27               # download a specific version
docker images                        # list local images
docker build -t myapp:1.0 .          # build from the Dockerfile in this folder
docker build --no-cache -t myapp:1.0 .   # rebuild every layer from scratch
docker tag myapp:1.0 myapp:latest    # add another tag to an image
docker history myapp:1.0             # see the layers and their sizes
docker image inspect myapp:1.0       # full metadata as JSON
docker rmi myapp:1.0                 # delete an image
```

**Tip:** always specify a version tag. `nginx` means `nginx:latest`, which can change under you without warning.

## 3\. Running Containers

`docker run` creates and starts a container from an image. It has the most flags, so here are the ones that matter.

```bash
docker run nginx                              # run in the foreground
docker run -d nginx                           # detached (in the background)
docker run -d --name web nginx                # give the container a name
docker run -d -p 8080:80 nginx                # publish host port 8080 to container port 80
docker run -d -e API_KEY=abc123 myapp         # set an environment variable
docker run -d --env-file .env myapp           # load variables from a file
docker run -d -v mydata:/var/lib/data myapp   # attach a named volume
docker run --rm -it ubuntu bash               # interactive shell, auto-delete on exit
docker run -d --restart unless-stopped nginx  # restart after crashes and reboots
docker run -d --memory 512m --cpus 1.5 myapp  # limit resources
```

How to read `-p 8080:80`: it is **host:container**. Visit `localhost:8080` on your machine and traffic goes to port 80 inside the container.

Flag cheat sheet: `-d` detach, `-it` interactive terminal, `-p` publish port, `-e` environment variable, `-v` volume or bind mount, `--rm` remove when it stops, `--name` custom name.

## 4\. Managing Containers

```bash
docker ps                        # running containers
docker ps -a                     # all containers, including stopped ones
docker stop web                  # graceful stop (SIGTERM, then SIGKILL)
docker start web                 # start a stopped container
docker restart web               # stop and start
docker kill web                  # immediate SIGKILL
docker rename web web-old        # rename a container
docker rm web                    # delete a stopped container
docker rm -f web                 # stop and delete in one step
```

## 5\. Looking Inside a Container

When something is wrong, these are the commands you will reach for first.

```bash
docker logs web                  # print logs
docker logs -f --tail 100 web    # follow the last 100 lines live
docker exec -it web bash         # open a shell in a running container
docker exec -it web sh           # use sh if bash is not installed (Alpine images)
docker exec web ls /app          # run a single command
docker inspect web               # full configuration as JSON
docker top web                   # processes inside the container
docker stats                     # live CPU, memory, and network usage
docker stats --no-stream         # one snapshot instead of a live view
docker port web                  # show published port mappings
docker cp web:/app/log.txt .     # copy a file out of a container
docker cp ./config.json web:/app/    # copy a file in
```

`run` **vs** `exec`**:** `docker run` creates a _new_ container from an image. `docker exec` runs a command inside a container that is _already running_.

## 6\. Volumes and Bind Mounts

```bash
docker volume create mydata               # create a named volume
docker volume ls                          # list volumes
docker volume inspect mydata              # where it lives and who uses it
docker volume rm mydata                   # delete a volume (data is gone)

docker run -v mydata:/data myapp          # named volume: managed by Docker
docker run -v $(pwd):/app myapp           # bind mount: your folder, live-synced
docker run -v $(pwd)/config:/config:ro myapp   # read-only bind mount
```

Use **named volumes** for data you want to keep, such as databases. Use **bind mounts** for source code during development, so edits on your machine appear instantly in the container.

### Back up a volume

```bash
docker run --rm -v mydata:/data -v $(pwd):/backup alpine \
  tar czf /backup/mydata.tgz -C /data .
```

## 7\. Networking

Containers on the same **user-defined network** can reach each other by container or service name.

```bash
docker network ls                         # list networks
docker network create appnet              # create a network
docker run -d --name db --network appnet postgres:16
docker run -d --name api --network appnet myapp
# inside "api", the database is reachable at the hostname "db"

docker network connect appnet web         # attach a running container
docker network inspect appnet             # see connected containers and IPs
docker network rm appnet                  # delete a network
```

Remember: inside a container, `localhost` means _that container_, not your computer and not other containers. Use the service name instead.

## 8\. Dockerfile Essentials

A Dockerfile is a recipe for building an image. Here is a clean example for a Node.js app:

```dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
USER node
CMD ["node", "server.js"]
```

The instructions you will use most:

-   `FROM` sets the base image.
    
-   `WORKDIR` sets the working directory for later instructions.
    
-   `COPY` copies files from your machine into the image.
    
-   `RUN` executes a command at build time and saves the result as a layer.
    
-   `ENV` sets an environment variable.
    
-   `EXPOSE` documents which port the app listens on (it does not publish it).
    
-   `USER` switches to a non-root user.
    
-   `CMD` sets the default command. `ENTRYPOINT` sets the fixed executable that `CMD` arguments are passed to.
    

### Habits that make better images

1.  **Order layers from least to most frequently changed.** Copy dependency files and install first, then copy your source code. This keeps Docker's build cache working for you.
    
2.  **Add a** `.dockerignore` **file** so `node_modules`, `.git`, and `.env` never enter the build context.
    
3.  **Use small base images** such as `-alpine` or `-slim` variants.
    
4.  **Use multi-stage builds** so compilers and build tools never reach the final image.
    
5.  **Run as a non-root user** whenever possible.
    

### Multi-stage build example

```dockerfile
FROM golang:1.23 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server

FROM gcr.io/distroless/static:nonroot
COPY --from=build /app /app
ENTRYPOINT ["/app"]
```

The final image contains only the compiled binary, which makes it far smaller and has a much smaller attack surface. Use the Go version your project actually targets.

## 9\. Docker Compose

Compose runs multi-container applications from a single `docker-compose.yml` file. Note that modern Docker uses `docker compose` (with a space). The older hyphenated `docker-compose` is the legacy standalone tool.

```bash
docker compose up -d             # create and start everything in the background
docker compose up -d --build     # rebuild images first
docker compose ps                # status of services
docker compose logs -f           # follow logs from all services
docker compose logs -f api       # follow one service
docker compose exec api sh       # shell into a service
docker compose run --rm api npm test   # one-off command in a fresh container
docker compose restart api       # restart one service
docker compose pull              # pull the latest images
docker compose config            # validate and print the final config
docker compose down              # stop and remove containers and networks
docker compose down -v           # ...and also delete the volumes (data loss)
```

### Example: a web app with a database

```yaml
services:
  web:
    build: .
    ports:
      - '3000:3000'
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/app
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U app']
      interval: 5s
      timeout: 3s
      retries: 5

volumes:
  pgdata:
```

Notes: the top-level `version:` key is obsolete in current Compose and can be omitted. The inline password here is for a local demo only; for anything real, load secrets from an env file or a secrets manager.

## 10\. Registries: Sharing Images

```bash
docker login                             # log in to Docker Hub
docker login ghcr.io                     # log in to another registry
docker tag myapp:1.0 username/myapp:1.0  # name the image for your account
docker push username/myapp:1.0           # upload
docker pull username/myapp:1.0           # download
docker logout                            # remove stored credentials
```

## 11\. Cleaning Up and Reclaiming Disk Space

Docker can quietly eat tens of gigabytes. Start by seeing where the space went.

```bash
docker system df                 # disk usage by images, containers, volumes, cache
docker container prune           # remove all stopped containers
docker image prune               # remove dangling (untagged) images
docker image prune -a            # remove all images not used by a container
docker volume prune              # remove volumes not used by any container
docker builder prune             # clear the build cache
docker system prune              # stopped containers, unused networks, dangling images
```

**Warning:** `docker system prune -a --volumes` deletes everything unused, including volumes that may hold database data. Run `docker system df` and `docker volume ls` first, and never run it on a machine where you are not sure what is stored.

## 12\. Troubleshooting by Symptom

**The container exits immediately.** Run `docker ps -a` to see the exit code, then `docker logs <name>` to see why. To poke around, start it with a shell instead: `docker run --rm -it --entrypoint sh myapp`.

**Useful exit codes:** `0` finished normally, `1` application error, `137` killed (often out of memory), `143` stopped by SIGTERM.

**I cannot reach the app in my browser.** Check that you published the port (`-p 8080:80`) with `docker port <name>`. Then make sure the app listens on `0.0.0.0` inside the container, not `127.0.0.1`, or it will refuse outside connections.

**One container cannot reach another.** Put both on the same user-defined network and connect using the service name, not `localhost`.

**My code changes do not show up.** Either you need to rebuild (`docker compose up -d --build`), a cached layer is stale (`docker build --no-cache`), or you forgot a bind mount for development.

**Permission denied when talking to the Docker daemon.** Your user is not in the `docker` group (see section 1), or the Docker service is not running.

**Docker says there is no space left on device.** Run `docker system df`, then prune what you can safely remove (section 11).

## 13\. Handy One-Liners

```bash
# Stop every running container
docker stop $(docker ps -q)

# Remove every container, running or not (careful)
docker rm -f $(docker ps -aq)

# Show a container's IP addresses
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' web

# A clean, readable list of images and their sizes
docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}'

# Throwaway Ubuntu shell for testing
docker run --rm -it ubuntu bash

# Serve the current folder on http://localhost:8080
docker run --rm -p 8080:80 -v $(pwd):/usr/share/nginx/html:ro nginx

# Run a tool without installing it, using your current folder
docker run --rm -v $(pwd):/app -w /app node:20 npm test

# Follow the last 50 log lines of every Compose service
docker compose logs -f --tail 50
```

## Safety Habits Worth Building

1.  **Pin your image tags.** Avoid `:latest` in anything that matters. Pin a version (or even a digest) so builds are repeatable.
    
2.  **Never bake secrets into images.** Anything you `COPY` or set with `ENV` in a Dockerfile can be extracted by anyone who gets the image. Pass secrets at runtime instead.
    
3.  **Run as a non-root user.** Add `USER` to your Dockerfile so a compromised app has less power.
    
4.  **Prune with care.** `--volumes` and `down -v` delete data. Look first with `docker volume ls`.
    
5.  **Do not mount the Docker socket into containers** (`/var/run/docker.sock`) unless you understand the risk, because it gives the container control of the host.
    
6.  **Keep a** `.dockerignore`**.** It speeds up builds and keeps secrets out of the build context.
    

## Final Thoughts

You do not need to memorize all of this. Learn the daily loop of `build`, `run`, `logs`, `exec`, and `stop`, get comfortable with `docker compose up` and `down`, and keep the cleanup and troubleshooting sections within reach for the days when something misbehaves. Everything else can live in this cheat sheet.

Pick one command from this list that you have never tried, such as `docker stats`, a multi-stage build, or the volume backup trick, and use it on a real project this week. That is how a cheat sheet turns into real skill.

---

*Published via [ZyVOP](https://zyvop.com/docker-commands-master-cheat-sheet-6engq?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
