【问题标题】:Communicate between two docker containers在两个 docker 容器之间进行通信
【发布时间】:2017-09-24 09:16:46
【问题描述】:

我是 docker 新手,在容器之间的通信方面需要您的帮助。

我有两个容器 容器 1:它是一个网站,在 80 端口上运行 容器 2:它是上述网站的 Web API,运行在 8000 端口

我在我的 Raspberry Pi 中安装了两个容器。我的 RPi 主机名是 raspberrypi 我用 --net=host 创建了两个容器,所以在我的网站中,我可以通过http://raspberrypi:8000/dosomething 调用我的网站

但是 RPi 的主机名可以更改,我无法使用新的 API URL 重新创建网站容器(例如:http//new_host_name:8000/dosomething)所以我的问题是

有没有办法将主机名分配给容器,以便我可以在其他容器中使用它? 例如: Container 2 使用“my_service”作为其主机名,因此在 Container 1 中,我可以使用“http//my_service:8000/dosomething”。我的客户可以更改他们的 RPI 主机名,我不需要更新我的代码。

谢谢,祝你有美好的一天。

【问题讨论】:

标签: docker


【解决方案1】:

假设您使用以下命令运行第一个容器:

docker run -d --name my_service web_api_image

所以你可以使用--link 标志来运行第二个:

docker run -d -P --name web --link my_service:my_service website_image

然后,在网站容器中,您可以使用 my_service 主机名引用 Web api。

请注意: --linkdeprecated

你也可以使用docker-compose:

version: "2"
services:
  web_api:
    image: web_api_image
    container_name: web_api
    ports:
      - "8000:8000"
    expose:
      - "8000"
  website:
    image: website_image
    container_name: website
    ports:
      - "80:80"
    links:
      - "web_api:web_api"

替换图像名称并使用docker-compose up运行

【讨论】:

  • 谢谢。但是当我使用--link时,它会显示一条错误消息“docker:来自守护进程的错误响应:冲突选项:主机类型网络不能与链接一起使用。这将导致未定义的行为。”。也许,我使用--net=host。无论如何,在这种情况下,你能给我一个关于 docker-compose 的例子吗?
  • 不要使用--net 标志。确保您删除了所有容器docker ps -a。如果您更喜欢 docker-compose 我编辑答案..
  • @Doraemon 所以,你能接受/支持我的回答吗?
【解决方案2】:

您可以使用docker-compose,因为同一个撰写文件中的所有容器默认都在同一个网络中,并且可以使用它们的服务名称相互调用。

但是,如果您使用docker run,则可以使用-h 标志指定主机名。示例:docker run -h test.example.com -it ubuntu /bin/bash

我建议您查看 docker-compose 的 aliases。更进一步,您和您的客户都可以使用env_file 变量来指定变量的值。

【讨论】:

    【解决方案3】:

    这是如何在docker中使用桥接驱动网络在两个容器之间进行通信。

    .net core 2.2 中的 github 示例是here

    version: '3.4'
    
    services:
    eventstoresample: 
      image: eventstoresample
      build:
        context: .
        dockerfile: EventStoreSample/Dockerfile
      networks:
        clusternetwork:
          ipv4_address: 172.16.0.12
    
    eventstore: 
    image: eventstore/eventstore
    environment:
      - EVENTSTORE_INT_IP=172.16.0.13
      - EVENTSTORE_EXT_HTTP_PORT=2113
      - EVENTSTORE_EXT_TCP_PORT=1113
      - EVENTSTORE_EXT_HTTP_PREFIXES=http://*:2113/
    ports:
      - "1113:1113"
      - "2113:2113"
    networks:
      clusternetwork:
        ipv4_address: 172.16.0.13
    
    networks:
      clusternetwork:
      driver: bridge
      ipam:
        driver: default
        config:
          - subnet: 172.16.0.0/24
    

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2018-07-15
      • 1970-01-01
      相关资源
      最近更新 更多