首页 > 解决方案 > 如果使用“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 在这里使用正确吗?如果没有,有人可以告诉如何解决这个问题。

标签: dockernetworkingdocker-composedocker-container

解决方案


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.


推荐阅读