Docker: 有什么方法可以列出正在运行的 Docker 容器中打开的套接字?

我希望在一个正在运行的 docker 容器中执行 netstat,以查看打开的 TCP 套接字及其状态。但是,在我的一些 Docker 容器上,netstat 不可用。有没有办法不使用 netstat,通过一些 docker API 来获得打开的套接字(及其状态,以及它们连接到的 IP 地址(如果有的话) ?(顺便说一下,我的容器使用的是 docker 代理,也就是说,不是直接桥接的)

我想我可以直接查看/proc 文件系统,但是在这一点上,我不妨将 cp netstat 停靠到容器中并执行它。我想知道 Docker 有没有什么设施可以提供这个。

97584 次浏览

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

For example, on my system:

$ docker inspect -f '\{\{.State.Pid}}' c70b53d98466
15652

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

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\"\n"

(nsenter is part of the util-linux package)

The two commands from @larsks answer merged into one-liner - no need to copy-paste the PID(s) (just replace container_name_or_id):

sudo nsenter -t $(docker inspect -f '\{\{.State.Pid}}' container_name_or_id) -n netstat

server:docker container ls

CONTAINER ID    IMAGE              COMMAND                  CREATED          STATUS           PORTS       NAMES


80acfa804b59    admirito/gsad:10   "docker-entrypoint.s…"   18 minutes ago   Up 10 minutes    80/tcp      gvmcontainers_gsad_1

If you have iproute2 package installed, you can use

sudo nsenter -t $(docker inspect -f '\{\{.State.Pid}}' container_name_or_id) -n ss

or

sudo nsenter -t $(docker inspect -f '\{\{.State.Pid}}' container_name_or_id) -n ss -ltu

It will show TCP and UDP

If you want them all (all containers) try this.

$ for i in `docker ps -q` ; do sudo nsenter -t $(docker inspect -f '\{\{.State.Pid}}' $i) -n netstat ; done

I tried the other solutions and it didn't work for me by my colleague gave me this solution. Thought I would mention it here for others like me and for me to refer to later lol.

docker exec -it [container name] bash

grep -v “rem_address” /proc/net/tcp

docker inspect <container_id>

  • Look for "ExposedPorts" in "Config"