1

I'm learning the getting started guide offered in Node.js official site, whose code snippet goes as follow.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

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

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

Also, I attempt to run that app (stored app.js in ${PWD}/guides/getting-started-guide) in Node's docker container run from the official node:9.1 image. (The version of docker in use is Docker version 17.05.0-ce, build 89658be)

docker run --rm -p 3000:3000 -u "node" -v ${PWD}/guides/getting-started-guide:/home/node/app -w /home/node/app --name "hello" -it node:9.1 node app.js

After the container is up, I see the log Server running at http://127.0.0.1:3000/. And the server responses "Hello World" when queried within the container.

However, the browser reports This site can’t be reached when I try to access it in the host machine with url http://localhost:3000 or http://127.0.0.1:3000/.

Dying for someone's help~

sammy00
  • 11
  • 1
  • Bind to 0.0.0.0 not localhost (127.0.0.1). – j_mcnally Nov 14 '17 at 03:17
  • It works!!! Why's that? – sammy00 Nov 14 '17 at 03:37
  • Docker net uses a different interface than localhost, 0.0.0.0 binds all interfaces in the container... its the typical way to bind inside a container. – j_mcnally Nov 14 '17 at 03:46
  • To expand on the different interface, A docker container is assigned it's own loopback interface which has the 127.0.0.1/8 range as normal. So `127.0.0.1` in a container refers to a different interface than `localhost` or `127.0.0.1` on the Docker host. – Matt Nov 16 '17 at 22:14

0 Answers0