DEV Community

Cover image for How to Dockerize a NodeJs App
Ashok Naik
Ashok Naik

Posted on

How to Dockerize a NodeJs App

Docker is an essential tool when it comes to the deployment and delivery of an Application.

The main idea of docker is to create a package of your code along with dependencies into a unit called a container. It's a way to package software so that it can run on any hardware

To know more about docker

To know more about the Installation process of Docker Desktop

This blog covers the steps of adding docker to your application.

Before moving forward we need to understand 3 important components of docker.

  • DockerFile is a blueprint to create a Docker Image
  • Docker Image is a template to run docker Containers
  • Docker Container is a running process/application

I have a simple Node JS application with an index file which exposes a get API which sends a response message of

Docker is easy to learn 🐳

and runs on port 8080.

Alt Text

The First step is to create a docker file in the root folder of the Project.

Alt Text

In the docker file, the very first instruction is FROM used for installing NodeJs Base Image which helps in setting up an environment to run NodeJs Application.

The next instruction WORKDIR is used to set the working directory of a Docker container.

COPY uses two arguments the source and destination path which copies the package.json file to the current working directory.

RUN opens a terminal session and install dependencies listed in package.json.

COPY . . Copies local file to the Working directory

A .dockerignore file needs to be created similar to .gitignore
inorder to exclude node_modules folder.

ENV instruction is used to set the environment variable.

EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime.

CMD final instruction tells the container how to run the application.

Every instruction in the docker file is considered as a layer, the layers are cached when nothing is changed in the Dockerfile

The next instruction is to create a docker image that can be created using the following command.

docker build -t username/imagename .

Alt Text

All instructions in the DockerFile are executed to form the Image ID which is used to run a container.

The final step is to run the Docker Container with the help of the following command

docker run -p local-port:container-port image-id

-p flag is used for port forwarding.

Alt Text

Now if we check the


We can find our application up and running

Alt Text

Thats all folks !!!

Top comments (0)