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:
FROM node:14 AS build
: This sets the base image for the build stage as Node.js version 14.WORKDIR /app
: This sets the working directory inside the container to/app
.COPY package*.json ./
: This copies thepackage.json
andpackage-lock.json
files from the host machine to the working directory inside the container.RUN npm install
: This installs the dependencies specified in thepackage.json
file.COPY . .
: This copies the entire source code of the application from the host machine to the working directory inside the container.RUN npm run build
: This runs the build command specified in thepackage.json
file to build the application.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.WORKDIR /app
: This sets the working directory inside the container to/app
.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.COPY --from=build /app/node_modules ./node_modules
: This copies thenode_modules
directory from the build stage to the/app/node_modules
directory inside the final stage container.EXPOSE 3000
: This exposes port 3000, if the application listens on that port.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.