multi stage node js dockerfile

Here is a multi-stage Node.js Dockerfile with explanations for each step:

# Stage 1: Build the application
FROM node:14 AS build

# Set the working directory inside the container
WORKDIR /app

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

# Install the dependencies
RUN npm install

# Copy the source code to the working directory
COPY . .

# Build the application
RUN npm run build

# Stage 2: Create a lightweight container to run the application
FROM node:14-alpine

# Set the working directory inside the container
WORKDIR /app

# Copy the built application from the previous stage
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules

# Expose a port (if required)
EXPOSE 3000

# Specify the command to run the application
CMD ["node", "dist/index.js"]

Explanation for each step:

  1. FROM node:14 AS build: This sets the base image for the build stage as Node.js version 14.
  2. WORKDIR /app: This sets the working directory inside the container to /app.
  3. COPY package*.json ./: This copies the package.json and package-lock.json files from the host machine to the working directory inside the container.
  4. RUN npm install: This installs the dependencies specified in the package.json file.
  5. COPY . .: This copies the entire source code of the application from the host machine to the working directory inside the container.
  6. RUN npm run build: This runs the build command specified in the package.json file to build the application.
  7. FROM node:14-alpine: This sets the base image for the final stage as Node.js version 14 with the Alpine Linux distribution, which is a lightweight version of Linux.
  8. WORKDIR /app: This sets the working directory inside the container to /app.
  9. COPY --from=build /app/dist ./dist: This copies the built application from the build stage to the /app/dist directory inside the final stage container.
  10. COPY --from=build /app/node_modules ./node_modules: This copies the node_modules directory from the build stage to the /app/node_modules directory inside the final stage container.
  11. EXPOSE 3000: This exposes port 3000, if the application listens on that port.
  12. CMD ["node", "dist/index.js"]: This specifies the command to run the application when the container starts.

This Dockerfile uses multi-stage builds to separate the build process from the final application runtime. The first stage builds the application and the second stage creates a lightweight container to run the built application. This approach helps reduce the final image size and eliminates the need to include build dependencies in the final image.