Docker Swarm Inspect 从每个节点获取内部 IP

Docker Swarm Inspect to get internal IP from every node

我正在尝试从全球部署在多个 swarm 节点上的服务获取内部(容器级别)IP。

与此类似。

docker node ls -q | xargs docker node inspect -f '{{ .ID }} [{{ .Description.Hostname }}]: {{ .Spec.Labels }} {{ .Status.Addr  }}'

这 returns 每个节点的主机 IP 和这些主机上的标签。

我开始使用以下方法跨所有节点检索特定服务的所有 ID:

docker service ps [swarm_task] -q

然后像这样检查每一个:

docker service ps [swarm_task] -q | xargs docker inspect -f '{{ .NetworksAttachments.Addresses }}'

但 IP 地址的格式不同,我收到此错误:

Template parsing error: template: :1:23: executing "" at <.NetworksAttachments...>: can't evaluate field Addresses in type interface {}

检查中的格式是这样的:

"Addresses": [
                "10.0.0.187/24"
            ]

docker --format 的参数是一个标准的 go text/template 表达式。

由于 NetworksAttachments 是一个数组,您可能需要迭代 NetworksAttachments 以获得有效输出。

range 关键字的设计目的是:

$ docker service ps [swarm service name] -q --filter "desired-state=Running" \
| xargs docker inspect --format '{{range .NetworksAttachments}}{{.Addresses}}{{end}}'

我的 docker 引擎输出是:

[10.x.x.y/16]
[10.x.x.z/16]

我将 --filter "desired-state=Running" 添加到 docker service ps 以仅关注 运行 个容器。

可以参考Gotext/template文档:

{{range pipeline}} T1 {{end}}

The value of the pipeline must be an array, slice, map, or channel. If the value of the pipeline has length zero, nothing is output; otherwise, dot is set to the successive elements of the array, slice, or map and T1 is executed. If the value is a map and the keys are of basic type with a defined order ("comparable"), the elements will be visited in sorted key order.