Nopcea Flavius
Nopcea Flavius

Reputation: 303

docker container port accessed from another container

I have a container1 running a service1 on port1

also

I have a container2 running a service2 on port2

How can I access service2:port2 from service1:port1?

I mention that the container are linked together.

I ask if there is a way to do it without accessing the docker0 IP (where the port is visible)

thanks

Upvotes: 1

Views: 2842

Answers (1)

BMitch
BMitch

Reputation: 263636

The preferred solution is to place both containers on the same network, use the build-in dns discovery to reach the other node by name, and you'll be able to access them by the container port, not the host published port. By CLI, that looks like:

docker network create testnet
docker run -d --net testnet --name web nginx
docker run -it --rm --net testnet busybox wget -qO - http://web

The busybox shows a sample client container connecting to the nginx container with the name web, over port 80. Note that this port didn't need to be published to be reachable by other containers.

Setting up multi-container environments with their own network is a common task for docker-compose, so I'd recommend looking into this tool if you find yourself doing this a lot.

Upvotes: 2

Related Questions