Containerizing a Node.js Web Application with Docker: A Step-by-Step Guide

Containerizing a Node.js Web Application with Docker: A Step-by-Step Guide

Containerizing your Node.js application with Docker offers numerous benefits. It allows you to package your application with its dependencies and runtime into a consistent, reproducible environment that can be deployed anywhere Docker is supported. In this guide, we will walk you through the process of containerizing a Node.js web application using Docker.

Step 1: Create a Dockerfile

To start, create a new file named Dockerfile in the root directory of your project. This file will contain the instructions for building your Docker image.

FROM node:18.0.0

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["node", "src/index.js"]

This Dockerfile uses the official Node.js 18.0.0 image, sets the working directory, copies the package files, installs dependencies, copies the rest of the application code, exposes port 3000, and runs the start command.

Step 2: Build the Docker Image

Next, navigate to the directory containing your Dockerfile and run the following command to build the Docker image:

docker build -t my-node-app .

This command builds an image named my-node-app using the current directory as the build context.

Step 3: Run the Application in a Docker Container

To run your application in a Docker container, use the following command:

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

This command runs the my-node-app image in a container, mapping port 3000 on the host to port 3000 in the container.

Step 4: Access Your Application

Open a web browser and navigate to http://localhost:3000 to view your running Node.js application inside the Docker container.

Step 5: Run the Container in the Background

To run the container in the background, add the -d flag:

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

This command runs the container detached from the terminal.

Step 6: Stop the Running Container

To stop the running container, get the container ID and use docker stop:

docker stop <container-id>

This command will stops the running container.