I am trying to wrap my head around how to access other containers running as part of docker-compose services.
I have seen a lot of answers talking about containers accessible by their service name inside of other containers but also a lot of tutorials simply use the localhost with the exposed port.
So I am just trying to gain clarity on when to use which and why it works the way it works.
My sample application is: https://github.com/daniil/full-stack-js-docker-tutorial
In it, I have an NGINX server that maps both ui and api services together, but after the fact I realized that inside of my React container (3000:3000) I can actually just get access to Express container (5050:5050) by making an axios request to http://localhost:5050.
But at the same time if I try to connect to my MySQL container (9906:3306) via localhost, it doesn't work, I have to use db as a host, ie the container name.
Can someone please help me understand how it all works:
- When can I use
http://localhost:SERVICE_PORT, does it work inside React service because it's a browser request? ie: axios - How come I can't use
http://api:5050inside of React / axios request, is it because there is no host resolution for that? - How come I can't use
http://localhost:9906|3306to connect to my db service? - What is the purpose or benefit of NGINX reverse proxy to tie client and api together, if you actually don't need to have anything in between since localhost seems to work?
- If containers are supposed to isolated, why is it then
localhost:5050from within my React container still sees the API server running on 5050 in a different container? - Other general rules that can help me understand how cross-container communication works