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.

  • Docker image seemingly having missing layers
  • How to deploy mongoDB Docker image to Elastic Beanstalk?
  • What is the difference between docker Swarm and Swarm mode?
  • Can docker port forward to a unix file socket on the host container?
  • Automatic push to a Docker private registry
  • How to preserve apt-cache archive directory when using docker / host volumes
  • 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.

  • CircleCI: Best way to verify if docker containers are responding via HTTP
  • docker container internal server applications
  • Different development environments with docker
  • Strange tables in oracle xe
  • docker build: Returned a non-zero code: 2
  • Docker-Compose Restart Policy
  • 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.