Dockerizing My Node.js App: A Beginner’s Guide

Abylin Johnson
3 min readMay 6, 2023

--

In this article we will see how to dockerize a node application.

In this guide, I will provide you with a step-by-step process for Dockerizing a Node.js web server application, with index.js as the starting point.

First create a Dockerfile

Paste the following code

FROM node:18

WORKDIR /app

COPY package*.json ./


COPY . .

ENV PORT=8080

EXPOSE 8080

CMD ["npm", "start"]

The first line of code, ‘FROM node:18’, downloads a copy of the Node.js Docker image with version 18. The ‘WORKDIR /app’ command sets up a working directory on the Docker image where our code will reside. The ‘COPY package*.json ./’ instruction copies the package.json file to the working directory of the Docker image.

Next, the ‘RUN npm install’ command runs the ‘npm install’ command in the shell and installs the dependencies for us. Finally, using the ‘COPY . .’ command, we copy the whole code to the working directory. To avoid copying the ‘node_modules’ file, we should add it to the .dockerignore file.

The ‘ENV PORT=8080’ command creates an environment variable ‘PORT’ with the value ‘8080’. By using the ‘EXPOSE 8080’ instruction, we expose port 8080 of the Docker image. Finally, to start the application, we use the command ‘CMD [“npm”, “start”]’.

Now lets build the docker image using the code buid command

sudo docker build <path>

To the see the created docker image use

sudo docker images

You can also use the -t flag to give a tage name. We can see that we have created a docker image. now lets run this docker image.

sudo docker run <IMAGE ID>

By using the ‘-p’ command, we were able to map port 8080 of our Docker image to port 8000 on our local machine, giving us access to the application via a web browser or other type of client.

You can see that our web application is running without any problem.

To see the current running docker images

sudo docker ps

Happy Hacking !

--

--

Abylin Johnson
Abylin Johnson

No responses yet