Considering the fact I cannot use Docker compose and a very simple Docker setup:
- a NodeJs app (container
A) - a service exposing a REST api (container
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.
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:Then launch one container attached to that network:
And then launch a second container:
Now within the
app1container you can use the hostnameapp2to refer to the second container, and in theapp2container you can use the hostnameapp1to refer to the first container. Here's a simple, runnable example:Taking container
app1as an example, we can successfully access our services the appropriate container names. The following commands all run successfully:You can read more about this in the Docker networking documentation.