ruebenramirez / blog

My blog
http://blog.ruebenramirez.com/
7 stars 0 forks source link

grab values from docker inspect #397

Open ruebenramirez opened 7 years ago

ruebenramirez commented 7 years ago

https://blog.newrelic.com/2016/08/24/docker-health-check-instruction/

In this article there's a reference to a json formatted output from the docker inspect command:

docker inspect --format='{{json .State.Health}}' your-container-name

A few weeks ago, I had come up with this monstosity:

DYNAMIC_PORT=$(shell sudo docker inspect $(TMP_IMAGE_NAME) | grep 'HostPort' | grep -v \'\' | awk '{print $2}' | egrep -o '[0-9]+')

Which can simply be replaced with a json formatted string lookup...or so I thought.

I spun up a redis container with a dynamic port mapping via:

docker run -d -p 6379 --name redis redis

through docker inspect, I found that the network settings came back as:

$ docker inspect redis
[
    {
        "Id": "5a5afdd4e7f83840e1f93d13c81a92170b5375a29ba2d05a10508c308c6ee423",
        "Created": "2017-04-22T06:42:47.99321031Z",
......
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "edf91c07556cc384f81292fdbf2d1c5331f2b29554400cc5e2d7dd201386d85c",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "6379/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "32769"
                    }
                ]
            },
......
            }
        }
    }
]

so I expected that I could grab the 32769 port that was randomly assigned to the container with:

docker inspect --format '{{json .NetworkSettings.Ports.6379/tcp.HostPort}}' redis          
Template parsing error: template: :1: unexpected ".6379" in operand

but no dice...

We can get almost all the way there though:

docker inspect --format '{{json .NetworkSettings.Ports}}' redis                  
{"6379/tcp":[{"HostIp":"0.0.0.0","HostPort":"32769"}]}