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