How to use the host network, and any other user-defined network together in Docker-Compose?

孤街醉人 提交于 2019-11-29 02:48:46

问题


I want to connect two Docker containers, defined in a Docker-Compose file to each other (app and db). And one of them (app) should also be connected to the host network.

The containers should be connected to a common user-defined network (appnet or default) to use the embedded DNS capabilities from docker networking.

app needs also to be directly connected to the host network to receive ethernet broadcasts (network layer 2) in the physical network of the docker host.

If I use both directives network_mode: host and networks in compose together, I get the following error.

ERROR: 'network_mode' and 'networks' cannot be combined

So I have to do this with networks only!?

version: "3.3"

services:

  app:
    build: .
    image: app
    container_name: app
    environment:
      - MONGODB_HOST=db
    depends_on:
      - db
    networks:
      - appnet
      - hostnet

  db:
    image: mongo:latest
    container_name: db
    networks:
      - appnet

networks:
  appnet:
  hostnet:
    external:
      name: host

The foregoing compose file produces a error. ERROR: for app network-scoped alias is supported only for containers in user defined networks

If I use the network name host in the service without defining it in networks (because it already exists), it says. ERROR: Service "app" uses an undefined network "host"

How to use the host network, and any other user-defined network (or the default) together in Docker-Compose?

I'm using Docker version 17.11.0-ce-rc3, build 5b4af4f and docker-compose version 1.17.1, build 6d101fb


回答1:


TL;DR you can't. The host networking turns off the docker network namespace for that container. You can't have it both on and off at the same time.

Instead, connect to your database with a published port, or a unix socket that you can share as a volume. E.g. here's how to publish the port:

version: "3.3"

services:

  app:
    build: .
    image: app
    container_name: app
    environment:
      - MONGODB_HOST=127.0.0.1

  db:
    image: mongo:latest
    container_name: db
    ports:
      - 127.0.0.1:27017:27017



回答2:


To use host network, you don't need to define it. Just use "ports" keyword to define, which port(s) from service you want to expose in host network.




回答3:


Since Docker 18.03+ one can use host.docker.internal to access your host from within your containers. No need to add host network or mix it with the user defined networks.

Source: Docker Tip #65: Get Your Docker Host's IP Address from in a Container



来源:https://stackoverflow.com/questions/47303141/how-to-use-the-host-network-and-any-other-user-defined-network-together-in-dock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!