0

I am trying to dockerize a Node.js server. I use the following index.js and Dockerfile files:

    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');
    });

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

FROM node:latest
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm i
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]

Then I run docker build . -t webapp and docker run -p 8080:3000 webapp, but when I try to open the app in the browser I see "The webpage at http://localhost:8080/ might be temporarily down or it may have moved permanently to a new web address."

Then when I change the hostname in the index.js to 0.0.0.0, it seems to work fine and I can access my app in the browser under http://localhost:8080/.

What is the difference between running an app in a container on the localhost vs. on 0.0.0.0?

youhatch
  • 141
  • 3
  • 7

1 Answers1

1

In a container, localhost is the container itself. So when you bind to 127.0.0.1 your program will only accept connections coming from inside the container.

You need to bind to 0.0.0.0 for it to accept connections from outside the container.

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35