如何在Docker Compose中连接不同网络中的容器? [英] How do I connect containers in different networks in Docker Compose?

查看:213
本文介绍了如何在Docker Compose中连接不同网络中的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

---
version: '3.7'

networks:
  sydney:
    name: sydney
  london:
    name: london

services:
  sydney-service:
    image: whatever
    hostname: sydney-service
    container_name: sydney-service
    networks:
      - sydney

  london-service:
    image: whatever
    hostname: london-service
    container_name: london-service
    environment:
      PAIR_SERVER: sydney-service:8080 # doesn't work
    networks:
      - london

我在docker撰写文件中有多个网络。由于不同的服务位于不同的网络中,因此它们不会互相看到。如何将一个网络中的一项服务连接到另一网络中的另一项服务?

I have multiple networks in a docker compose file. As different services are in different networks they do not see each other. How do I connect one service in one network to another service in another network?

谢谢!

推荐答案

您可以通过将它们放置在同一网络中来进行连接。这是docker中网络的目的,也是通过docker网络连接docker容器的前提条件之一。

You connect them by placing them in the same network. That is the purpose of networks in docker and one of the prerequisites of connecting docker containers over docker networking.

您可以在多个网络中拥有一个容器,这可能会解决您面临的问题:

You can have a container in more than one network, which may solve issues you are facing:

version: '3.7'

networks:
  sydney:
    name: sydney
  london:
    name: london
  global:

services:
  sydney-service:
    image: whatever
    hostname: sydney-service
    container_name: sydney-service
    networks:
      - sydney
      - global

  london-service:
    image: whatever
    hostname: london-service
    container_name: london-service
    environment:
      PAIR_SERVER: sydney-service:8080 # doesn't work
    networks:
      - london
      - global






另一个选择是绕过容器网络,并与其他服务进行通信已发布的端口。在这种情况下,主机名是docker主机,端口是已发布的端口,而不是容器端口。如果您的目的是能够在使用撰写文件部署的容器之间进行通信,则我建议不要这样做。


The other option is to bypass container networking, and communicate with the other service on a published port. In that case, the hostname is the docker host, and the port is the published port rather than the container port. I recommend against this if your purpose is to be able to communicate between containers deployed with a compose file.

这篇关于如何在Docker Compose中连接不同网络中的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆