Sub topic 4
Filtering and Formatting the Output of docker ps
This chapter assumes you can run docker ps and docker ps -a, and that you know a container's name and ID can both identify it. It also assumes you have a few containers to look at. Start some with these commands:
docker run -d --name web --label env=staging nginx:alpine
docker run -d --name cache --label env=prod redis:alpine
docker run --name ok alpine true
docker run --name bad alpine sh -c "exit 3"After this, web and cache are running, and ok and bad are stopped. Clean them up when you finish with docker rm -f web cache ok bad.
Why filter and format
On a busy host, docker ps -a prints dozens of rows with wide columns that wrap in a narrow terminal. Two flags help:
--filterchooses which containers appear.--formatchooses which fields appear and how they are laid out.
You can also use both flags in scripts, where you need predictable output that another command can read.
Filtering with --filter
A filter is a key=value pair. Pass it with --filter (or -f), and repeat the flag for more filters. Quote the pair so the shell does not interpret special characters.
docker ps -a --filter "status=exited"Include -a in your filter commands. Without it, docker ps lists only running containers. Add -a whenever a filter is meant to find stopped ones.
Common filter keys
| Key | Matches | Example |
|---|---|---|
| `name` | Container name, as a substring or regular expression | `name=web` |
| `id` | Container ID prefix | `id=3f4a` |
| `status` | Lifecycle state: `created`, `running`, `paused`, `restarting`, `removing`, `exited`, `dead` | `status=exited` |
| `exited` | Exit code of a stopped container | `exited=3` |
| `label` | Presence of a label, or a label with a given value | `label=env=prod` |
| `ancestor` | Containers created from an image (or image descendant) | `ancestor=nginx:alpine` |
| `before` / `since` | Containers created before or after a given container | `since=web` |
| `network` | Containers attached to a network | `network=bridge` |
| `volume` | Containers that mount a volume or path | `volume=/data` |
| `publish` / `expose` | Containers publishing or exposing a port | `publish=80` |
| `health` | Health check result: `starting`, `healthy`, `unhealthy`, `none` | `health=unhealthy` |
Here are a few of them in use:
docker ps -a --filter "exited=3"
docker ps --filter "label=env=prod"
docker ps -a --filter "ancestor=alpine"
docker ps --filter "health=unhealthy"With the sample containers, exited=3 returns only bad, because it exited with code 3. This is a quick way to find containers that failed, since exited=0 means a clean exit and any other code usually means an error.
Combining filters
Docker applies two rules:
- Filters with different keys are combined with AND. A container must match all of them.
- Repeating the same key is combined with OR. A container must match at least one value.
docker ps -a --filter "status=exited" --filter "ancestor=alpine"
docker ps -a --filter "status=running" --filter "status=exited"The first command lists exited containers that were created from alpine. The second lists containers that are running or exited. The second form is useful for excluding created and paused containers without listing everything.
The following diagram shows how Docker evaluates these rules for each container.
Name matching is a substring match
name=web matches web, web-2, and my-website. The value is treated as a regular expression, so you can anchor it:
docker ps -a --filter "name=^web$"
docker ps -a --filter "name=^web-"The first command matches only a container named exactly web. The second matches names that start with web-. If a filter returns more than you expected, a substring match is the most common cause.
Names also carry a leading slash internally, which can matter for linked containers. For ordinary use you can ignore this.
status versus exited
These two keys are easy to confuse:
status=exitedselects every container in the exited state, whatever its exit code.exited=Nselects exited containers whose exit code is exactlyN.
Use status to find stopped containers in general. Use exited to find containers that stopped for a particular reason. For example, code 137 usually means the process was killed by SIGKILL, which Docker sends with docker kill or after a stop grace period runs out.
Formatting with --format
By default, docker ps prints a fixed table: ID, image, command, creation time, status, ports, and names. The --format flag replaces this with a Go template. Placeholders go in double braces, and each one names a field.
docker ps -a --format "{{.Names}} is {{.State}}"Output for the sample containers looks like this:
bad is exited
ok is exited
cache is running
web is runningAvailable fields
| Placeholder | Meaning |
|---|---|
| `.ID` | Short container ID |
| `.Names` | Container name |
| `.Image` | Image name |
| `.Command` | Command the container runs, truncated |
| `.CreatedAt` | Creation timestamp |
| `.RunningFor` | Time since creation, in words, such as "3 minutes ago" |
| `.Ports` | Published ports |
| `.State` | One word state, such as `running` or `exited` |
| `.Status` | Longer text, such as `Up 3 minutes` or `Exited (3) 2 minutes ago` |
| `.Size` | Writable layer size (only filled in with `-s`) |
| `.Labels` | All labels, comma separated |
| `.Label "key"` | The value of one label |
| `.Mounts` | Volume or bind mount names |
| `.Networks` | Attached network names |
.State and .Status differ in a useful way. .State is a single word that is safe to compare in a script. .Status is human-readable text and its wording can change, so do not parse it. The exit code appears in .Status as Exited (3), but for programmatic use, prefer the exited filter.
Using a table layout
Starting the template with table adds a header row and aligns columns. Use \t to separate columns.
docker ps -a --filter "status=exited" --format "table {{.Names}}\t{{.Status}}\t{{.Image}}"NAMES STATUS IMAGE
bad Exited (3) 2 minutes ago alpine
ok Exited (0) 2 minutes ago alpineWithout table, Docker prints exactly what the template says and nothing else. That is what you want when another program reads the output, because there is no header line to skip.
Reading a single label
Use .Label with the key to print one value:
docker ps --format "{{.Names}}\t{{.Label \"env\"}}"Containers without that label print an empty value. Combine this with a label filter when you need a clean list.
JSON output
For tools that parse structured data, {{json .}} prints each container as one JSON object per line.
docker ps -a --format "{{json .}}"Recent Docker versions also accept --format json as a shortcut. The {{json .}} form works on older versions too. The JSON output carries every field, so a tool such as jq can pick out what it needs:
docker ps -a --format "{{json .}}" | jq -r '.Names + " " + .State'This example requires jq to be installed.
Setting a default format
If you always use the same layout, put it in ~/.docker/config.json under the psFormat key:
{
"psFormat": "table {{.Names}}\t{{.Image}}\t{{.Status}}"
}After this, plain docker ps uses your layout. An explicit --format on the command line still takes priority, so scripts can ignore your personal default. Because a default can change what docker ps prints, check this file first when a colleague's output looks different from yours.
Quiet output and truncation
Two small flags change output in ways that matter for scripts.
-q(--quiet) prints only container IDs, one per line. It works together with filters.--no-truncprints full-length IDs and complete commands instead of shortened ones.
docker ps -aq --filter "status=exited"
docker ps -a --no-trunc --format "{{.ID}} {{.Names}}"The -q output is designed to be passed to other commands. For example, you could remove every exited container like this:
docker rm $(docker ps -aq --filter "status=exited")Run the docker ps part alone first and read the list. The docker rm command deletes without asking, and a filter that matches more than you intended removes more. Bulk removal and docker container prune are covered in a later chapter.
If the filter matches nothing, $(...) expands to an empty string and docker rm prints a usage error. Nothing is deleted in that case, but the error can be confusing in a script.
Two related flags are worth knowing. -n 5 shows the five most recently created containers (including stopped ones), and -l shows only the latest one. -s adds a size column.
Common mistakes
- Forgetting
-a.docker ps --filter "status=exited"without-acan come back empty. Add-awhen looking for stopped containers. - Unquoted filters. In some shells, characters such as
^and$inname=^web$are interpreted before Docker sees them. Wrap each filter in quotes. - Expecting OR across different keys. Two different keys are always AND. To get an OR across keys, run two commands.
- Treating
.Statusas stable. Its text is for humans. Use.State, or filter bystatusandexited. - Shell differences. The examples use bash quoting. In Windows PowerShell and
cmd, quoting of{{ }}and\tdiffers, so adjust the quotes and test with a simple template first.
Exercises
Exercise
You run docker ps -a --filter "status=exited" --filter "status=created". Which containers are listed, and why?
Show answer
Containers that are either exited or created. The same key repeated is combined with OR, so a container only needs to match one of the two values.
Exercise
Write one command that prints only the names of stopped containers that exited with a non-zero code of 1, one per line, with no header.
Show answer
docker ps -a --filter "exited=1" --format "{{.Names}}" (The exited filter selects the exit code, and a template without table prints no header.)
Exercise
Why is name=web a risky filter to feed into docker rm, and how do you make it match only a container named exactly web?
Show answer
The name filter is a substring regular expression, so it also matches names such as web-2 or my-website. Anchor it with --filter "name=^web$".