On this page
- What does the finished layout look like?
- How do you install MongoDB?
- How do you lock MongoDB down?
- How do you set up the Express API?
- How do you build the React front end?
- How do you configure Nginx for the SPA and the API?
- How do you secure it with a firewall and HTTPS?
- How do you check, update and back it up?
- Questions
What does the finished layout look like?
Everything runs on one instance. MongoDB listens on localhost only. The Node.js API listens on localhost port 5000. React is not a running process in production at all: it becomes a folder of static HTML, JavaScript and CSS that Nginx serves. Nginx is the only service on the public ports.
browser --> Nginx :443 --> / static React build (/var/www/shop)
--> /api/* 127.0.0.1:5000 Express under PM2
--> 127.0.0.1:27017 MongoDBThe commands here target Ubuntu 24.04 and Debian 12, where the MongoDB repository is supported. MongoDB 5.0 and newer need a CPU with AVX on x86; check with grep -m1 -o avx /proc/cpuinfo before you start. For memory, 2 GB is a sensible floor because the WiredTiger cache and a React build both want room.
How do you install MongoDB?
Add the MongoDB signing key and the repository for your release, then install the server package.
sudo apt install -y gnupg curl
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
# Ubuntu 24.04
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
# Debian 12
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.0 main" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable --now mongod
mongosh --eval "db.runCommand({ ping: 1 })"The ping should return ok: 1. Rocky, Alma and more options such as replica sets are covered on the MongoDB guide.
How do you lock MongoDB down?
Create an administrator and an application user, then switch on authorization. The default config already binds to 127.0.0.1; leave it that way.
mongosh
use admin
db.createUser({ user: "admin", pwd: passwordPrompt(), roles: ["root"] })
use shop
db.createUser({ user: "shopapp", pwd: passwordPrompt(), roles: [{ role: "readWrite", db: "shop" }] })
exitEdit /etc/mongod.conf and add:
security:
authorization: enabledsudo systemctl restart mongod
mongosh -u shopapp -p --authenticationDatabase shop shop --eval "db.stats()"The app connects with a URI like mongodb://shopapp:PASSWORD@127.0.0.1:27017/shop?authSource=shop. If the password contains special characters, percent-encode them in the URI.
How do you set up the Express API?
Install Node.js LTS (see installing Node.js and npm), clone your repository as deploy, and keep secrets in an environment file that git ignores.
cd ~/apps
git clone https://git.example.net/team/shop.git
cd shop/server
npm ci --omit=dev
cat > .env <<'EOF'
NODE_ENV=production
PORT=5000
MONGO_URI=mongodb://shopapp:PASSWORD@127.0.0.1:27017/shop?authSource=shop
JWT_SECRET=change-me-to-a-long-random-string
EOF
chmod 600 .envA minimal index.js that uses Mongoose and listens on loopback looks like this:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.set("trust proxy", "loopback");
app.use(express.json());
app.get("/api/health", async (req, res) => {
res.json({ db: mongoose.connection.readyState === 1 ? "up" : "down" });
});
mongoose.connect(process.env.MONGO_URI).then(() => {
app.listen(process.env.PORT, "127.0.0.1");
});Start it with PM2 so it survives crashes and reboots, letting Node load the env file itself:
pm2 start index.js --name shop-api --node-args="--env-file=.env"
pm2 saveThe boot setup is on the PM2 page. --env-file is built into current Node.js lines.
How do you build the React front end?
Build on the server or in CI, and copy only the output to a web folder. With a Vite-based client the output goes to dist; Create React App projects use build.
cd ~/apps/shop/client
npm ci
VITE_API_URL=/api npm run build
sudo mkdir -p /var/www/shop
sudo rsync -a --delete dist/ /var/www/shop/Use a relative API path such as /api in the client so it calls the same domain, which avoids CORS entirely. Variables baked into a front-end build are public, so never put secrets there. The build is the most memory-hungry step; if it gets killed on a small instance, add a swap file as described in creating a swap file.
How do you configure Nginx for the SPA and the API?
Serve the build as the document root, send unknown paths to index.html so client-side routes work on reload, and proxy /api to Express.
server {
listen 80;
listen [::]:80;
server_name shop.example.net;
root /var/www/shop;
index index.html;
location /api/ {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /assets/ {
expires 30d;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri /index.html;
}
}Save it under /etc/nginx/sites-available/shop, link it into sites-enabled, then run sudo nginx -t and sudo systemctl reload nginx. Vite puts hashed files in /assets, which is why that folder can be cached for a long time.
How do you secure it with a firewall and HTTPS?
Open only SSH and web traffic, then add a certificate:
sudo ufw allow OpenSSH
sudo ufw allow "Nginx Full"
sudo ufw enable
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d shop.example.net --redirectPorts 5000 and 27017 must not appear in the rules. Confirm with sudo ss -ltnp that both listen on 127.0.0.1 only. Point the DNS name at the server first, as in setting DNS records.
How do you check, update and back it up?
Test from your own machine:
curl -I https://shop.example.net/
curl https://shop.example.net/api/healthYou want a 200 for the page and {"db":"up"} from the API. For a release, pull the code, rebuild the client, sync the files and reload the API without downtime:
cd ~/apps/shop && git pull
(cd server && npm ci --omit=dev)
(cd client && npm ci && npm run build && sudo rsync -a --delete dist/ /var/www/shop/)
pm2 reload shop-apiBack up the database with mongodump --uri "mongodb://admin@127.0.0.1:27017/?authSource=admin" --archive=/var/backups/shop-$(date +%F).gz --gzip on a schedule, and keep copies off the server. The optional daily backup add-on snapshots the whole disk, which is a good second layer.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
Questions about Deploy a MERN app
Should React run with npm start in production?
No. npm start runs a development server. Build once and let Nginx serve the static files; they need no Node process at all.
Can MongoDB run on Rocky Linux or AlmaLinux?
Yes, MongoDB publishes an RPM repository for RHEL 9 compatible systems. The other steps on this page are the same apart from using dnf and firewall-cmd.
Why does a page reload return 404 on a client route?
Nginx looks for a real file with that name. The try_files $uri /index.html line hands unknown paths back to React so its router can handle them.
How much RAM does a MERN server need?
For a small app, 2 GB covers MongoDB, Node.js and Nginx. MongoDB uses about half of the RAM minus 1 GB for its cache by default, so busier databases benefit from 4 GB or more.
Can I use a hosted database instead of local MongoDB?
Yes, set MONGO_URI to that database and skip the MongoDB install. Keep the connection over TLS and restrict access to the server IP.