How to access container from another compose that connected to external network?

烈酒焚心 提交于 2020-01-03 19:31:12

问题


Here is compose file with config of container that I wish to connect to from external container (defined in another compose file):

version: '3.5'
services:
  service-to-connect-to:
    build: .
    networks:
      - my-external-network

networks:
  my-external-network:
    external: true

and another compose file that contains config for container from which I wish to connect to service-to-connect-to:

version: "3.5"

services:
  service-to-connect-from:
    build: .

I tried to connect to service-to-connect-to via this domains:

service-to-connect-to service-to-connect-to.my-external-network my_external_network.service-to-connect-to

but nothing of them worked.

Where I'm wrong?

Thanks


回答1:


First, you have to add both services to same network in order to connect them. So, the latter compose file should be something like

version: "3.5"

services:
  service-to-connect-from:
    build .
    networks:
      - my-external-network

networks:
  my-external-network:
    external: true

Now that both services are on the same network they can find each other using container's name. Container name is by default same as the service name BUT docker compose also prefixes it by project name which is by default the directory name where the compose file exists. You can see this if you first start the services by docker-compose up -d and then see how the containers get named by running docker ps. The container name could be for example project1_service-to-connect-to. With this name you can connect from another service.

If you like to, you can also set the container's name explicitly using container_name option for service. When used, compose doesn't prefix the container name anymore.




回答2:


This is not possible with compose, because the second docker-compose file will create a different network with the current directory name and then your both the services will be in two different docker network and will not be able talk to each other.

So you can do two things: 1. either use same network for both the services (then its better to have one combined compose file). 2. use docker swarm stacks, where you can connect to other services with <service_name>.<stack_name>

References: https://docs.docker.com/docker-cloud/apps/service-links/#using-service-and-container-names-as-hostnames

https://docs.docker.com/v17.09/engine/userguide/networking/configure-dns/

Note: Even service links does not help, because compose creates different network while running the second file.



来源:https://stackoverflow.com/questions/51522543/how-to-access-container-from-another-compose-that-connected-to-external-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!