DEV Community

Cover image for How to Dockerize Your Node.js App in Minutes
Abhishek Yadav
Abhishek Yadav

Posted on

How to Dockerize Your Node.js App in Minutes

Prerequisites

Before we begin, make sure you have Docker installed on your development machine. You can download and install Docker Desktop from the official Docker website here for your operating system.

Once Docker is installed, ensure that you have a working Node.js application that you want to dockerize.
You can clone this repo to get started this is simple node-app here

Setting Up Dockerfile

The first step in dockerizing your Node.js application is creating a Dockerfile. This file contains instructions for building a Docker image that encapsulates your application and its dependencies.
Create a dockerfile in your node-app directory.

Here's a simple Dockerfile to get you started:

# Use the official Node.js image based on Alpine Linux with the latest LTS version
FROM node:alpine

# Set the working directory inside the container
WORKDIR .

# Copy package.json and package-lock.json to the working directory
COPY package.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY . .

# Expose the port the app runs on
EXPOSE 3000

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

Enter fullscreen mode Exit fullscreen mode

Building Your Docker Image

Once you've created your Dockerfile, it's time to build your Docker image. Open a terminal or command prompt, navigate to the directory containing your Node.js application and Dockerfile, and run the following command
You can specify your image name using the -t flag.

docker build -t your-image-name .

Running Your Docker Container

With your Docker image built, you can now run a Docker container based on that image. Use the following command
docker run -p 4000:5000 your_image_name

This command will start a container from your image and map port 5000 of the container to port 4000 on your host machine, allowing you to access the application via
http://localhost:4000
Regardless of the EXPOSE settings, you can override them at runtime by using the -p as we are doing in the command.

Congratulations! You've successfully dockerized your Node.js application.

Top comments (0)