Wednesday, September 13, 2017

Running the NodeJS Example Inside Docker Container

Running the NodeJS Example Inside Docker Container


Yesterday, I showed how to run NodeJS inside a Docker container. Today, I updated my Github project (https://github.com/medined/docker-nodejs) so that the Example server works correctly.

The trick is for the NodeJS code inside the container to find the containers IP address and listen on that address instead of localhost or 127.0.0.1. This is not difficult.

 
 require(dns).lookup(require(os).hostname(), function (err, add, fam) {
  var http = require(http);
  http.createServer(function (req, res) {
    res.writeHead(200, {Content-Type: text/plain});
    res.end(Hello World );
  }).listen(1337, add);
  console.log(Server running at http:// + add + :1337/);
})

If youre using my Docker image, then youd just run the following to start the server. Use ^C to stop the server.

 
node example.js


Now you can browse from the host computer using the following URL. Note that the docker run command exposes port 1337.

 
http://localhost:1337/


download file now

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.