Docker communication between containers

淺唱寂寞╮ 提交于 2020-02-07 02:00:04

问题


I want to create two containers and connect from one to another and I fail to do so. My docker-compose.yml:

version: '3.3'

networks:
  my_network:

services:
  test:
    image: ubuntu:latest
    command: sleep infinity
    networks:
      - my_network
  nginx:
    image: nginx:latest
    ports:
        - 80:80
    networks:
      - my_network

To test connection I run echo "" > /dev/tcp/0.0.0.0/80 on host machine and it goes fine; Then I do the same inside the second container test; There I get

echo "" > /dev/tcp/0.0.0.0/80
bash: connect: Connection refused
bash: /dev/tcp/0.0.0.0/80: Connection refused

Any ideas what I do wrong?


回答1:


You can connect from one container to the other using the service name, in your case test or nginx. For example in the nginx container you could run:

$ echo "" > /dev/tcp/test/<port>

You don't even need to expose the port in the docker-compose.yml.

If you want to use a different hostname to connect to a container you can use aliases



来源:https://stackoverflow.com/questions/59967498/docker-communication-between-containers

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