How to Dockerize a NodeJS App

Bawantha Rathnayaka
Nov 8, 2020 · 2 min read

In this article i will show you how to dockerize a nodejs application

Part 1: Creating Node.js application

Usually, when I start a new Node.js project I use npm to generate my initial project.

npm init

When I was asked for the details of the application (name, version, etc.), just enter default values.

Then, Npm will create a package.json that will hold the dependencies of the app. Let’s add the Express Framework as the first dependency

$ npm install express --save

The file should look like this now:

{
"name": "helloworld",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}

Next, everything has installed, we can create an index.js file with a simple HTTP server that will serve our Hello World website:

var express = require('express')
var app = express()
var port = 3000app.get("/", function(req. res){
res.send("Hello World")
});
app.listen(port, function(){
console.log("Server started on port 3000")
}}

Now the application is ready to launch:

$ node index.js

Part 2: Dockerizing Node.js application

Let’s add to the directory with our application:

FROM node:latestWORKDIR /appCOPY ..
RUN npm install
EXPOSE 3000ENTRYPOINT ["node", "index.js"]

now we can build our Docker image

docker build -t {DOCKER_PROFILE_USERNAME}/node:latest .

Then, view our docker images use this command

docker images

now run docker container

docker run -p 3000:3000 {DOCKER_PROFILE_USERNAME}/node

Surf to http://localhost:3000/ to see it running.

SLIIT FOSS Community

SLIIT FOSS Community is a team of volunteers who believe in…

SLIIT FOSS Community

SLIIT FOSS Community is a team of volunteers who believe in the usage of Free/Open Source Software (FOSS). The primary objective of the community is to promote, develop and diversify the usage of Free/Open Source Software at SLIIT.

Bawantha Rathnayaka

Written by

Blogger | FullStack Developer 💻 | Undergraduate 🎓 |

SLIIT FOSS Community

SLIIT FOSS Community is a team of volunteers who believe in the usage of Free/Open Source Software (FOSS). The primary objective of the community is to promote, develop and diversify the usage of Free/Open Source Software at SLIIT.