0
0
Node.jsframework~5 mins

Docker containerization for Node.js in Node.js

Choose your learning style9 modes available
Introduction

Docker helps you package your Node.js app with everything it needs to run. This makes it easy to run your app anywhere without setup problems.

You want to share your Node.js app with others and ensure it runs the same on their computers.
You need to deploy your Node.js app to a server or cloud without worrying about missing software.
You want to test your Node.js app in a clean environment that matches production.
You want to run multiple Node.js apps on one machine without conflicts.
You want to simplify updating your app by rebuilding and redeploying containers.
Syntax
Node.js
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]

FROM sets the base image with Node.js installed.

WORKDIR sets the folder inside the container where commands run.

Examples
Basic Dockerfile for a Node.js app named server.js.
Node.js
FROM node:18
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
CMD ["node", "server.js"]
Uses a smaller Alpine Linux image and installs only production packages.
Node.js
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 8080
CMD ["node", "app.js"]
Sample Program

This example shows a simple Node.js HTTP server and a Dockerfile to containerize it. When you build and run the Docker container, the server listens on port 3000 and responds with a friendly message.

Node.js
/* index.js */
const http = require('http');
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello from Dockerized Node.js!');
});

server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

/* Dockerfile */
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
OutputSuccess
Important Notes

Always include EXPOSE to tell Docker which port your app uses.

Use npm ci instead of npm install in production for faster, reliable installs.

Keep your Dockerfile simple and copy only needed files to reduce image size.

Summary

Docker packages your Node.js app and its environment together.

This makes your app easy to run anywhere without setup issues.

Use a Dockerfile to define how your Node.js app is built and run inside a container.