Multi-stage Dockerization of MEVN Application

Multi-stage Dockerization of MEVN Application

Multi-stage Docker builds help create smaller Docker images by separating the build environment from the runtime environment. This is useful for MEVN (MongoDB, Express.js, Vue.js, Node.js) apps, as development and production may require different dependencies.

Here's a basic example of a multi-stage Dockerfile for a MEVN application:

# Stage 1: Build stage
FROM node:14 AS build
WORKDIR /app

# Copy package.json and package-lock.json separately
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code
COPY . .

# Build the Vue.js frontend
RUN npm run build

# Stage 2: Production stage
FROM node:14-alpine
WORKDIR /app

# Copy only the necessary files from the build stage
COPY --from=build /app/dist ./dist
COPY --from=build /app/server ./server

# Install only production dependencies
COPY --from=build /app/package*.json ./
RUN npm install --only=production

# Expose the port used by the application
EXPOSE 3000

# Start the application
CMD ["npm", "start"]

In this example:

  • Build Stage (node:14):

    • Installs dependencies.

    • Copies and builds the Vue.js frontend.

    • This stage is only used for building, and the resulting artifacts are stored in the /app/dist directory.

  • Production Stage (node:14-alpine):

    • Uses a lightweight Alpine-based Node.js image for production.

    • Copies only the necessary files from the build stage, including the built Vue.js files and the server code.

    • Installs only production dependencies to keep the image size small.

    • Exposes the port used by the application.

    • Defines the default command to start the application.

To build the Docker image, run the following command:

docker build -t your-image-name .

To run the Docker container:

docker run -p 3000:3000 your-image-name

Make sure to update the Dockerfile to fit your MEVN app's structure. Also, change the commands for building and starting your app according to your project's setup. This example uses a typical Vue.js app structure with a dist folder for the built frontend and a server folder for the server-side code. Adjust the paths as needed for your project structure.

Did you find this article valuable?

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