How to Build a Node.js App with Docker

node js docker

Docker is known as the industry leader when it comes to containerizing applications because of their portability and scalability. With Docker, deploying applications is far simplified since the containerized applications can perform uniformly regardless of the environment. It simplifies the distribution of your application while avoiding issues that arise from several machine configurations.

In this guide, we will explore all possible steps for building a Node.js application and containerizing it with Docker.

Installing Docker on the Machine

Docker simplifies the workflow of developers, designers, and engineers. Before creating a Node.js App with Docker, you need to install Docker.

Follow the given steps to install Docker on the Ubuntu machine:

Step 1: Updating System Repository

In order to keep Ubuntu packages and known vulnerabilities in the system free, this step is very important for Ubuntu users. The apt update command retrieves the list of packages from the repositories:

sudo apt update
update system repositories

Step 2: Installing Required Dependencies

Now, install the required dependencies so that there is no issue during the Docker installation:

sudo apt install -y apt-transport-https ca-certificates curl software-properties-common
Installing Required Dependencies

Step 3: Adding GPG Key for Docker

This step retrieves the official GPG keys for Docker and adds them to your system’s keyring. This key will be used to check whether the key is downloaded with curl and processed into the format the system requires.

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
Adding GPG Key for Docker

Step 4: Configure the Docker Repository

Getting the official Docker repository as it automatically detects the architecture and Ubuntu version to provide the correct packages. Let’s configure the Docker repository:

echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
Configure the Docker Repository

Step 5: Installation of the Docker Engine

With the new repository added, we freshened up the package list:

sudo apt update
update package list

At this step, we install four core Docker components:  

sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
install docker components

The components being installed:

  1. docker-ce: The Docker Community Edition engine (the core Docker program)  
  2. docker-ce-cli: Command-line interface for Docker  
  3. containerd.io: Container runtime that Docker uses  
  4. docker-compose-plugin: Plugin that provides Docker Compose functionality 

Step 6: Checking the Docker installation

After you run this command, you are given a test image to download; the image is dubbed hello-world. If everything is installed in the right way and the command is executed successfully, a message is shown confirming that the command is run, showing that Docker is in good form.

sudo docker run hello-world
check docker installation

Step 7: (Optional) Add your user to the Docker group 

As seen, running Docker commands requires elevated permissions (sudo). Now, add your user account to the “docker” group for admin permission:

sudo usermod -aG docker ${USER}
add user to docker group

A balance between convenience and productivity can streamline workflows, but one needs to log out and in for the settings to apply.  Log out and log back in for the changes to take effect, or run:  

newgrp docker
newgrp docker

Creating a Simple Node.js Application

Let’s create a sample Node.js application, which we will dockerize:  

Step 1: Creating a project directory

This creates a dedicated folder for our project and moves into it. The folder name will also give us an idea of what the project contains:  

mkdir nodejs-docker-app && cd nodejs-docker-app
Creating a project directory

Step 2: Initializing a Node.js project

Now, start by creating a package.json file, which is the manifest file and will contain the dependencies and configuration for the project, thus initializing a new Node.js Project. The -y flag automatically accepts all standard input, making for a basic configuration:

npm init -y

Step 3: Installing Express.js

Now, install Express.js, which is flexible as well as a minimal Node.js web app framework. It offers robust features for web as well as mobile apps.  

npm install express
installing express js

Step 4: Creating the application file 

This creates an empty JavaScript file named app.js that will hold the main code for our application. For every Node.js application, it is a convention to have a main file, which is the entry point to the application:

touch app.js
Creating the application file 

Step 5: Adding the code to app.js

This is the code for creating a simple web server using Express.js:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
  res.send('Hello from Node.js in Docker on Ubuntu 24.04!');
});
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Adding the code to app.js

Step 6: Testing the application locally

This command runs your node application without Docker on your machine to check that it works correctly:

node app.js
Testing the application locally

Once the application is running, navigate to http://localhost:3000 in your browser, and you will see the message “Hello from Node.js in Docker!”.

output message localhost

Dockerize the Node.js Application

Now, let’s containerize our Node.js application:

Step 1: Create a Dockerfile

Now, create a new Docker file for Node JS application with no extension, simply named Dockerfile. As a text document, a Dockerfile contains all the instructions that Docker needs to build the image of an application:

touch Dockerfile
create a dockerfile

Step 2: Adding content to the Dockerfile

Now, add the below content inside the created Dockerfile:

FROM node:20-slim
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
Adding content to the Dockerfile

Step 3: Creating a .dockerignore file

Now, create a file named “.dockerignore”. This file works like “.gitignore”, but for Docker. It adds files and folders that you do not want to copy when building files into the Docker image:

touch .dockerignore
Creating a .dockerignore file

Step 4: Adding entries to .dockerignore

In this step, each line represents the files or folders that do not need to be added in the building of the particular Node Docker image:

node_modules
npm-debug.log
Dockerfile
.dockerignore
.git
.gitignore
Adding entries to .dockerignore

The above entries make sure the Docker image does not contain extra files.

Building and Running the Docker Container

In this final section, we build and run the Docker container:

Step 1: Building the Specific Docker image

Now, utilize the below command to build a Node JS Docker image from the instructions specified in the Dockerfile:

docker build -t nodejs-app .
Building the Specific Docker image

During the build process, see each step executed along with the corresponding output/messages.

Step 2: Running the Docker container

To start or create a container from the image you created, use this command:

docker run -p 3000:3000 -d --name my-nodejs-app nodejs-app
Running the Docker container

Step 3: Verifying the container is running

This command reviews all currently running containers:

docker ps
Verifying the container is running

If your container is running all right, you should find, surprisingly, “my-nodejs-app” on the list.

Step 4: Testing the Containerized Application

Using the browser, go to http://localhost:3000. The output will still be the same; however, it will now be coming from the Docker container:

Testing the Containerized Application

This serves as a confirmation that the Node.js application is executing in the Docker container and responds correctly to requests coming from the host machine. The application is encapsulated, portable, and can be deployed with ease to any system that supports Docker.

Final Words

Build and run applications with ease using Docker containers. Docker simplifies the workflow of developers, designers, and engineers working in the same or associated teams, enabling smooth collaborations regardless of location or system. Following this guide improves your enterprise application development, deployment, and operations.

Deploy Docker on UltaHost’s DDoS-protected VPS Hosting to easily build Node.js apps and streamline your workflows. Enjoy ultra-fast SSD NVMe storage, DDoS protection up to 3500+ Gbps, and lightning-fast server deployment at a competitive price. Safeguard your business or online service with our top-tier firewalls!

FAQ

What are the advantages of running a Node.js app on Docker?
What should my Dockerfile include for a basic Node.js app?
How do I optimize my Docker image size for a Node.js app?
What’s the best way to handle environment variables in a Dockerized Node.js app?
How do I persist data when running a Node.js app in Docker?
What are the best practices for containerizing a Node.js app?
How do I debug a Node.js app running in Docker?

Related Post

How to Set Up Laravel in Docker

Laravel is a PHP based web framework known for its clea...

How to Set Up and Use Private Docker Registry

Setting up a private Docker registry can significantly ...

How to Install GraphQL in Node JS

GraphQL is a tool for APIs that lets clients request on...

How to Share Data Between Docker Containers

Docker is a containerization platform that enables us t...

How to Limit Docker Memory and CPU Usage

Docker is a powerful tool that simplifies software deve...

How to Install PHP Dependencies on Docker

As a web developer, you're likely no stranger to the im...

Leave a Comment