Why Docker Works with 0.0.0.0 but Not 127.0.0.1

dockernetworking

const hostname = '0.0.0.0'; // << This is where I'm confused
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

When I dockerize this app and run it in a container, hostname 0.0.0.0 works, but 127.0.0.1 doesn't work. I understand the reason why is because docker containers pretty much get their own IP.

So when I build and run the container when I set the hostname variable to 127.0.0.1, and then visit 127.0.0.1 on my browser, I'm not connecting to the container's IP address, but my local machine.

But why is it when I run the containerized app on 0.0.0.0 and visit 127.0.0.1 on my browser, it now connects to the container instead of my local machine?

Thank you.

Best Answer

docker is "a different machine" and your machine gets a port forward to that machine on localhost.

So when the app inside docker listens to 127.0.0.1 that is only valid inside that machine, to connect to it from "outside" you need to listen to the any address.

So there is 2 different 127.0.0.1.

If you listen to any (0.0.0.0) then it is also available on 127.0.0.1, and all other interfaces/IPs on the machine.

These days you should make sure to listen to :: which is the IPv6 variant, but it should also include v4. Trying to use current standards will reduce future issues.