JSON data from Docker Images
I was trying to get some structured information from docker images, hoping to replace some ugly Sed and AWK trickery. I could have used the docker-py library. Instead I chose to use the poorly documented --format option to docker images (and some other Docker CLI commands). Adrian Mouat gives some useful starting points at Docker Inspect Template Magic and notes that formatting is built around Go templates.
I quickly figured out that this format would meet my immediate need.
sudo docker images --format '{{.Repository}}:{{.Tag}}' \ | grep $IMAGE_NAME \ | grep -v latest \ | head -1
That’s fine, but I still had no idea what other possible names could be used in the format template. While getting there, I learned that Curl can be used with a Unix socket to talk to the Docker daemon.
sudo curl --unix-socket /var/run/docker.sock \ http://localhost/images/json | python -m json.tool
This produces a prettyprinted list of all the Docker images. However, the names are not the same as those that can be used in the format template.
The actual field names that can be used in the format template can be found in cli/command/formatter/image.go. They include:
- .ID — 12-char SHA aka Image ID
- .Repository — aka image name
- .Tag
- .Digest — unsure
- .CreatedSince — e.g., “4 weeks”
- .CreatedAt — date
- .Size
- .Containers
- .VirtualSize
- .SharedSize
- .UniqueSize