docker - 如果使用“network_mode:host”,容器无法访问主机服务
问题描述
我在 docker-compose.yml 中定义了 2 个容器。容器 1 通过 HTTP 请求与运行在主机上的服务进行通信。容器 2 需要访问互联网,因此设置了 network_mode:host,以便它可以访问主机接口(eth0 和 eth1)。
docker-compose.yml 看起来像:
version: "3"
services:
container1:
image: Image1
environment:
- SYSTEMAPI_URI
cap_add:
- SYS_TTY_CONFIG
devices:
- "/dev/tty1:/dev/tty1"
- "/dev/tty2:/dev/tty2"
volumes:
- /var/lib/docker/volumes/<>
container2:
image: Image2
environment:
- SYSTEMAPI_URI
- STORAGE_FOLDER=/mnt
- CERTIFICATE_PATH=/mnt/cert
- STORAGE_HOST=/var/lib/docker/volumes/<>
- EXTRA_CONFIG=${DOLLAR}SYSTEMAPI_VAR_DNSMASQ_EXTRA_CONFIG
volumes:
- /var/lib/docker/volumes/<>
privileged: true
network_mode: "host"
将 network_mode 设置为 host 时,从 container1 到主机服务的 HTTP 请求因超时而失败。route 命令只有 eth0 和 eth1 的条目。如果没有 network_mode,请求会通过,但 container2 会失去与 Internet 的连接。
network_mode 在这里使用正确吗?如果没有,有人可以告诉如何解决这个问题。
解决方案
The right way to get access to services running on host is to add extra_hosts
(here is the official reference). You also don't need the privileged mode (it is usually better to avoid it whenever possible).
With extra_hosts you map the name that your container is looking for to the IP of your host.
推荐阅读
- c# - Entity Framework : setting value converter for type generically, including TPH types
- java - Address binding issue - Remote Debugging of Maven Application
- c# - Getting Error 400 When Calling A Web Api Method Using Ajax
- node.js - How do I create a user in the firebase emulator via cloud function?
- javascript - Discord js message sending to specific channel
- maven - 通过 Maven Deploy Plugin to Nexus 获取已部署快照的时间戳
- reactjs - React-player:无法播放映射数组中的选定项目
- .net-core - Azure NLB redirection is resulting in AntiForgery Exception upon load distribution
- javascript - 动态创建的 SQL 查询仅部分工作
- javascript - 引导模式不会在页面加载时打开