Project-08: Step-by-Step Guide to Containerizing a MERN Stack App Using Docker

Project-08: Step-by-Step Guide to Containerizing a MERN Stack App Using Docker

Step 1: Create a Docker Network

A Docker network is needed to enable communication between the frontend, backend, and MongoDB containers.

GitHub Repository:
https://github.com/PakeezaPakeeza/mern-stack-simple-app.git

Command:

docker network create mern-nw

Step 2: Build and Run the Frontend

Build the Frontend

Navigate to your frontend directory and build the Docker image:

cd mern/frontend
docker build -t mern-frontend .

Run the Frontend

Start the frontend container, attaching it to the mern-nw network:

docker run --name=frontend-cont --network=mern-nw -d -p 5173:5173 mern-frontend

Verify the Frontend

Open your browser and visit:

http://localhost:5173

Step 3: Run the MongoDB Container

Run MongoDB

Start the MongoDB container, attach it to the mern-nw network, and persist its data using a local volume:

docker run --network=mern-nw --name mongodb -d -p 27017:27017 -v ~/opt/data:/data/db mongo:latest

Step 4: Build and Run the Backend

Build the Backend

Navigate to your backend directory and build the Docker image:

cd mern/backend
docker build -t mern-backend .

Run the Backend

Start the backend container and attach it to the mern-nw network:

docker run --name=backend-cont --network=demo -d -p 5050:5050 mern-backend

Step 5: Verify the Application

Test the Frontend

Open your browser and access the frontend:

http://localhost:5173

Check the Backend Logs

Ensure the backend is running and connected to MongoDB by viewing its logs:

docker logs backend

Test the Backend API

Use tools like Postman, Curl, or your browser to test the backend API:

http://localhost:5050

Troubleshooting: getaddrinfo ENOTFOUND mongodb

Cause:

The backend container couldn't resolve the hostname mongodb. This typically happens when the MongoDB container's name does not match the expected hostname in the backend configuration.

Quick Solution:

  1. Ensure the MongoDB container name matches the hostname used in the backend connection string (mongodb://mongodb:27017/...).

    • Example: Rename or start the MongoDB container as mongodb instead of mongodb-cont:

        docker run --name mongodb --network mern-nw -d -p 27017:27017 mongo:latest
      

Simplify with Docker Compose

To streamline the process, use Docker Compose to build and run all the services (frontend, backend, MongoDB) together. Ensure your docker-compose.yaml file is located in repository.

Command:

    docker compose up -d