Write down Docker Compose file for MERN application

Write down Docker Compose file for MERN application

A MERN (MongoDB, Express.js, React, Node.js) stack typically involves multiple services working together. Below is a basic Docker Compose file for a MERN application. This example assumes that you have a Node.js/Express backend, a React frontend, and a MongoDB database.

Create a directory structure for your MERN application:

/my-mern-app
|-- backend
|   |-- Dockerfile
|   |-- package.json
|   |-- server.js
|-- frontend
|   |-- Dockerfile
|   |-- package.json
|   |-- src
|-- docker-compose.yml

1. Backend Dockerfile (/my-mern-app/backend/Dockerfile):

FROM node:14

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 5000

CMD ["npm", "start"]

2. Backend package.json (/my-mern-app/backend/package.json):

{
  "name": "backend",
  "version": "1.0.0",
  "main": "server.js",
  "dependencies": {
    "express": "^4.17.1"
    // Add other dependencies as needed
  },
  "scripts": {
    "start": "node server.js"
  }
}

3. Backend server.js (/my-mern-app/backend/server.js):

const express = require('express');
const app = express();
const port = 5000;

app.get('/', (req, res) => {
  res.send('Hello from the backend!');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

4. Frontend Dockerfile (/my-mern-app/frontend/Dockerfile):

FROM node:14

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

5. Frontend package.json (/my-mern-app/frontend/package.json):

{
  "name": "frontend",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
    // Add other dependencies as needed
  },
  "scripts": {
    "start": "react-scripts start"
  }
}

6. Docker Compose file (/my-mern-app/docker-compose.yml):

version: '3'
services:
  backend:
    build:
      context: ./backend
    ports:
      - "5000:5000"

  frontend:
    build:
      context: ./frontend
    ports:
      - "3000:3000"
    depends_on:
      - backend

  mongo:
    image: mongo:latest
    ports:
      - "27017:27017"

In this setup:

  • The backend service builds and runs the Node.js/Express backend.

  • The frontend service builds and runs the React frontend. It depends on the backend service.

  • The mongo service uses the official MongoDB image.

To run the MERN application, navigate to the directory containing the docker-compose.yml file and run:

docker-compose up

Access the frontend at http://localhost:3000 and the backend at http://localhost:5000.

Did you find this article valuable?

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