How to Deploy a Node.js Application with Docker: Step-by-Step Tutorial

Deploying a Node.js application with Docker involves creating a `Dockerfile`, building an image, and running a container. This end-to-end tutorial walks you through containerizing your Node.js app, optimizing the build process, and deploying it to production. By the end, you’ll have a fully Dockerized Node.js service that’s portable, scalable, and easy to manage.

Docker simplifies dependency management, eliminates “it works on my machine” issues, and streamlines deployment across environments. Whether you’re using Express, NestJS, or a plain Node server, this guide applies universally.

Docker and Node.js logos side by side, representing containerized deployment

Photo by Markus Winkler on Pexels

## Prerequisites

Before starting, ensure you have:

  • Node.js (v18 or later) installed locally
  • Docker Desktop or Docker Engine installed
  • A basic Node.js application (we’ll use a simple Express server as an example)
  • Basic familiarity with terminal commands

### Sample Node.js App

Create a minimal Express server:

“`javascript

// app.js

const express = require(‘express’);

const app = express();

const PORT = process.env.PORT || 3000;

app.get(‘/’, (req, res) => res.send(‘Hello from Docker!’));

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

“`

Add a `package.json` with `express` as a dependency.

## Step 1: Create a Dockerfile

The Dockerfile is a text file containing instructions to build your container image. Place it in your project’s root directory.

### Basic Dockerfile for Node.js

“`dockerfile

# Use official Node.js runtime as base image

FROM node:18-alpine

# Set working directory inside container

WORKDIR /usr/src/app

# Copy package files first (for caching)

COPY package*.json ./

# Install dependencies

RUN npm ci –only=production

# Copy application code

COPY . .

# Expose the port your app runs on

EXPOSE 3000

# Command to run the app

CMD [“node”, “app.js”]

“`

Key points:

  • `node:18-alpine` is a lightweight base image (~130MB)
  • `npm ci` is faster and stricter than `npm install`
  • Copy `package*.json` before the app code to leverage Docker’s layer caching

## Step 2: Build the Docker Image

Run this command in your project directory:

“`bash

docker build -t my-node-app .

“`

Flags explained:

  • `-t my-node-app` tags the image with a name
  • `.` refers to the current directory (build context)

After building, verify the image exists:

“`bash

docker images

“`

You should see `my-node-app` listed with a size around 200MB.

Terminal output showing successful Docker image build with layers

Photo by Wolfgang Weiser on Pexels

## Step 3: Run the Container

Start a container from your image:

“`bash

docker run -d -p 3000:3000 –name node-container my-node-app

“`

Breakdown:

  • `-d` runs in detached mode (background)
  • `-p 3000:3000` maps host port 3000 to container port 3000
  • `–name node-container` gives your container a friendly name

Visit `http://localhost:3000` in your browser. You should see “Hello from Docker!”.

### Useful Docker Commands

Command Purpose
`docker ps` List running containers
`docker stop node-container` Stop the container
`docker start node-container` Restart a stopped container
`docker logs node-container` View application logs
`docker exec -it node-container sh` Access container shell

## Step 4: Optimize the Dockerfile (Production Ready)

The basic Dockerfile works but can be improved for security, speed, and size.

### Multi-Stage Build

“`dockerfile

# Stage 1: Build

FROM node:18-alpine AS builder

WORKDIR /app

COPY package*.json ./

RUN npm ci

COPY . .

RUN npm run build # if you have a build script

# Stage 2: Production

FROM node:18-alpine

WORKDIR /usr/src/app

COPY –from=builder /app/dist ./dist

COPY package*.json ./

RUN npm ci –only=production

EXPOSE 3000

CMD [“node”, “dist/app.js”]

“`

Benefits:

  • Final image contains only runtime files (no dev dependencies)
  • Smaller attack surface
  • Faster deployment

### Use .dockerignore

Create a `.dockerignore` file to exclude unnecessary files:

“`

node_modules

.git

*.md

.gitignore

Dockerfile

.dockerignore

“`

This reduces build context size and speeds up builds.

Comparison diagram of single-stage vs multi-stage Docker build sizes

Photo by RDNE Stock project on Pexels

## Step 5: Use Docker Compose (Optional but Recommended)

For applications with multiple services (e.g., Node.js + MongoDB), Docker Compose simplifies orchestration.

Create a `docker-compose.yml` file:

“`yaml

version: ‘3.8’

services:

app:

build: .

ports:

  • “3000:3000”

environment:

  • NODE_ENV=production
  • DB_HOST=mongo

depends_on:

  • mongo

mongo:

image: mongo:6

volumes:

  • mongo-data:/data/db

volumes:

mongo-data:

“`

Run everything with:

“`bash

docker-compose up -d

“`

Pro tip: Use environment variables for configuration instead of hardcoding values.

## Step 6: Deploy to Production

Once your Docker image is ready, push it to a registry and deploy.

### Push to Docker Hub

“`bash

docker tag my-node-app yourusername/my-node-app:latest

docker push yourusername/my-node-app:latest

“`

### Deploy on a Server

SSH into your server and run:

“`bash

docker pull yourusername/my-node-app:latest

docker run -d -p 80:3000 yourusername/my-node-app

“`

For zero-downtime deployments, consider using Docker Swarm or Kubernetes.

## Common Pitfalls & How to Avoid Them

  • Forgot to include .dockerignore → Your image becomes bloated with `node_modules`
  • Using `npm install` instead of `npm ci` → Slower builds and potential version inconsistencies
  • Hardcoding ports → Use environment variables (`process.env.PORT`)
  • Running as root → Add `USER node` in your Dockerfile for security
  • Not using health checks → Add `HEALTHCHECK` instruction to monitor app status

## Conclusion

You’ve successfully deployed a Node.js application with Docker. From writing a Dockerfile to running containers and optimizing for production, this workflow ensures your app runs consistently across any environment. Docker eliminates deployment friction and gives you full control over your application’s runtime.

Ready to take your DevOps skills further? Visit freeresource.store for exclusive access to premium Docker templates, pre-built Node.js images, and open-source deployment scripts. Join our membership community and accelerate your containerization journey today!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *