Pages

Monday, June 24, 2019

Run NodeJs in Docker

Hello Everyone,

In this tutorial we're going to run à simple HelloWorld NodeJS application in Docker.

To start with that, let's first create our NodeJS HelloWorld application.

const http  = require('http');
const os    = require('os');

console.log("kubia server starting...");

var handler = function(request, response) {
    console.log("Received request from : "+request.connection.remoteAddress);
    response.writeHead(200);
    response.end("You've hit : "+ os.hostname() +"\n");
}

var www     = http.createServer(handler);
www.listen(8080);

In this script, we're starting a server listening in port 8080 and printing the hostname of the container.

To create an image of our application, we need to create a DockerFile as fallow :

from node:7
ADD app.js /app.js
ENTRYPOINT ["node","app.js"]


The first line from node:7, means that we want to create our image base on the image node version 7.

The line ADD app.js /app.js, copies our script app.js to the root directory of our container.

The last line, ENTRYPOINT ["node","app.js"], is the command line to start our application.

The next step, we need to build our image and to do that, we need to execute the following command :

docker build -t test_nodejs_application .

The last step to accomplish it to start a container based on this image.
docker run --name test_nodejs_application -p 8083:8080 -d test_nodejs_application

If we test our application on the browser, you see the page of our application with the hostname of the container. 

You can find the code of this HelloWorld NodeJs application in the following link.



No comments:

Post a Comment