问题描述
我想在正在运行的 docker 容器中执行 netstat 以查看打开的 TCP 套接字及其状态.但是,在我的某些 docker 容器上,netstat 不可用.有没有办法在不使用 netstat 的情况下通过某些 docker API 获取打开的套接字(及其状态,以及它们连接到哪些 IP 地址(如果有)?(顺便说一句,我的容器使用 docker-proxy - 也就是说,没有直接桥接)
I would like to execute netstat inside a running docker container to see open TCP sockets and their statuses. But, on some of my docker containers, netstat is not available. Is there any way to get open sockets (and their statuses, and which IP addresses they are connected to if any) without using netstat, via some docker API? (BTW, my container uses docker-proxy - that is, not directly bridged)
我想我可以直接查看/proc 文件系统,但到那时,我还不如将 docker cp netstat 放入容器并执行它.我想知道 docker 是否可以为此提供任何设施.
I guess I could look at /proc file system directly, but at that point, I might as well docker cp netstat into the container and execute it. I was wondering if there was any facility that docker might provide for this.
推荐答案
您可以使用 nsenter
命令在 Docker 容器的网络命名空间内的主机上运行命令.只需获取 Docker 容器的 PID:
You can use the nsenter
command to run a command on your host inside the network namespace of the Docker container. Just get the PID of your Docker container:
docker inspect -f '{{.State.Pid}}' container_name_or_id
例如,在我的系统上:
$ docker inspect -f '{{.State.Pid}}' c70b53d98466
15652
一旦你有了 PID,把它用作 nsenter
的目标 (-t
) 选项的参数.例如,要在容器网络命名空间内运行 netstat
:
And once you have the PID, use that as the argument to the target (-t
) option of nsenter
. For example, to run netstat
inside the container network namespace:
$ sudo nsenter -t 15652 -n netstat
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
请注意,即使容器没有安装 netstat
,这也能正常工作:
Notice that this worked even though the container does not have netstat
installed:
$ docker exec -it c70b53d98466 netstat
rpc error: code = 13 desc = invalid header field value "oci runtime error: exec failed: container_linux.go:247: starting container process caused "exec: \"netstat\": executable file not found in $PATH"
"
(nsenter
是 util-linux
包的一部分)
(nsenter
is part of the util-linux
package)
这篇关于Docker:有什么方法可以列出正在运行的 Docker 容器中打开的套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!