Multi-stage Dockerization of MERN Application

Multi-stage Dockerization of MERN Application

Multi-stage Docker builds are useful for putting applications into Docker, as they separate the build environment from the runtime environment. This helps make the final Docker image smaller. Here's an example of a multi-stage Dockerfile for a MERN (MongoDB, Express.js, React, Node.js) application:

# Stage 1: Build the React App
FROM node:14 as build
WORKDIR /app/client

# Copy only the necessary files for npm install
COPY client/package*.json ./
RUN npm install

# Copy the rest of the application files
COPY client/ ./

# Build the React app
RUN npm run build

# Stage 2: Create the Node.js Express Server
FROM node:14-alpine
WORKDIR /app/server

# Copy package.json and package-lock.json to install dependencies
COPY server/package*.json ./
RUN npm install --production

# Copy the built React app from the previous stage
COPY --from=build /app/client/build /app/client/build

# Copy the server files
COPY server/ ./

# Expose the port that the Node.js app will run on
EXPOSE 5000

# Start the Node.js server
CMD ["npm", "start"]

Explanation:

  1. Stage 1: Build the React App

    • Use an official Node.js image as the build environment.

    • Set the working directory to the client directory.

    • Copy only the necessary package files for npm install to take advantage of Docker caching when dependencies haven't changed.

    • Copy the rest of the client application files.

    • Run npm install and build the React app.

    • The result is a production-ready build of the React app in the /app/client/build directory.

  2. Stage 2: Create the Node.js Express Server

    • Use a smaller Node.js Alpine image for the runtime environment.

    • Set the working directory to the server directory.

    • Copy the package files to install production dependencies.

    • Run npm install --production to install only the necessary dependencies for running the server in production.

    • Copy the built React app from the previous stage (/app/client/build) into the /app/client/build directory.

    • Copy the server files.

    • Expose the port that the Node.js app will run on (assumed to be 5000 in this example).

    • Define the default command to start the Node.js server.

This setup makes the Docker image better by getting rid of unneeded build parts and leftovers. This makes the final image smaller and safer. To use this Dockerfile, save it in the main folder of your MERN app and create the image with the docker build command:

docker build -t your-image-name .

Change your-image-name to a good name for your Docker image. After building the image, you can run a container using this image, and your MERN application should start working.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!