In Docker, do I need to publish ports if I set network to host?

I was running into an issue today where I have a Dockerfile that EXPOSEs several ports and I wanted to run it with the --net=host flag.

However, all connections to the ports that the container was supposed to be listening on were refused.

  • Best practice re running bash for attaching to Docker running instance
  • Elastic Beanstalk, Docker and Continuous integration
  • Is there any efficient way get the left physical memory in docker?
  • Can (should) Docker be used for winforms applications?
  • OS Container vs Application Container
  • Do I need to rebuild image when parent image is updated?
  • Running docker inspect on the container I noticed this:

            "Ports": {
                "8000/tcp": {},
            }
    

    Growing exasperated I deleted the --net flag all together and went to the default bridge network. Surprise it works!

        "Ports": {
            "8000/tcp": null,
        }
    

    Except now it has this strange null setting. What is the difference here? Also, plot I’m running inside of a VM trying to communicate with another VM. Probably a million reasons this won’t work.

  • How to install docker daemon when resizing data center cluster size in Mesosphere?
  • Vagrant provision with Docker
  • How do I start a php server in the background as a daemon in a docker container
  • Dockerized Nginx upstream error serving separate Docker container with Flask/uWSGI app
  • Kubernetes: Unable to create repository
  • sha256sum error while building nvidia-docker on ppc64le
  • One Solution collect form web for “In Docker, do I need to publish ports if I set network to host?”

    Question

    Is the publish option needed when the network mode is host?

    Answer

    No, the host network stack is directly used by the container:

    'host': use the Docker host network stack. Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.

    Proof

    Start a container with netcat:

    user@host:~$ docker run -it --rm --net host nc:1.10-41
    root@container:/# nc -l -p 9999
    

    Back into the host:

    user@host:~$ nc 127.0.0.1 9999
    Sending a message for test <enter>
    

    The message will be displayed from the netcat command executed within the container.

    Monitoring

    A  netstat from the host will show the established connection:

    user@host:~$ netstat latuep |grep 9999
    tcp        0      0 localhost:38600         localhost:9999          ESTABLISHED
    tcp        0      0 localhost:9999          localhost:38600         ESTABLISHED
    

    As for your issue

    The error may stem from another configuration/network environment. Can VMs ping each other? Do they share the same LAN? Is a firewall set?

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.