Remove dynamically assigned ports from docker inspect

Asked 2 years ago, Updated 2 years ago, 91 views

When I dynamically mapped 80 ports in a container, I tried to get the port mapped to the host OS only by using the docker inspect command, but no matter how hard I tried, it didn't work.
I was hoping that someone familiar with the Golang template would give me some advice.

The following is an attempt.

Dynamically assign 80 ports in the container to ports in the host OS.

$docker run-p 80-d-it --name test ubuntu:18.04
$ docker ps | grep test
9 dda4ab9 febfubuntu:18.04"/bin/bash"23 seconds ago Up 22 seconds 0.0.0.0:32770->80/tcp test
$ 

docker inspect provides information with 80/tcp mapped to 32770, as follows:

$docker inspect test | jq'.[0].NetworkSettings.Ports'
{
  "80/tcp": [
    {
      "HostIp": "0.0.0.0",
      "HostPort": "32770"
    }
  ]
}

I can get it below, but I wanted to specify 80 ports for the container when multiple ports are assigned.

$docker inspect --format='{range.NetworkSettings.Ports}}{{range.}}{{.HostPort}}}{{end}}{{end}}' test
32770
$

I thought about specifying "80/tcp", but it didn't work as below.

$docker inspect --format='{range.NetworkSettings.Ports}}{{range.80/tcp}}{{.HostPort}}}{{end}}{{end}}' test
Template parsing error: template::1: unexpected"/"in operand
$ 

I think it's an escape character problem, but it didn't work even if I surrounded it with "\" or "

go docker

2022-09-30 21:33

1 Answers

80/tcpHow about this syntax when filtering containers with ports?

 docker inspect test --format='{{(index.NetworkSettings.Ports "80/tcp")0)}'

-->map [HostIp: 0.0.0.0 HostPort:5401]

If you want to see only the ports on the container,

 docker inspect test --format='{{(index.NetworkSettings.Ports"80/tcp")0).HostPort}}'

-->5401

Or it might be simpler to use the docker port command.

 docker port test | grep '80/tcp'

-->80/tcp->0.0.0:5401


2022-09-30 21:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.