How To Build a Node.js Application with Docker

By Raman Kumar

Updated on Sep 05, 2024

In this tutorial, we guide how to build a Node.js application with Docker. You through the process of building a simple Node.js application that serves multiple pages using the Express framework. We'll structure the application with different routes, create HTML views for each page, and use Express to handle routing between them. Once the application is set up, we’ll take it a step further by containerizing it using Docker.

You’ll learn how to:

  • Set up a basic Node.js project with multiple routes.
  • Serve different HTML pages using Express.
  • Create a Dockerfile to containerize the Node.js application.
  • Build a Docker image for the app and run it in a container.

By the end of this tutorial, you’ll have a fully Dockerized Node.js application that can be deployed anywhere, including on cloud platforms or in a local environment.

Node.js is a popular, server-side runtime environment that allows developers to run JavaScript outside of a browser. It’s widely used to build fast, scalable web applications thanks to its non-blocking, event-driven architecture. In this tutorial, we’ll use Node.js along with Express, a minimal web framework for building APIs and web apps.

Docker is a powerful tool that allows developers to containerize applications. Containers are lightweight, stand-alone, and executable software packages that contain everything needed to run an application: code, libraries, runtime, and system tools. Using Docker ensures that your application can run consistently across different environments, which makes it a great choice for modern application development and deployment. In this post, we’ll show you how to package your Node.js application in a Docker container, making it easier to deploy and run in any environment.

Prerequisites

  • A Linux OS installed dedicated server or KVM VPS.
  • Basic knowledge of Linux commands.
  • Basic knowledge of Docker and Node.js

We have used Ubuntu 24.04 server for this tutorial. You can use any disto to perform this tutorial except, you need to check the Docker engine installation steps for your distro.

Build a Node.js Application with Docker

Step 1: Install Node.js

Execute following set of command to install the Node.js. These commands are copied from Node.js official website :

# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 20

# verifies the right Node.js version is in the environment
node -v # should print `v20.17.0`

# verifies the right npm version is in the environment
npm -v # should print `10.8.2`

Step 2: Create a Simple Node.js Application with Routes

2.1 Set Up the Project Directory

First, create a directory for your Node.js application:

mkdir node-docker-app
cd node-docker-app

2.2 Initialize the Node.js Project

Run the following command to initialize the Node.js project:

npm init -y

This command will create a package.json file.

2.3 Install Dependencies

Install Express, which we'll use to handle routing:

npm install express

2.4 Create Directory Structure

Now, create the following directory structure for the application:

mkdir routes views

Your project directory should look like this:

node-docker-app
├── routes
├── views
├── app.js
├── package.json

2.5 Create Views (HTML Pages)

In the views directory, create the HTML files that will be served for different routes.

Create index.html file

nano views/index.html

Add following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
</head>
<body>
    <h1>Welcome to the Home Page</h1>
    <p>This is the main page of our Dockerized Node.js application.</p>
    <a href="/about">Go to About Page</a>
</body>
</html>

Create about.html file

nano views/about.html

Add following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>About Page</title>
</head>
<body>
    <h1>About Us</h1>
    <p>This is the about page of our Node.js application running in a Docker container.</p>
    <a href="/">Go to Home Page</a>
</body>
</html>

2.6 Create Route Handlers

Next, create route handlers in the routes folder.

Create index.js file:

nano routes/index.js

Add following code:

const express = require('express');
const router = express.Router();
const path = require('path');

router.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../views/index.html'));
});

module.exports = router;

Create about.js file:

nano routes/about.js

Add following code:

const express = require('express');
const router = express.Router();
const path = require('path');

router.get('/about', (req, res) => {
    res.sendFile(path.join(__dirname, '../views/about.html'));
});

module.exports = router;

2.7 Create the Main Application File

In the root of your project, create the main application file app.js:

nano app.js

Add the following content to app.js:

const express = require('express');
const app = express();

// Import routers
const indexRouter = require('./routes/index');
const aboutRouter = require('./routes/about');

// Use routers
app.use('/', indexRouter);
app.use('/', aboutRouter);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

This file sets up the Express app, imports the routes, and starts the server.

Step 3: Install Docker Engine

Execute following set of command to install the Docker Engine. These commands are copied from Docker official documentation page:

# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add the repository to Apt sources:
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update

To install the latest version, run:

sudo apt-get install docker-ce

Step 4: Create a Dockerfile

To containerize the Node.js application, create a Dockerfile in the root directory of your project.

Define Dockerfile Instructions. Create Dockerfile :

nano Dockerfile

Add the following:

# Use the official Node.js image as the base
FROM node:20-alpine

# Set the working directory in the container
WORKDIR /app

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

# Install dependencies
RUN npm install

# Copy the rest of the application code to the container
COPY . .

# Expose the port the app runs on
EXPOSE 3000

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

Create a .dockerignore File. To optimize the build, create a .dockerignore file to prevent unnecessary files from being added to the Docker image:

nano .dockerignore

Add the following content to .dockerignore:

node_modules
npm-debug.log

Step 5: Build the Docker Image

Now, let's build the Docker image of your Node.js application. Run the following command from the root of your project directory:

docker build -t node-docker-app .
  • -t node-docker-multi-page-app tags the image with the name node-docker-multi-page-app.
  • The . specifies the current directory as the build context.

Step 6: Run the Docker Container

Once the Docker image is built, run a container using the following command:

docker run -d -p 3000:3000 --name node-app node-docker-app
  • -d runs the container in detached mode (in the background).
  • -p 3000:3000 maps port 3000 on your host to port 3000 on the container.
  • --name node-app gives the container a name for easy reference.

Step 7: Access the Application

Open your browser and navigate to http://server_ip:3000 to access the home page of your application. You should see the "Welcome to the Home Page" content. You can also visit the about page at http://server_ip:3000/about.

Step 8: Manage the Docker Container

Here are some commands to manage the container:

Stop the container:

docker stop node-app

Start the container:

docker start node-app

Remove the container:

docker rm -f node-app

Conclusion

You’ve now successfully seen how to build a Node.js application with Docker. We have created a multi-page Node.js application with Express, set up routing, and containerized the application using Docker. You can easily expand on this setup by adding more routes, middleware, and features, or deploying your Dockerized app