Search code examples
dockerubuntukuberneteskubectl

Why Is HostPort Not Showing in The Outputs of Netstat from Host Machine


I used the kubectl with yaml files to create target pod, and found the process in the pod is listening target port as expected.

To my surprise, the Port is not seen in the outputs of netstat -tunlp or netstat -alp or netstat -an from host machine. But it works if I try telnet localhost targetPort!!!

Why this happens?? Can anybody explain this?


Solution

  • This is because of docker. By default docker does not add container network namespaces to the linux runtime data (/var/run mounted as a tmpfs from /run) which is what you see when you run the ip netns command.

    To view the network namespaces you need to use nsenter.

    1. Get the container id.
    docker ps
    
    1. Get the container process id.
    docker inspect --format '{{ .State.Pid }}' <<container-id>>
    
    1. Now use the nsenter to display the pods network spaces. Advantage of using nsenter over docker exec is that nsenter will enable you to execute all tools or commands available on the node inside the pod where as docker exec will allow only limited or restricted commands.
    nsenter -t <<container pid>> -n netstat -tunlp