4

I'm just trying to learn Node.js and Docker at the same time. I have a very simple Node.js app that listens on a port and returns a string. The Node app itself runs fine when running locally. I'm now trying to get it running in a Docker container but I can't seem to reach it.

Here's my Node app:

const http = require('http');

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

var count = 0;

var server = http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end("Here's the current value: " + count);
    console.log('Got a request: ', req.url);
    count++;
});

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

My Dockerfile:

FROM node:latest

MAINTAINER Jason

ENV PORT=3000

COPY . /var/www
WORKDIR /var/www

EXPOSE $PORT

ENTRYPOINT ["node", "app.js"]

My build command:

docker build -t jason/node .

And my run command:

docker run -p 3000:3000 jason/node

The app.js file and Dockerfile live in the same directory where I'm running the commands. Doing a docker ps shows the app running but I just get a site cannot be reached error when navigating to 127.0.0.1:3000 in the browser. I've also confirmed that app.js was properly added to the image and I get the message "Server running at http://127.0.0.1:3000/" after running.

I think I'm missing something really simple, any ideas?

Jason
  • 2,455
  • 4
  • 37
  • 48
  • Omit `hostname` or use '0.0.0.0' on listen function. Make it `server.listen(port, '0.0.0.0', () => { console.log(`Server running at http://${hostname}:${port}/`); });` – YYY Dec 10 '16 at 18:51
  • That was it, thanks Yuva! Create an answer and I'll select it. – Jason Dec 10 '16 at 19:11
  • I had the same issue, and it was fixed now. Thank you very much Yuva. – truthblue82 Feb 14 '20 at 01:49

2 Answers2

4

Omit hostname or use '0.0.0.0' on listen function. Make it server.listen(port, '0.0.0.0', () => { console.log(Server running..); });

YYY
  • 6,107
  • 1
  • 12
  • 14
2

If You use docker on Windows 7/8 you most probably have a docker-machine running then You would need to access it on something like 192.168.99.100 or whatever ip your docker-machine has.

To see if you are running a docker-machine just issue the command

docker-machine ls
Sergiu Vidrascu
  • 246
  • 1
  • 4
  • Windows 10 and there's no docker-machine listed. The problem was as Yuva mentioned in the comment above. Thanks Sergiu. – Jason Dec 10 '16 at 19:12