Skip to main content

Containerising a Three-Tier MERN E-Commerce App with Docker and Nginx

Published 6 min readMarkdown
Containerising a Three-Tier MERN E-Commerce App with Docker and Nginx

So far in this series, we’ve learned how to build Docker images, run containers, manage networks, use volumes, and simplify multi-container setups with Docker Compose.

Now, let’s put it all together into something real, a 3-tier e-commerce MERN application using Docker + Nginx.


What You’ll Learn

How to containerise a MERN (MongoDB, Express, React, Node js) app
Writing separate Dockerfiles for frontend and backend
How Docker Compose connects multi-container apps
Why you can’t directly access containerised apps via localhost
How Nginx solves this with reverse proxy and static serving


Application Overview

We’ll use a 3-tier e-commerce app consisting of:

LayerTechnologyPurpose
FrontendReact+Vite (client folder)Customer UI
BackendNode.js + Express (server folder)Business logic and API
DatabaseMongoDB Atlas (Cloud)Data storage
ProxyNginxHandles frontend + API routing

GitHub Repository:
https://github.com/papani-sivasai/three-tier-ecommerce


Why Do We Need Nginx?

Before we write any Dockerfiles, let’s address the most confusing part for beginners:

Why can’t my frontend reach the backend when both containers are running successfully?

The Problem Without Nginx

When both frontend (React) and backend (Express) run inside Docker:

  • The frontend container can talk to the backend container via Docker’s internal DNS (e.g., http://backend:5000).

  • But your browser (running on the host machine) doesn’t know that name it only knows localhost.

If your frontend tries to fetch data from http://backend:5000, you’ll get:

net::ERR_NAME_NOT_RESOLVED

Even if you expose ports and use 0.0.0.0, the browser can’t access container hostnames, leading to CORS, 404, or 502 errors.

The Problem Nginx Solves

Nginx acts as a reverse proxy and static file server, sitting in front of both your frontend and backend containers:

  • Serves your React app directly to the browser

  • Forwards /api requests to your backend container

  • Exposes a single entry point (http://localhost)

  • Eliminates CORS issues

Think of Nginx as the front door to your Dockerized application.


Architecture Diagram

This structure ensures:

  • The browser only talks to Nginx.

  • Nginx handles both static assets and API routes.

  • The backend connects to MongoDB Atlas securely via environment variables.


Understanding the Folder Structure

three-tier-ecommerce/
│
├── client/          # React frontend
│   ├── Dockerfile
│   ├── .dockerignore
│   └── ...
│
├── server/          # Express backend
│   ├── Dockerfile
│   ├── .dockerignore
│   └── ...
│
├── nginx/          # Nginx configuration
│   ├── nginx.conf
│
└── docker-compose.yml

Backend (server) — Dockerfile

Let’s start with the Express server.

# Use a lightweight Node base image
FROM node:18-alpine

# Set the working directory
WORKDIR /app

# Copy dependency files and install dependencies
COPY package*.json ./
RUN npm install

# Copy the source code
COPY . .

# Expose the server port
EXPOSE 5000

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

Explanation:

  • Using node:18-alpine keeps the image small.

  • Install dependencies first for caching efficiency.

  • The app listens on port 5000 inside the container.

Frontend (client) — Multi-Stage Dockerfile

React apps need to be built first and then served.
We’ll use a multi-stage build for efficiency.

# Stage 1: Build the app
FROM node:18-alpine AS build

# Set working directory
WORKDIR /app

# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install

# Copy the rest of the source code
COPY . .

# Build the project (creates /app/dist)
RUN npm run build

# Stage 2: Serve with Nginx
FROM nginx:alpine

# Remove default nginx static assets
RUN rm -rf /usr/share/nginx/html/*

# Copy built assets from the build stage
COPY --from=build /app/dist /usr/share/nginx/html

# Expose port 80
EXPOSE 80

# Start nginx
CMD ["nginx", "-g", "daemon off;"]

Explanation:

  • Stage 1 installs dependencies and builds the static React app.

  • Stage 2 copies the build output into an Nginx container to serve static files.

  • This avoids shipping Node.js in the final image. Image gets faster & smaller.


Nginx Configuration

Now let’s configure Nginx to:

  1. Serve the React frontend.

  2. Proxy API requests to the backend.

nginx/nginx.conf

server {
    listen 80;

    server_name localhost; # Chnage to https://example.com (if you are connecting to the production website)

    # Serve the React frontend
    location / {
        proxy_pass http://frontend:80;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_intercept_errors on;
        error_page 404 = /index.html;
        proxy_redirect off;
    }

    location = /index.html {
        proxy_pass http://frontend:80/index.html;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
    }

    # Proxy API requests to backend
    location /api {
        proxy_pass http://backend:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Docker Compose File

Finally, let’s connect it all with Docker Compose.

services:
  backend:
    build: ./server
    container_name: ecommerce-backend
    image: backend
    ports:
      - "5500:5500"
    env_file:
      - ./server/.env
    networks:
      - ecommerce-network
    restart: always

  frontend:
    build: ./client
    container_name: ecommerce-frontend
    image: frontend
    expose:
      - "80"     
    env_file:
      - ./client/.env
    depends_on:
      - backend
    networks:
      - ecommerce-network
    restart: always

  nginx:
    image: nginx:alpine
    container_name: ecommerce-nginx
    ports:
      - "80:80" 
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - frontend
      - backend
    networks:
      - ecommerce-network

networks:
  ecommerce-network:
    driver: bridge

Explanation:

  • All containers share the same network (ecommerce-network).

  • Nginx depends on both client and server.

  • Only port 80 is exposed to the host → the browser entry point.


Create .env file in the Server folder

Store sensitive credentials here.

# Database Configuration
MONGODB_URI=<Enter your mongo uri here>

# Server Configuration
PORT=5000
NODE_ENV=development

# JWT Configuration
JWT_SECRET=<Enter your jwt here>

# CORS Configuration
CLIENT_URL=http://localhost:5173

# Cloudinary Configuration (for image uploads)
CLOUDINARY_CLOUD_NAME=<Enter your cloud name here>
CLOUDINARY_API_KEY=<Enter your cloud API key here>
CLOUDINARY_API_SECRET=<Enter your cloud API secret here>

# PayPal Configuration (for payments)
PAYPAL_MODE=sandbox
PAYPAL_CLIENT_ID=<Enter your paypal client id here>
PAYPAL_CLIENT_SECRET=<Enter your paypal client secret here>

Create .env file in the client folder

CLIENT_URL=http://localhost:5173
VITE_API_BASE_URL=/api
VITE_NODE_ENV=development

Make sure you should never commit this .env file publicly.


Run Everything

Build and start all services:

docker compose up -d --build

You should see:

✔ Network ecommerce-network  Created
✔ Container ecommerce-backend Started
✔ Container ecommerce-frontend Started
✔ Container ecommerce-nginx  Started

Now open 👉 http://localhost

  • React app loads

  • API requests flow through Nginx

  • Backend connects to Mongo Atlas

  • No CORS errors or DNS issues


Wrap-Up

You’ve just containerised a 3-tier MERN app using everything learned so far:

  • Dockerfiles for frontend & backend

  • Docker Compose for orchestration

  • Shared network communication

  • Nginx reverse proxy as the single entry point

This setup isn’t just for development, it’s also a production-grade pattern used by most modern full-stack applications.


Coming Up Next: Docker Commands and Scenario based interview question and answers

In the next part of this series, we’ll list out all the important basic commands, trouble shooting commands, and scenario based interview question and answers.

Stay tuned..!! 🙂

For a Compose MERN stack the durable pattern is nginx as the only public listener, with the Node API and Mongo on an internal network only. Resolve upstreams by Compose service name, not published host ports — publishing the API or DB on the host can bypass ufw and widen the attack surface. Keep proxy_http_version 1.1 with Connection cleared for keepalive into Node, and forward Host plus X-Forwarded-For / X-Forwarded-Proto so the app sees the public scheme for absolute URLs and cookies.

Path joining still bites after containers come up: a trailing-slash mismatch between location and proxy_pass doubles or strips a prefix, so the SPA gets HTML for an API call or Node 404s a route it owns. After compose up I curl the API service name from the nginx container first, then the same path through published 80/443, and compare status timing. Stale resolved IPs after a recreate need a variable-plus-resolver pattern or a proxy recreate on deploy — most post-redeploy 502s are upstream DNS or path joining, not the Node image. Leave Mongo unpublished.