How to Become a Docker CLI Power User With “–format” and Output Templates

Estimated read time 6 min read

[ad_1]

Using the Docker CLI to list and inspect the resources on your system often produces verbose output that can hide important details. Docker supports Go’s templating syntax in conjunction with the --format flag to give you control over what’s displayed.

Learning how to use templates can turn you into a Docker CLI power user. They let you efficiently select and transform command outputs to create the views you need. This results in a more productive CLI experience and less time spent scanning long console lines.

Which Commands Support “–format”?

The --format flag is supported by most commonly used docker commands. You can use it with docker inspect and commands that produce lists of items, such as docker ps, docker images, and docker volumes.

When you include the --format flag, Docker will send the command’s output through the Go template string you provide. You can use the templating features provided by Go to consume placeholders set by Docker. These give you access to the data fetched by the CLI.

A Basic Example

Running docker inspect on a container displays a lengthy JSON object that usually overflows your terminal window. Using --format, you can pull out the specific parts of the data that you’re interested in. Here’s an example that shows the container’s status, PID, and start time:

~$ docker inspect 94a8d1315315 --format '{{.State.Status}} (PID: {{.State.Pid}}) {{.State.StartedAt}}'
running (PID: 1488278) 2022-03-22T20:45:58.614115689Z

It’s much easier to spot the target values using a template than when manually trawling through the raw JSON.

Accessing Output Values

Dynamic parts of your template are wrapped in double curly parentheses. You can reference values within the Docker command’s output using the {{.Field}} syntax. Field should be the name of a property in the JSON representation of that output. Nested fields are selected using chained syntax that’s similar to property accesses in JavaScript, .Field.NestedValue.

You can work out which fields are available by viewing the command’s raw output. docker inspect displays JSON by default; this can be directly mapped to the template syntax’s placeholders. For other commands such as ps and images, you can retrieve the underlying JSON structure using a special template:

docker ps --format '{{json .}}`

The json function displays the raw JSON version of the data you supply.

Simple Transformations

Transformation functions offer a convenient way to manipulate values. upper and lower convert strings to uppercase and lowercase respectively. You can apply title casing to a string with title. Functions are inserted into the template ahead of the value they operate on:

~$ docker inspect 94a8d1315315 --format '{{upper .State.Status}} (PID: {{.State.Pid}})'
RUNNING (PID: 1488278)

If you want to add a newline character between values, use the println function:

~$ docker inspect 94a8d1315315 --format '{{.State.Status}} {{.State.Pid}}{{println}}{{.State.StartedAt}}'
running 1488278
2022-03-22T20:45:58.614115689Z

Working With Arrays

The template syntax has integrated support for iterating the elements of an array. The range function loops over an array’s values and sets the . variable to each one:

~$ docker inspect 94a8d1315315 --format '{{range .Mounts}}{{println .Destination}}{{end}}'
/config
/data

You can combine array elements together with the join function:

~$ docker inspect 94a8d1315315 --format '{{join .Config.Cmd " "}}'
caddy run --config /etc/caddy/Caddyfile --adapter caddyfile

This creates a string that incorporates each value in the array. The elements are joined together with the text specified as the argument’s second parameter.

Tabulating Output

Many Docker commands default to showing data in a human-readable table layout. You can create your own tables using the special table template component.

Use t characters to separate data  fields into table columns. The template will be executed for each of the items included in the Docker CLI command’s output. Table columns are automatically sized to match the length of their content.

~$ docker images --format 'table {{.ID}}t{{.Tag}}t{{.Size}}'
IMAGE ID       TAG          SIZE
ede20431e41f   caddy        40.4MB
e5179b119094   <none>       40.4MB

Docker automatically includes appropriate column headers for the fields in your template.

Conditional Formatting

Templates support conditional “if” statements too. You can dynamically customize the command’s output by displaying a different value based on a condition:

~$ docker ps --format '{{.ID}} {{if eq .State "running"}}Alive{{else}}Not Running{{end}}'
94a8d1315315 Alive

This template displays either Alive or Not Running depending on whether each container’s State field is set to running. The if block is followed by the value that’s shown when the condition matches. An optional else block can be chained afterwards. The condition is terminated by the {{end}} keyword.

Go templates understand several comparison operators. The eq shown above checks whether the first value is equal to the second. The following options are available in addition:

  • ne – A “not equal to” comparison.
  • lt – A “less than” (<) comparison).
  • lte – A “less than or equal to” (<=) comparison).
  • gt – A “greater than” (>) comparison).
  • gte – A “greater than or equal to” (>=) comparison).

There are and, or, and not keywords too for chaining conditions together into complex expressions.

Advanced Formatting Using Jq

The --format flag is primarily used to create human-readable output strings. If you’re more comfortable inspecting raw JSON, you can use other tools like jq to manipulate Docker’s output more directly. This can be useful when you want to create more advanced queries than Go templates alone can provide.

docker inspect produces JSON by default so its output can be piped straight into jq:

~$ docker inspect 94a8d1315315 | jq .[0].Config.Cmd
[
  "caddy",
  "run",
  "--config",
  "/etc/caddy/Caddyfile",
  "--adapter",
  "caddyfile"
]

The output from other commands should be converted to its raw JSON with --format before it’s passed to jq:

~$ docker images --format '{{json .}}' | jq .Size
"968MB"
"946MB"
"40.1MB"

Jq provides its own syntax for selecting, manipulating, and formatting JSON data. The fundamentals are similar to Go’s template placeholders. Fields are referenced using the .Field syntax. There’s support for selecting array elements using the .[index] notation.

Conclusion

The Docker CLI becomes more powerful when you can selectively view and manipulate output data. Go templates with the --format flag provide a way to create customized interfaces that streamline the management of your containers.

In some situations, --format still might not offer the power and flexibility you need. Piping Docker commands to external tools like jq provides another way to rapidly interrogate your installation and surface its data within other systems.



[ad_2]

Source link

You May Also Like

More From Author