How do I connect containers in different networks

2020-03-31 03:37发布

---
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

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?

Thanks!

1条回答
祖国的老花朵
2楼-- · 2020-03-31 04:03

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

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.

查看更多
登录 后发表回答