Considering the fact I cannot use Docker compose
and a very simple Docker
setup:
A
)B
)How can I connect to B
from A
to query the API without SSHing but just in appending stuff to docker run...
?
I've succeeded in getting internal ip of B
(using docker container inspect B
) and requesting from A
something like fetch("http://ip-of-b/api")
. It works but it's not well-down. Indeed if I make another deploy, B
ip changes.
Is there a very simple way to make a production bridge between these 2 containers?
I've read about --add-host=host.docker.internal:host-gateway
but I can't understand how it works/it's relevant.
PS: in the future, I might have a third container (C
) that must also be able to connect to A
.
I've succeeded in getting internal ip of B (using docker container inspect B) and requesting from A something like fetch("http://ip-of-b/api").
That solution is problematic because container ips are dynamic; if you were to restart one of the two containers, you would no longer be able to connect. You want to use container names.
It's important to realize that Docker Compose is just a convenient wrapper around the docker API; you can accomplish exactly the same thing using docker run
. When you bring up a Docker Compose application stack, Compose starts by creating a user-defined network, and then it subsequently attaches all the containers to that network. That's important because containers on a user defined network are able to refer to eachother by name.
We can do the same thing with docker run
. First create a network:
docker network create mynetwork
Then launch one container attached to that network:
docker run --name app1 --network=mynetwork app1-image
And then launch a second container:
docker run --name app2 --network=mynetwork app2-image
Now within the app1
container you can use the hostname app2
to refer to the second container, and in the app2
container you can use the hostname app1
to refer to the first container. Here's a simple, runnable example:
docker network create mynetwork
docker run -d --name app1 --network mynetwork docker.io/alpinelinux/darkhttpd
docker run -d --name app2 --network mynetwork docker.io/alpinelinux/darkhttpd
docker run -d --name app3 --network mynetwork docker.io/alpinelinux/darkhttpd
Taking container app1
as an example, we can successfully access our services the appropriate container names. The following commands all run successfully:
docker exec app1 wget -O- http://app1:8080
docker exec app1 wget -O- http://app2:8080
docker exec app1 wget -O- http://app3:8080
You can read more about this in the Docker networking documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With