Blog

How to build a Node.JS project using Docker


How to build a Node.JS project using Docker?
Are you using Node.JS for your application development and want to build it?
How to run it in a different environment without worrying about dependencies?
How to change the port number while running node.js code?

This article will help you step by step, understand and implement all of the above.

To start with, you need to have Docker installed in your system, Follow this link to install Docker

Steps to Build and run NodeJS project using Docker

  1. We will use keymetrics/pm2 image in this article, you can also use Node.js official docker image with minor changes. The reason behind using PM2 images is its rich logging support.

    Pull “keymetrics/pm2” docker image.
  2. Take git clone or Copy source code in any system directory 
    (for example I’m taking /usr/share/nginx/html)
     
  3. Let’s create Dockerfile in the same folder as above 
FROM keymetrics/pm2:8-jessie
WORKDIR /usr/share/nginx/html
COPY . .
RUN npm install
EXPOSE 3000
CMD [ "pm2-runtime", "start", "server.js" ]

server.js: It’s the main file name of your project (can be server.js, app.js, etc.)

EXPOSE: define port number on which your code is running

FROM keymetrics/pm2:8-jessie: specify node.js version that your application is built on

Let’s build Docker image out of this Dockerfile and run the code, In the same directory where code resides fire following command 

docker build -t $projectname_nodejs .

It will create a new docker image that contains your built node.js code. 

Now when you run this Docker Image code will start to serve, follow this command

docker run -d --restart always --name $projectname_api -p 3000:3000 $projectname_nodejs

You can check it with localhost:3000
If you are using it in the server, hit the IP of server:3000 and can find application serving there. 

here -p contains 2 ports system port and container port, if 3000 port on system is not available, you can change it via changing the first parameter -p 4000:3000 , it will start serving on system’s 4000 port. 

If you deploy like this, even if you delete code from the server for security purpose, it will always be available via Docker image so can not be found easily. 

Do share your feedback in the comment section.

Drafted on: 26th December 2019

Leave a Comment