title: Docker Compose accessing another container via localhost
body: <p>I am trying to wrap my head around how to access other containers running as part of <code>docker-compose</code> services.</p>
  <p>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.</p>
  <p>So I am just trying to gain clarity on when to use which and why it works the way it works.</p>
  <p>My sample application is: <a href="https://github.com/daniil/full-stack-js-docker-tutorial" rel="nofollow noreferrer">https://github.com/daniil/full-stack-js-docker-tutorial</a></p>
  <p>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 <code>http://localhost:5050</code>.</p>
  <p>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 <code>db</code> as a host, ie the container name.</p>
  <p>Can someone please help me understand how it all works:</p>
  <ul>
  <li>When can I use <code>http://localhost:SERVICE_PORT</code>, does it work inside React service because it's a browser request? ie: axios</li>
  <li>How come I can't use <code>http://api:5050</code> inside of React / axios request, is it because there is no host resolution for that?</li>
  <li>How come I can't use <code>http://localhost:9906|3306</code> to connect to my db service?</li>
  <li>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?</li>
  <li>If containers are supposed to isolated, why is it then <code>localhost:5050</code> from within my React container still sees the API server running on 5050 in a different container?</li>
  <li>Other general rules that can help me understand how cross-container communication works</li>
  </ul>