NodeJS

Dockerizing a NodeJS Web Application


Dockerizing a NodeJS Web Application: Step-by-Step

NodeJS dependency management keeps your application running smoothly. Think of dependencies as the tools and building blocks your app needs to work. You update your phone apps pretty regularly; your NodeJS application's the same. These updates will make your app safe, stable, and up-to-date with the latest features. Read on to learn how to do this safely and avoid issues.

Why would I have to Dockerize My NodeJS App?

Before we dive into "how to do it", let us first have a high-level overview of "why to do it":

  • Portability: Docker containers are self-contained; therefore, they can be run on any machine that supports Docker, regardless of the OS or dependencies.
  • Consistency: Its dev, its staging, its prod env due to the same configuration.

 Prerequisites

Let's get started. Before we begin, we should have the following installed on your machine:

 

1. Setting up your NodeJS Application

Use the example from this step that you have some simple NodeJS app. If you haven't created any yet, here's a simple step to create one:

Initialize a NodeJS Project:

mkdir docker-node-appcd docker-node-appnpm init -yInstall Express (or any framework of your choice): npm install express

Create an app.js file: const express = require('express');

const app = express();const port = process.env.PORT || 3000;app.get('/', (req, res) => {  res.send('Hello, Dockerized NodeJS!');});app.listen(port, () => {  console.log(`Server running on port ${port}`);});

At this point, your NodeJS application is complete but remains to be Dockerized.

 

2. Creating a Dockerfile

 

A Dockerfile is what's called the script containing commands one needs to create a Docker image for your application.

Create a file called `Dockerfile` in the root of your project: # Use an official NodeJS runtime as a parent image

FROM node:20-alpine# Set the working directory inside the containerWORKDIR /usr/src/app# Copy package.json and package-lock.json into the working directoryCOPY package*.json ./# Install the dependenciesRUN npm install --legacy-peer-deps# Copy the rest of the application code to the working directoryCOPY . .# Expose the port on which the app will runEXPOSE 3000

# Command to run the app

CMD ["node", "app.js"]

What’s happening in the Dockerfile?

  • FROM node:20-alpine: We’re using the NodeJS 20 alpine image as our base image. (Note: Alpine images are much more smaller compared to regular images.)

  • WORKDIR /usr/src/app: It updates the working directory inside the container to /usr/src/app.

  • COPY package*.json ./: Copies the package.json and package-lock.json files to the container.

  • RUN npm install: Installs all the dependencies.

  • COPY . .: Copies the entire app code into the working directory.

  • EXPOSE 3000: Exposes port 3000 for the app (this should match the port used in your app).

  • CMD ["node", "app.js"]: Runs the app using NodeJS.

3. Creating a .dockerignore File

To avoid copying unnecessary files and folders (like node_modules and logs), we should create a .dockerignore file:

touch .dockerignoreAdd the following content:node_modulesnpm-debug.log

This ensures these files aren’t copied into the Docker image, keeping it lightweight.

4. Building the Docker Image

That's it! Now that we have our Dockerfile we can build the Docker image.

Build the Docker Image: docker build -t docker-node-app .

This command tells Docker to build an image named docker-node-app using the current directory (.).

Verify the Image: After the build is complete, run the following command to verify the image was created: docker images

5. Running the Docker Container

Now that the Docker image is ready, you can run the container.

Run the Container: docker run -p 3000:3000 docker-node-app

  1. This command:

    • -p 3000:3000: Maps port 3000 on your machine to port 3000 inside the container.

    • docker-node-app: The name of the image we want to run.Access the Application: Open your browser and open http://localhost:3000. You should see a message "Hello, Dockerized Node.js!"

6. Optimizing the Dockerfile

To make the image even more efficient, we can apply a few optimizations:

1. Use Multi-Stage Builds for Smaller Images

Multi-stage builds allow you to separate the build and runtime stages, making your final image smaller by excluding unnecessary files.

2. Leverage .dockerignore to Exclude Files

Ensure that your .dockerignore file is updated to exclude any other unnecessary files, like test files or configuration files meant for local development.

7. Pushing Your Docker Image to Docker Hub (Optional)

If you want to share your image or deploy it, you can push it to Docker Hub.

Login to Docker Hub:

 docker login

Tag Your Image: docker tag docker-node-app your-dockerhub-username/docker-node-app

Push the Image: docker push your-dockerhub-username/docker-node-app

Once pushed, you can pull and run this image from anywhere using Docker.

Conclusion

Congratulations! You have successfully Dockerized your NodeJS application. Dockerizing an application makes it much easier to deploy and manage in different environments. You can now scale it, replicate it on multiple servers, or even push for production builds with ease.

And now, with this tutorial, you have opened the first door to mastering containerization for your NodeJS applications. Docker is an extremely powerful tool for developers and doesn't have to be really intimidating you need to wait and see! Happy coding! 

Ready to transform your business with our technology solutions?   Contact Us today to Leverage Our NodeJS Expertise.


NodeJS

Related Center Of Excellence