Multi-stage Dockerization of MEAN Application

Multi-stage Dockerization of MEAN Application

Multi-stage builds in Docker help create smaller Docker images. They split the build environment from the runtime environment. This means the final image doesn't have unnecessary build artifacts and dependencies. Here's an example of a multi-stage Dockerfile for a MEAN (MongoDB, Express.js, Angular, Node.js) application:

# Stage 1: Build Angular App
FROM node:14 as build-angular
WORKDIR /app
COPY ./angular-app /app
RUN npm install
RUN npm run build

# Stage 2: Build Node.js Server
FROM node:14 as build-node
WORKDIR /app
COPY ./node-server /app
RUN npm install

# Stage 3: Create Final Image
FROM node:14

# Set environment variables for Node.js server
ENV NODE_ENV production
ENV PORT 3000

WORKDIR /app

# Copy build artifacts from previous stages
COPY --from=build-angular /app/dist /app/dist
COPY --from=build-node /app /app

# Expose port for Node.js server
EXPOSE 3000

# Command to start Node.js server
CMD ["node", "server.js"]

In this example:

  • Stage 1 (build-angular):

    • Uses a Node.js base image to build the Angular application.

    • Copies the Angular app source code into the image.

    • Installs npm dependencies and runs the Angular build process (npm run build).

    • The resulting build artifacts are stored in the /app/dist directory.

  • Stage 2 (build-node):

    • Uses another Node.js base image for building the Node.js server.

    • Copies the Node.js server source code into the image.

    • Installs npm dependencies.

  • Stage 3 (Final Image):

    • Uses a clean Node.js base image for the final production image.

    • Sets environment variables for the Node.js server (e.g., NODE_ENV, PORT).

    • Copies the build artifacts from both previous stages into the final image.

    • Exposes the port on which the Node.js server will run.

    • Specifies the command to start the Node.js server.

When making the Docker image, the build process only adds the necessary parts and dependencies for the final production image. This makes the Docker image safer and more efficient. Remember to change the paths and commands based on your MEAN application's structure.

Did you find this article valuable?

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