In this step, you will learn how to use Go templates to format the output of the docker inspect
command. This allows you to extract specific pieces of information from the detailed JSON output and display them in a custom format.
First, let's run a container that stays running.
docker run -d --name my-templated-container ubuntu sleep infinity
Now, let's inspect this container and use a Go template to display only its IP address. The IP address is located within the NetworkSettings.IPAddress
field of the inspect output.
docker inspect --format '{{.NetworkSettings.IPAddress}}' my-templated-container
In this command:
--format '{{.NetworkSettings.IPAddress}}'
: This flag specifies the format using a Go template.
{{...}}
: These double curly braces denote an action in the Go template.
.
: This represents the root object being inspected (the container).
NetworkSettings
: This accesses the NetworkSettings
field within the root object.
IPAddress
: This accesses the IPAddress
field within the NetworkSettings
object.
The output of this command will be just the IP address of the container.
You can use Go templates to extract various pieces of information. For example, to get the container's name and ID:
docker inspect --format 'Name: {{.Name}}, ID: {{.Id}}' my-templated-container
This will output something like Name: /my-templated-container, ID: <container_id>
.
Go templates offer powerful formatting capabilities, including conditional statements, loops, and functions. However, for this basic example, we are just accessing fields.
After inspecting, stop and remove the container.
docker stop my-templated-container
docker rm my-templated-container