美文网首页
docker inspect访问数组和map数据

docker inspect访问数组和map数据

作者: CodingCode | 来源:发表于2021-10-26 02:34 被阅读0次

举个例子来说,假设:
(删掉大部分不需要的内容)

$ docker inspect <container>
[
  {
    "HostConfig": {
      "PortBindings": {
        "8000/tcp": [
          {
            "HostIp": "192.168.1.167",
            "HostPort": "8000"
          }
        ],
        "8080/tcp": [
          {
            "HostIp": "192.168.1.167",
            "HostPort": "8080"
          }
        ]
      }
    },
    "Config": {
      "Env": [
        "HOME=/home/username",
        "DOCKER_HOST=tcp://172.18.0.1:2376",
        "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
        "LD_LIBRARY_PATH=/usr/lib64:/lib64"
      ]
    }
  }
]
  1. 访问数组

.Config.Env是一个数组。

$ docker inspect -f '{{.Config.Env}}' <container>
[HOME=/home/username DOCKER_HOST=tcp://172.18.0.1:2376 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin LD_LIBRARY_PATH=/usr/lib64:/lib64]
  1. 按下标取
$ docker inspect -f '{{index .Config.Env 0}}' <container>
HOME=/home/username

$ docker inspect -f '{{index .Config.Env 1}}' <container>
DOCKER_HOST=tcp://172.18.0.1:2376

$ docker inspect -f '{{index .Config.Env 2}}' <container>
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 

$ docker inspect -f '{{index .Config.Env 5}}' <container>

Template parsing error: template: :1:2: executing "" at <index .Config.Env 5>: error calling index: index out of range: 5

对于数组估计也只能按下标取,没别的办法了。

  1. 遍历
$ docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' <container>
HOME=/home/username
DOCKER_HOST=tcp://172.18.0.1:2376 
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 
LD_LIBRARY_PATH=/usr/lib64:/lib64

然后你可以过滤需要的环境变量值

$ docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' <container> | grep "^DOCKER_HOST"
DOCKER_HOST=tcp://172.18.0.1:2376
  1. 访问map
$ docker inspect --format '{{ .HostConfig.PortBindings }}' <container>
map[8000/tcp:[{192.168.1.167 8000}] 8080/tcp:[{192.168.1.167 8080}]]
  1. 按下标(key)访问
$ docker inspect --format '{{ index .HostConfig.PortBindings "8000/tcp"}}' <container>
[map[HostIp:192.168.1.167 HostPort:8000]]

$ docker inspect --format '{{ index .HostConfig.PortBindings "8080/tcp"}}' <container>
[map[HostIp:192.168.1.167 HostPort:8080]]
  1. 遍历
$ docker inspect --format='{{range $p, $conf := .HostConfig.PortBindings}}{{println $p "=>" $conf}}{{end}}' <container>
8000/tcp => [{192.168.1.167 8000}]
8080/tcp => [{192.168.1.167 8080}]

$ docker inspect --format='{{range $p, $conf := .HostConfig.PortBindings}}{{println $p "=>" (index $conf 0)}}{{end}}' <container>
8000/tcp => {192.168.1.167 8000}
8080/tcp => {192.168.1.167 8080}

$ docker inspect --format='{{range $p, $conf := .HostConfig.PortBindings}}{{println $p "=>" (index $conf 0).HostPort}}{{end}}' <container>
8000/tcp => 8000
8080/tcp => 8080

相关文章

网友评论

      本文标题:docker inspect访问数组和map数据

      本文链接:https://www.haomeiwen.com/subject/bllealtx.html