How to Dockerize a Node.js App for Production
Meta Description: Learn how to Dockerize a Node.js app for production step-by-step. This beginner-friendly guide helps junior developers and self-taught coders deploy their apps with ease.
🚀 Introduction
Docker is a game-changer for developers. It allows you to package your application and its dependencies into a lightweight, portable container—making it easier to deploy anywhere. If you’re a junior developer, student, or self-taught coder, this post will walk you through Dockerizing a Node.js app for production—step by step.
By the end of this tutorial, you’ll have a working Docker setup that runs your Node.js app like a pro.
🛠️ What You’ll Need
- Node.js installed
- Basic understanding of Node.js and Express
- Docker installed [Install Docker →]
- A simple Node.js project
📁 Step 1: Create a Simple Node.js App
Folder Structure:
my-node-app/
├── Dockerfile
├── package.json
├── package-lock.json
└── index.js
index.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello from Dockerized Node.js App!');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
package.json
{
"name": "my-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2"
}
}
Run npm install
to install dependencies.
🐳 Step 2: Write the Dockerfile
Now, let’s create a Dockerfile
to define how your app should be built inside a container.
Dockerfile
# Use official Node.js LTS base image
FROM node:20-alpine
# Set working directory
WORKDIR /app
# Copy package files first (for caching)
COPY package*.json ./
# Install dependencies
RUN npm ci --omit=dev
# Copy app files
COPY . .
# Expose port
EXPOSE 3000
# Start the app
CMD ["npm", "start"]
📝 Note: Using npm ci
and --omit=dev
improves performance and ensures only production dependencies are installed.
📦 Step 3: Create a .dockerignore File
Just like .gitignore
, Docker also supports .dockerignore
to avoid copying unnecessary files.
.dockerignore
node_modules
npm-debug.log
Dockerfile
.dockerignore
.git
This keeps your image lean and clean.
🧪 Step 4: Build the Docker Image
Run the following command in the root of your project:
docker build -t my-node-app .
-t
is used to name the image (tag).- The
.
tells Docker to look for the Dockerfile in the current directory.
🚀 Step 5: Run the Docker Container
Start the app inside a container:
docker run -d -p 8080:3000 my-node-app
-d
runs it in detached mode.-p
maps port 8080 on your machine to port 3000 in the container.
Now visit http://localhost:8080 and you’ll see your app running inside Docker! 🎉
Hi Everyone, please do not spam in comments.