How to Containerize a Node.js App with Docker

Containerizing your Node.js application with Docker ensures consistent environments across development, testing, and production. This guide provides a straightforward, step-by-step walkthrough on how to package a Node.js application into a lightweight Docker container. You will learn how to write a Dockerfile, ignore unnecessary files, and build and run your containerized application.

Step 1: Create a .dockerignore File

Before writing your Dockerfile, create a .dockerignore file in the root directory of your project. This prevents large or sensitive files, such as local dependencies and log files, from being copied into your Docker image.

Create a file named .dockerignore and add the following lines:

node_modules
npm-debug.log

Step 2: Create the Dockerfile

A Dockerfile is a text document containing the instructions Docker uses to build your image. Create a file named Dockerfile (with no file extension) in your project root and add the following configuration:

# Use the official Node.js runtime as a parent image
FROM node:18-alpine

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json first to leverage Docker's cache
COPY package*.json ./

# Install application dependencies
RUN npm install

# Copy the rest of the application source code
COPY . .

# Expose the port your app runs on
EXPOSE 3000

# Define the command to run your app
CMD [ "node", "index.js" ]

Step 3: Build the Docker Image

With your Dockerfile configured, you can now build the Docker image. Open your terminal, navigate to your project directory, and run the following command:

docker build -t my-node-app .

Step 4: Run the Docker Container

Once the build process is complete, you can start a container based on your new image using the docker run command:

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

Your Node.js application is now containerized and running inside Docker. You can access it by navigating to http://localhost:3000 in your web browser.