使用docker-compose与宿主机网络

10
我试图使用docker-compose创建一个容器,使其同时连接两个网络。我希望其中一个网络是宿主机网络(就像运行“docker run --net=host”一样),另一个是用户定义的网络。
我尝试了以下方法:
version: '3'

networks:
  test:
    driver: bridge
  host:
    external: true

services:
  helloworld:
    image: python:3.6-alpine
    networks:
      - test
      - host
    cap_add:
      - NET_ADMIN
      - NET_RAW
    ports:
      - 0.0.0.0:8080:8080
    command: sh -c "cd /tmp && python -m http.server 8080"

我将翻译以下内容:

我遇到了这个错误:

$ docker-compose up
Removing blah_helloworld_1
Starting 8743618e8af4_blah_helloworld_1 ... error

ERROR: for 8743618e8af4_blah_helloworld_1  network-scoped alias is supported only for containers in user defined networks

ERROR: for helloworld  network-scoped alias is supported only for containers in user defined networks
ERROR: Encountered errors while bringing up the project.

2
你可以在服务中使用 network_mode 属性。但是,这与 networks 属性是互斥的。如果你使用 network_mode: "host",你的服务将可以访问 test 网络,而无需显式加入。你想要实现什么目标? - vstm
1
@vstm,您能描述一下如果启用了“network_mode:”host“,如何访问'test'网络吗? - Mikl
2个回答

1

hostdocker network ls 列出时,它的工作方式与其他网络有很大不同。

默认情况下,每个容器都在自己独立的网络命名空间中隔离。当使用 network_mode: host(使用compose)将容器置于“host”网络时,容器仅保留在主机的网络命名空间中。

一个容器不能同时处于桥接网络(例如 test)和 host 网络中,因为这需要该容器同时存在于主机的网络命名空间和它自己的独立网络命名空间中。


0

根据文档:

  • target: 容器内部的端口号
  • published: 公开暴露的端口号
  • protocol: 端口协议(tcp或udp)
  • mode: host用于在每个节点上发布主机端口,ingress用于负载平衡swarm模式端口。

示例:

 ports:
   - target: 8080
     published: 8080
     protocol: tcp
     mode: host

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接