# The Docker CLI day to day: inspect, filter, format and clean up

The commands you use every day for images, containers, volumes and networks, how to filter and format their output for scripts, and how to win back disk space safely with docker system df and prune.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 12. About 25 minutes, beginner. Source: https://devops.rajeev.pro/courses/docker/12-docker-cli

## What you will learn

- Manage images, containers, volumes and networks with the docker <object> <verb> commands
- Filter lists with --filter and shape output with --format and Go templates
- Read any setting of a container or image with docker inspect
- Copy files in and out of containers, and watch live usage with docker stats
- See where disk space goes with docker system df, and reclaim it with the right prune

## One pattern

Before a shared command pattern, Docker users had to remember a different command family for images,
containers, volumes and networks. The same small set of actions now applies to each object: list, inspect,
remove and prune. In this lesson, you'll use that pattern to find objects, inspect their settings and reclaim
space without deleting data you intended to keep.

| Object      | ls                                  | inspect                    | rm                           | prune                    |
| ----------- | ----------------------------------- | -------------------------- | ---------------------------- | ------------------------ |
| `image`     | `docker image ls` (`docker images`) | `docker image inspect`     | `docker image rm` (`rmi`)    | `docker image prune`     |
| `container` | `docker container ls` (`docker ps`) | `docker container inspect` | `docker container rm` (`rm`) | `docker container prune` |
| `volume`    | `docker volume ls`                  | `docker volume inspect`    | `docker volume rm`           | `docker volume prune`    |
| `network`   | `docker network ls`                 | `docker network inspect`   | `docker network rm`          | `docker network prune`   |

`docker <object> --help` lists the rest.

The object-first pattern makes commands easier to discover: choose the object, then ask Docker to list or inspect
it. `rm` removes one named object; `prune` finds a class of unused objects and can remove several at once.
Because prune can delete useful data, inspect the target list and read the command's confirmation before accepting
it. The rest of this lesson uses that pattern on each object type and checks the result after cleanup.

## Images

An image is a reusable template; it is not a running process. List images to see tags and size, then inspect or
review history when you need to understand what will run. Removing a tag does not necessarily remove shared
layers, because another image may still reference them. Pulling a specific platform is useful when you need to
check an image for a different CPU architecture than the current host.

`image history` shows the build layers that contributed to an image. `image inspect` shows its configuration,
including the default user and entry point. These are useful checks before running a new image or diagnosing a
large one. Removing a tag is not the same as deleting every layer: Docker keeps layers still referenced by
another tag. Use the platform option when testing a multi-platform image, and confirm the host can run the
architecture you select.

```sh
$ docker image ls --filter reference='price-api*' --format '{{.Repository}}:{{.Tag}} {{.Size}}'
price-api:multi 14.6MB
price-api:dev 14.6MB
price-api:single 508MB
$ docker image history price-api:multi            # layers and their sizes (lesson 7)
$ docker image inspect price-api:multi --format '{{.Config.User}} {{json .Config.Entrypoint}}'
nonroot ["/price-api"]
$ docker image rm price-api:single                # removes the tag; layers go when nothing uses them
$ docker pull --platform linux/arm64 alpine:3.22  # a specific architecture
```

## Containers

A container is a created instance of an image, with runtime configuration such as its command, mounts, network
and environment. `ps` answers what is running; adding `-a` includes stopped containers. Inspect the state and
exit code before removing a failed container, and use logs to see what its process wrote. `exec` is for a
command inside a running container; `run` creates a new one. Keeping those actions distinct makes debugging
safer and easier to repeat.

```sh
$ docker ps -a --filter status=exited --format 'table {{.Names}}\t{{.Status}}'
$ docker inspect web --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'
$ docker logs --since 10m --tail 50 web
$ docker exec -it web sh
$ docker cp web:/etc/nginx/nginx.conf ./nginx.conf       # copy out of a container
$ docker cp ./index.html web:/usr/share/nginx/html/      # and into it
$ docker stats --no-stream                               # CPU, memory, network, against limits
$ docker top web                                         # processes, as the host sees them
$ docker container rm -f $(docker ps -aq --filter label=env=test)   # remove a whole group
```

`--filter` narrows lists (by `status`, `name`, `label`, `ancestor`, `network`…). `--format` takes a Go
template: `{{.Names}}`, `{{json .Config}}`, `table` for aligned columns. `docker inspect` returns everything
Docker knows about an object as JSON, and is the first place to look when something behaves oddly: the
mounts, environment, restart count, health log and exit code are all there.

## Volumes and networks

Volumes hold data outside a container's writable layer, so removing the container does not automatically mean
the data should be removed. Networks connect selected containers and provide names for service discovery.
Inspect both before cleanup: a named database volume may be valuable, while an anonymous test volume may be
disposable. The commands below show how to list and inspect these objects before taking action.

Use a volume for data that must outlive a container replacement, such as a development database. Use a network
to define which services can discover and reach one another. Both objects have independent lifecycles, so removing
one container does not tell you whether its data or network should be removed. Check the names and references
first; a named volume is easier to recognize and protect than an anonymous one.

```sh
$ docker volume ls --filter dangling=true          # volumes no container uses
$ docker volume inspect shop_pgdata --format '{{.Mountpoint}}'
$ docker network ls
$ docker network inspect appnet --format '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{"\n"}}{{end}}'
```

## Cleanup

Docker never deletes anything on its own. Images from old builds, stopped containers, anonymous volumes and the
build cache pile up until the disk is full, often on a CI runner at 2 a.m. See where the space goes:

```sh
$ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          21        0         5.446GB   479MB (8%)
Containers      0         0         0B        0B
Local Volumes   14        0         510.6MB   510.6MB (100%)
Build Cache     74        0         1.226GB   447.7MB
```

That's this machine after the course so far: 14 volumes nobody uses (mostly anonymous Postgres volumes from
lesson 6) and half a gigabyte of build cache. Clean each kind on purpose:

```sh
$ docker volume prune -f
Total reclaimed space: 510.6MB
$ docker builder prune -f
Total:	404.6MB
$ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          21        0         5.045GB   77.44MB (1%)
Containers      0         0         0B        0B
Local Volumes   1         0         0B        0B
Build Cache     37        0         820.9MB   43.11MB
```

| Command                  | Removes                                                                                      |
| ------------------------ | -------------------------------------------------------------------------------------------- |
| `docker container prune` | stopped containers                                                                           |
| `docker image prune`     | dangling images (untagged leftovers); `-a`: every image no container uses                    |
| `docker volume prune`    | unused **anonymous** volumes; `--all`: unused named volumes too                              |
| `docker network prune`   | networks no container uses                                                                   |
| `docker builder prune`   | build cache; `--filter until=168h` keeps the last week                                       |
| `docker system prune`    | containers, networks, dangling images and build cache; add `--volumes` or `-a` to go further |

> **Read before you prune.** Prune asks for confirmation and lists what it will delete: read that list. A volume prune deletes data with no undo, and `docker system prune -a --volumes` on a server can remove the database volume of a stack that is stopped for maintenance. Never put `-a --volumes` in a cron job.

> **In production.** On CI runners and build servers, schedule `docker builder prune --filter until=168h -f` and `docker image prune -a --filter until=168h -f`. On application servers, keep a few previous images for rollback, and set a log size limit (`--log-opt max-size=10m --log-opt max-file=3`) so container logs can't fill the disk.

## Measure before you prune

`docker system df` maps image, container and volume usage; prune narrowly after checking what is reclaimable.
`inspect --format` gives stable fields for scripts, and `docker context show` confirms which daemon a command will
affect. These are operational safeguards, not backups.

Prune is destructive to Docker objects, so use it only after measuring and checking what is unused. Start with
the exact object type and list candidates before removal. A stopped container can still hold a volume reference,
and a local Docker context can point at a different machine than you expect. Confirm the context, preserve named
volumes, and rerun the disk report after cleanup. This gives you evidence that space was reclaimed without
turning a routine housekeeping command into data loss.

```sh
$ docker system df
$ docker ps --format '{{.Names}} {{.Image}} {{.Status}}'
$ docker inspect api --format '{{.Name}} {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'
$ docker context show
$ docker container prune --filter until=24h
```

> **Video.** [Docker CLI Walkthrough: run, exec, logs, images, volumes, prune | #12](https://www.youtube.com/watch?v=vfLp0nh_qMA&t=459s) (Techno Bytes Unlocked)

## Mission: Find and reclaim wasted space

Measure Docker's disk use, create some junk on purpose (exited containers, anonymous volumes, a dangling image), find each kind with filters, and remove it with the matching prune without touching a named volume you want to keep.

- You need: Docker
- You'll have: docker system df before and after, with the keep-me volume still present

```sh
$ docker system df
$ docker volume create keep-me
$ for i in 1 2 3; do docker run -v /data alpine:3.22 true; done        # 3 exited containers, 3 anonymous volumes
$ docker ps -a --filter status=exited --filter ancestor=alpine:3.22 --format '{{.Names}} {{.Status}}'
$ docker container prune -f
$ docker volume ls --filter dangling=true        # now unused: the 3 anonymous ones, and keep-me
$ docker volume prune -f
$ docker volume ls --filter name=keep-me
DRIVER    VOLUME NAME
local     keep-me
$ docker system df && docker volume rm keep-me
```

`volume prune` removed the anonymous volumes but kept `keep-me`, because named volumes need `--all`. Order
matters too: volumes still attached to a stopped container aren't unused, so containers go first.

## Try it

- Run `docker system df` and find which type uses the most reclaimable space.
- List only exited containers with `docker ps -a --filter status=exited`.
- Print each container's name and IP address with a --format template.
- Copy a file out of a running nginx container with docker cp.
- Watch `docker stats --no-stream` while a container is busy.
- Run `docker volume prune` and read what it removed before confirming.

## Quiz

1. docker system df shows Local Volumes at 510MB, 100% reclaimable. What does that mean?
   - Docker is broken
   - **No container uses those volumes; docker volume prune would delete them** (answer)
   - The volumes are backed up
   - They are images
   Why: Usually anonymous volumes left by containers removed without -v. Check nothing you need is in them first: a deleted volume is gone.

2. Which prune removes only anonymous, unused volumes by default?
   - docker system prune -a
   - **docker volume prune (add --all to include unused named volumes)** (answer)
   - docker image prune
   - docker rm -v
   Why: Named volumes such as shop_pgdata are kept unless you add --all, because they usually hold data someone wants.

3. How do you print just the IP address of a container?
   - docker ip web
   - **docker inspect web --format with a Go template over .NetworkSettings.Networks** (answer)
   - docker ps --ip
   - cat /etc/hosts
   Why: inspect returns the full JSON; --format picks fields out of it, and it works the same for images, volumes and networks.

4. What does docker image prune remove without -a?
   - All images
   - **Only dangling images: untagged layers left behind when a tag moved to a new build** (answer)
   - Images older than a week
   - Running images
   Why: -a also removes every image no container uses, which means the next run downloads it again.

5. Why prefer docker container ls over docker ps in scripts you share?
   - It is faster
   - **Both work; the object-verb form (container ls, image rm, volume prune) is consistent and easier to read** (answer)
   - docker ps is deprecated and removed
   - Only container ls supports --format
   Why: The short forms remain fully supported. Pick one style and stay consistent.

## Resources

- [Docker Docs: Docker CLI reference](https://docs.docker.com/reference/cli/docker/) (Docker Docs)
- [Docker Docs: format command and log output](https://docs.docker.com/engine/cli/formatting/) (Docker Docs)
- [Docker Docs: prune unused Docker objects](https://docs.docker.com/engine/manage-resources/pruning/) (Docker Docs)
