0
0
DockerHow-ToBeginner · 3 min read

How to Create Dockerfile for Node.js: Simple Guide

To create a Dockerfile for Node.js, start with an official Node base image, copy your app files, install dependencies with npm install, and define the command to run your app using CMD. This setup packages your Node.js app into a container for easy deployment.
📐

Syntax

A basic Dockerfile for Node.js includes these parts:

  • FROM: Specifies the base Node.js image.
  • WORKDIR: Sets the working directory inside the container.
  • COPY: Copies your app files into the container.
  • RUN: Runs commands like npm install to install dependencies.
  • EXPOSE: Declares the port your app listens on.
  • CMD: Defines the command to start your Node.js app.
dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
💻

Example

This example Dockerfile creates a container for a simple Node.js app that listens on port 3000. It uses a lightweight Node.js image, installs dependencies, copies the app code, and starts the app with node index.js.

dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
Output
When you build and run this Dockerfile, your Node.js app will start inside the container and listen on port 3000.
⚠️

Common Pitfalls

Common mistakes when creating a Dockerfile for Node.js include:

  • Not copying package.json and package-lock.json separately before running npm install, which prevents Docker from caching dependencies.
  • Forgetting to set the working directory with WORKDIR, causing files to copy to unexpected locations.
  • Not exposing the correct port your app listens on.
  • Using CMD with a shell string instead of JSON array, which can cause issues with signal handling.

Wrong way:

FROM node:18-alpine
COPY . .
RUN npm install
CMD ["node", "index.js"]

Right way:

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
📊

Quick Reference

Tips for creating Node.js Dockerfiles:

  • Use official Node images with specific versions (e.g., node:18-alpine) for stability.
  • Set WORKDIR to organize files inside the container.
  • Copy package.json and package-lock.json first to leverage Docker cache.
  • Expose the port your app uses with EXPOSE.
  • Use JSON array syntax in CMD for proper signal handling.

Key Takeaways

Start your Dockerfile with an official Node.js base image like node:18-alpine.
Copy package files and run npm install before copying the rest of your app for better caching.
Set WORKDIR to define where your app lives inside the container.
Expose the port your Node.js app listens on using EXPOSE.
Use CMD with JSON array syntax to start your app cleanly.