如何在 Docker-Compose 中一起使用主机网络和任何其他用户定义的网络? [英] How to use the host network, and any other user-defined network together in Docker-Compose?

查看:124
本文介绍了如何在 Docker-Compose 中一起使用主机网络和任何其他用户定义的网络?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将在 Docker-Compose 文件中定义的两个 Docker 容器(appdb)相互连接起来.其中之一(app)也应该连接到host网络.

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.

容器应连接到一个通用的用户定义网络(appnetdefault)以使用来自 docker 网络的嵌入式 DNS 功能.

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

app 还需要直接连接到主机网络,才能在 docker 主机的物理网络中接收以太网广播(网络层 2).

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.

如果我同时使用 network_mode: hostnetworks 这两个指令,我会收到以下错误.

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

错误:network_mode"和networks"不能组合

所以我必须只使用 networks 来做这件事!?

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

如果我在服务中使用网络名称 host 而没有在网络中定义它(因为它已经存在),它会说.错误:服务应用程序"使用未定义的网络主机"

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"

如何在 Docker-Compose 中一起使用 host 网络和任何其他用户定义的网络(或默认网络)?

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

我正在使用 Docker version 17.11.0-ce-rc3, build 5b4af4fdocker-compose version 1.17.1, build 6d101fb

推荐答案

TL;DR 你不能.主机网络关闭了该容器的 docker 网络命名空间.您不能同时打开和关闭它.

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.

相反,使用已发布的端口或可以作为卷共享的 unix 套接字连接到您的数据库.例如.以下是发布端口的方法:

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

这篇关于如何在 Docker-Compose 中一起使用主机网络和任何其他用户定义的网络?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆