Use host networking and additional networks in docker compose

phzonta picture phzonta · Mar 21, 2016 · Viewed 12.7k times · Source

I'm trying to set up a dev environment for my project.

I have a container (ms1) which should be put in his own network ("services" in my case), and a container (apigateway) which should access that network while exposing an http port to the host's network.

Ideally my docker compose file would look like this:

version: '2'
services:
    ms1:
        expose:
            - "13010"
        networks:
            services:
                aliases:
                    - ms1
   apigateway:
        networks:
            services:
                aliases:
                    - api
        network_mode: "host"
networks:
    services:

docker-compose doesn't allow to use network_mode and networks at the same time.

Do I have other alternatives?

At the moment I'm using this:

   apigateway:
        networks:
            services:
                aliases:
                    - api
        ports:
            - "127.0.0.1:10000:13010"

and then apigateway container listens on 0.0.0.0:13010. It works but it is slow and it freezes if the host's internet connection goes down.

Also, I'm planning on using vagrant in the future upon docker, does it allow to solve in a clean way?

Answer

tne picture tne · Nov 27, 2017

expose in docker-compose does not publish the port on the host. Since you probably don't need service linking anymore (instead you should rely on Docker networks as you do already), the option has limited value in general and seems to provide no value at all to you in your scenario.

I suspect you've come to using it by mistake and after realizing that it didn't seem to have any effect by itself, stumbled upon the fact that using the host network driver would "make it work". This had nothing to do with the expose property, mind you. It's just that the host network driver lets contained processes bind to the host network interface directly. Thanks to this, you could reach the API gateway process from the outside. You could remove the expose property and it would still work.

If this is the only reason why you picked the host network driver, then you've fallen victim of the X-Y problem:

(tl;dr) You should never need to use the host network driver in normal situations, the default bridge network driver works just fine. What you're looking for is the ports property, not expose. This sets up the appropriate port forwarding behind the scenes.