DEV Community

Ada Cheng
Ada Cheng

Posted on • Updated on

Dockerizing a Node.js web application

In this article, I would like to document how I dockerize my portfolio web site, which is a Node.js application.

Table of Contents

Build the Node.js application

Firstly, create Dockerfile for the Node.js application.

FROM node:14.18.2-alpine3.14
WORKDIR /app
COPY package.json ./
COPY package-lock.json ./
COPY ./ ./
RUN npm ci
CMD ["npm", "run", "start"]
Enter fullscreen mode Exit fullscreen mode

Since I've used node-sass package for enabling SASS in my application and the package supports limited Node.js version, I need to find the right node.js docker image at docker hub.

Supported Environments by node-sass package

At docker hub, search for the right image in the Tags tab. Once the desired image is found, put it on the first line (i.e. the FROM layer) of the Dockerfile.

Node.js docker images

Secondly, create .dockerignore file to exclude files and directories from the docker image.

node_modules
*.log
Enter fullscreen mode Exit fullscreen mode

Thirdly, build the Node.js application.

yarn build
Enter fullscreen mode Exit fullscreen mode

Fourthly, build the docker image.

*Make sure Docker Engine is running in your development environment.

docker build -f Dockerfile -t portfolio-website .
Enter fullscreen mode Exit fullscreen mode

Deployment

  • Deploy by exposing port 5001 instead of default port 3000 (you can change to any port according to your environment).
docker run --name portfolio-website -it -p 5001:3000 portfolio-website
Enter fullscreen mode Exit fullscreen mode

Verification

  • Check that the web application is running by opening http://localhost:5001/ in a web browser.

Dockerized Node.js application

Latest comments (2)

Collapse
 
alexstaroselsky profile image
Alexander Staroselsky • Edited

Could consider only installing production packages to greatly reduce the size of the image and speed up the build. npm ci —production

Collapse
 
adafycheng profile image
Ada Cheng

Thanks a lot for your advice!