How to Dockerize a MERN Stack App (Node, React, MongoDB)
Docker Setup

How to Dockerize a MERN Stack App (Node, React, MongoDB)

Beginner’s Guide: How to Dockerize a MERN Stack App (Node, React, MongoDB)

Author
Richard Mendes
September 07, 2025 • 3 mins

Docker makes it easy to run your applications anywhere by packaging everything into containers. In this guide, I will Dockerize a MERN stack application step by step. starting with the frontend, then backend, and finally setting up docker-compose for the whole project.

Let’s start with the frontend. Inside your frontend folder, create a new file named Dockerfile and paste the following code:

FROM node:18.9.1

WORKDIR /app

COPY package.json .

RUN npm install

EXPOSE 5173

COPY . .

CMD ["npm", "run", "dev"]

Now that the frontend is dockerized, let’s move on to the backend.

Inside your backend folder, create a new file called Dockerfile and add the following code:

FROM node:18.9.1

WORKDIR /app

COPY package.json .

RUN npm install

COPY . .

EXPOSE 5050

CMD ["npm", "start"]

At this point, you have two separate Dockerfiles (one for frontend and one for backend). Running them manually with multiple docker run commands can be messy. This is where Docker Compose makes life easier, it lets you define and run multi-container apps in a single configuration file.

Inside the root of your project (same level as frontend and backend folders), create a new file called docker-compose.yml and add the following:

services:
backend:
build: ./project/backend
ports:
- "5050:5050"
networks:
- app_network
environment:
MONGO_URI: mongodb://mongo:27017/appdb
depends_on:
-mongodb

frontend:
build: ./project/frontend
ports:
- "5173:5173"
networks:
- app_network
environment:
REACT_APP_API_URL: http://backend:5050

mongodb:
image: mongo:latest
ports:
- "27017:27017"
networks:
- app_network
volumes:
- mongo-data:/data/db

networks:
app_network:
driver: bridge

volumes:
mongo-data:
driver: local # Persist MongoDB data locally

You can download the code here from my repository.

GitHub Link: https://github.com/richard9004/mern_stack_with_docker






Comments (0)

No comments yet. Be the first to comment!

Latest Articles