Comprehensive Guide to Dockerizing JavaScript and Node.js Projects for Beginners

Estimated reading time: 6 minutes

When it comes to the development environment, developers have actively embraced the use of containers.

Docker is one of the most widely used containerization platforms that enable users to bundle applications and all their dependencies as one container.

This helps in the deployment of your application to any environment of your choice as the application will function optimally in whichever environment it has been deployed in.

Dockerizing a JavaScript/Node.js project is a usable solution that makes the development, testing, and deploying practical and easy.

What is Docker?

Docker is an application platform that employs the use of containers to deploy applications in the simplest manner possible.

These containers package the application with all it needs such as libraries and configuration files and can be run on any other system that supports the Docker system.

Whether you want to optimize your Node.js project or just want to hire Angular developers for another project, Docker provides the consistency that is needed across different stacks and technologies.

Fast-Track Your DevOps Career 🚀

Stay ahead of the curve with the latest industry insights. Get weekly tips & propel your skills to the next level.

Subscribe Now!

Why Dockerize Your Node.js Project?

Dockerizing your Node.js project provides you with different benefits:

Consistency Across Environments

Using containers means your application will work the same in the development, testing, and production processes with ease.

Simplified Dependencies

Docker containers include everything your application needs to run, eliminating the classic “works on my machine” problem.

Adaptability

Docker makes it easier to scale your application by allowing you to run multiple containers across different environments.

Isolation

They are independent of each other, thus increasing their security and reliability.

After you know the basic concept of Docker, now it is time for the Dockerizing of your JavaScript/Node.js project.

Step-by-Step Guide to Dockerizing Your JavaScript/Node.js Projects

Step 1: Install Docker

In the first step, you have to install Docker. You will have to do so before starting the following steps. Docker provides installation packages that are specific to the operating system, Windows, macOS, or Linux.

Please go to the Docker website and read more about installation for the OS that you are using.

After installation, verify that Docker is installed correctly by running the following command in your terminal:

Bash
docker version

Client: Docker Engine - Community
 Version:           23.0.3
 API version:       1.42
 Go version:        go1.19.7
 Git commit:        4e8bcvd
 Built:             Tue Jan  5 10:05:20 2024
 OS/Arch:           darwin/amd64
 Context:           default

Server: Docker Desktop 4.19.0 (12345)
 Engine:
  Version:          23.0.3
  API version:      1.42 (minimum version 1.12)
  Go version:       go1.19.7
  Git commit:       59118bf
 Built:             Tue Jan  5 10:05:20 2024
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.20
  GitCommit:        2806fc1057397dbaeefbea0e4e17bddfbd388f38
 runc:
  Version:          1.1.5
  GitCommit:        v1.1.5-0-gf19387a
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

You should be able to see the version number of Docker to confirm that it is installed and can be used.

Step 2: Create a Simple Node.js Application

For this guide, let’s create a simple Node.js application that we’ll Dockerize. If you already have a project then you can just skip this step.

You need to create a new directory and then navigate into it:

Bash
mkdir my-node-app

cd my-node-app

Initialize a new Node.js project:

Bash
npm init -y

Then create an index.js file. This simple application creates an HTTP server that responds with “Hello, Docker!” when accessed.

Create an index.js file with the following content:

JavaScript
// index.js
const http = require('http');

const hostname = '0.0.0.0'; // Listen on all network interfaces
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, Docker!\n');
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Step 3: Create a Dockerfile

A Dockerfile is a script that contains a series of instructions for Docker to build an image of your application. Based on your project directory, you need to create a file named ‘Dockerfile’.

Dockerfile
# Use the official Node.js image.
# https://hub.docker.com/_/node
FROM node:18

# Create and set the working directory
WORKDIR /usr/src/app

# Copy package.json and package-lock.json
COPY package*.json ./

# Install application dependencies
RUN npm install

# Copy the application code
COPY . .

# Expose the application port
EXPOSE 3000

# Command to run the application
CMD [ "node", "index.js" ]

Step 4: Create a .dockerignore file

Create a .dockerignore file in the root directory to specify files and directories that should be excluded from the Docker image:

Dockerfile
node_modules
npm-debug.log

Step 5: Build the Docker Image

Build your Docker image with the following command:

Bash
docker build -t my-node-app .

Docker Build 39x Times Faster: Docker Build Cloud

Step 6: Run the Docker Container

Run the Docker container and map port 3000 of the container to port 3000 on your host:

Bash
docker run -p 3000:3000 my-node-app

Expected Output:

When you run the container, you should see the following output:

Bash
Server running at http://0.0.0.0:3000/

Step 7: Testing and Debugging

Open a web browser and navigate to http://localhost:3000. You should see:

Bash
Hello, Docker!

To view logs from the running container, use:

Bash
docker logs <container-id>

Replace <container-id> with the actual container ID, which you can find by running docker ps.

To access the container’s terminal, use:

Bash
docker exec -it <container-id> /bin/bash

Docker Container Logs Location: A Comprehensive Guide

Docker Container ls Filter: 13 Ultimate Hacks!

Step 8: Pushing Your Image to Docker Hub

Log in to Docker Hub:

Bash
docker login

Tag your Docker image with your Docker Hub username:

Bash
docker tag my-node-app your-dockerhub-username/my-node-app

Push the image to Docker Hub:

Bash
docker push your-dockerhub-username/my-node-app

Must read the comprehensive guide on “Docker Push Image to Remote Registry” provides the latest information and steps to effectively push images to remote registries and share your image across the team.

Docker Push Image to Remote Registry Made EASY -⏱️ 5-Minute!

Level Up Your DevOps Skills! 📈

Get Weekly Tips, Tutorials & Master the Latest Trends – Subscribe Now!

Subscribe Now!

Conclusion

Dockerizing your JavaScript/Node.js project has many advantages; it can maintain the same configuration in different environments and make deployment easier.

This means you’ll know exactly how to go about building a Docker container for your app which will be portable, scalable, and easier to manage among others.

Additional Resources

Kashyap Merai
Kashyap Merai

Kashyap Merai, a Certified Solution Architect and Public Cloud Specialist with over 7 years in IT. He helped startups in Real Estate, Media Streaming, and On-Demand industries launch successful public cloud projects.

Passionate about Space, Science, and Computers, He also mentors aspiring cloud engineers, shaping the industry's future.

Connect with him on LinkedIn to stay updated on cloud innovations.