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)
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.
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:For example, on my system:
And once you have the PID, use that as the argument to the target (
-t
) option ofnsenter
. For example, to runnetstat
inside the container network namespace:Notice that this worked even though the container does not have
netstat
installed:(
nsenter
is part of theutil-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