如何在Docker-Compose中一起使用主机网络和任何其他用户定义的网络? [英] How to use the host network, and any other user-defined network together in Docker-Compose?
问题描述
我想将在Docker-Compose文件中定义的两个Docker容器彼此连接(app
和db
).并且其中之一(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.
容器应连接到通用的用户定义网络(appnet
或default
),以使用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: host
和networks
,则会出现以下错误.
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
所以我只需要用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
上述撰写文件产生错误.
ERROR: for app network-scoped alias is supported only for containers in user defined networks
The foregoing compose file produces a error.
ERROR: for app network-scoped alias is supported only for containers in user defined networks
如果我在服务中使用网络名称host
而不在网络中定义它(因为它已经存在),它说.
ERROR: Service "app" uses an undefined network "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 5b4af4f
和docker-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屋!