Customizing Docker command output using go templates

Modifying Docker command output

Ever wanted to process the output of your favorite Docker command in a shell script?
E.g. $ docker images

1
2
3
4
5
docker@default:~$ docker images
REPOSITORY             TAG         IMAGE ID         CREATED         SIZE  
portainer/portainer    latest      19d07168491a     6 weeks ago     74.1MB  
abiosoft/caddy         latest      484501ab523c     6 weeks ago     69.7MB  
ubuntu                 latest      47b19964fb50     2 months ago    88.1MB

Of course, the old school way would be to slice away the header row, then awk or cut your way happily through the columns you need.

But dont! Docker command-line uses a powerful feature you should learn to use:
--format <go-template>

If I wanted a simple list of all images with tags in a single string, I could just do this:
--format ' {{.Repository }}:{{.Tag}}'

1
2
3
4
5
docker@default:~$ docker images --format ' {{.Repository }}:{{.Tag}}'
portainer/portainer:latest
abiosoft/caddy:latest
ubuntu:latest
vault:latest

And if I quickly wanted to pull/update some images, I could run:
docker images --format 'docker pull {{.Repository }}:{{.Tag}}' | sh


Hint: if you dont know which field names to use …

… or are too lazy reading Docker docs, just remember this simple format string:
--format='{{ json .}}'
It will show you all the available field names for this particular command in Json format!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
docker@default:~$ docker images --format='{{ json .}}' | jq 
 
{
  "Containers": "N/A",
  "CreatedAt": "2022-03-17 20:33:42 +0100 CET",
  "CreatedSince": "7 weeks ago",
  "Digest": "<none>",
  "ID": "35b24c90bf2a",
  "Repository": "klakegg/hugo",
  "SharedSize": "N/A",
  "Size": "665MB",
  "Tag": "0.95.0-ext-alpine",
  "UniqueSize": "N/A",
  "VirtualSize": "665.3MB"
}
updatedupdated2022-05-092022-05-09