如何使Docker容器使用主机网络?

时间:2019-08-27 05:06:15

标签: docker docker-compose

我正在为Mac运行docker。我的docker compose配置文件是:

version: "2.3"
services:
  base:
    build:
      context: .

  dev:
    network_mode: "host"
    extends:
      service: base

通过docker-compose run --rm dev sh启动容器时,它无法ping IP地址(172.25.36.32)。但是我可以从主机ping此地址。我在配置文件上设置了network_mode: "host"。如何使Docker容器共享主机网络?

我发现host网络不适用于Mac。在Mac中有解决方案吗?

下面是docker network inspect ID的输出:

[
    {
        "Name": "my_container_default",
        "Id": "0441cf2b99b692d2047ded88d29a470e2622a1669a7bfce96804b50d609dc3b0",
        "Created": "2019-08-27T06:06:30.984427063Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "22d3e7500ccfdc7fcd192a9f5977ef32e086e340908b1c0ff007e4144cc91f2e": {
                "Name": "time-series-api_dev_run_b35174fdf692",
                "EndpointID": "23924b4f68570bc99e01768db53a083533092208a3c8c92b20152c7d2fefe8ce",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "time-series-api",
            "com.docker.compose.version": "1.24.1"
        }
    }
]

2 个答案:

答案 0 :(得分:0)

我认为您需要使用container选项而不是up来启动run,因为运行会覆盖许多选项:

docker-compose up dev

或者您可以将--use-aliasesrun一起使用

  

-use-aliases在网络中使用服务的网络别名                             容器连接到。

请参阅this

PS 更新后

以下内容将适用于MAC

dev:

  network: host
  extends:
    service: base

答案 1 :(得分:0)

我认为您需要在network期间添加build选项。尝试

version: "2.3"
services:
  base:
    build:
      context: .
      network: host
  dev:
    network_mode: "host"
    extends:
      service: base

编辑:在Linux上可以使用,请参阅Mac的文档

主机网络驱动程序仅适用于Linux主机,Mac的Docker桌面,Windows的Docker桌面或Windows Server的Docker EE不支持该主机网络驱动程序。