Deploying a MERN Stack Application on AWS EC2 with Nginx and PM2
Building a MERN stack application is only one part of delivering a production-ready product. Once the frontend and backend are complete, they need to be deployed, secured, monitored, and maintained.
For developers who want control over their infrastructure, Amazon EC2 provides a flexible environment for hosting Node.js applications.
However, simply uploading a project to an EC2 instance and running node server.js is not a complete production deployment.
A reliable setup needs a process manager, reverse proxy, HTTPS, environment configuration, firewall rules, database connectivity, logging, and a deployment strategy.
In this guide, we will deploy a React + Vite frontend and a Node.js + Express backend using:
- Amazon EC2: Hosts the backend application and optionally the frontend.
- Node.js: Runs the backend.
- Express.js: Handles API requests.
- MongoDB: Stores application data.
- PM2: Manages Node.js processes.
- Nginx: Handles reverse proxying and static file delivery.
- Certbot: Configures HTTPS certificates.
- Git: Manages application source code.
We will also discuss a separate frontend deployment using Amazon S3 and CloudFront.
1. Understanding the Deployment Architecture
Before creating an EC2 instance, understand how the application components communicate.
For a traditional single-instance deployment, the architecture looks like this:
Internet
|
Domain / DNS
|
Nginx
|
+----------+----------+
| |
Frontend Backend API
Static Files /api/*
| |
| localhost:5000
| |
| PM2
| |
| Express.js
| |
| MongoDB
| Atlas / Self-hosted
|
React + Vite
Nginx acts as the public entry point.
The frontend is served as static files, while API requests are forwarded to the Express application running on a private local port.
For example:
| Component | Address |
|---|---|
| Frontend | https://example.com |
| Backend API | https://api.example.com |
| Express internally | http://127.0.0.1:5000 |
| MongoDB Atlas | Remote database endpoint |
The Node.js application does not need to be directly exposed to the public internet.
Nginx receives external requests and forwards the relevant traffic to the backend.
This separation provides a cleaner deployment architecture and makes it easier to manage HTTPS, routing, and security.
2. Preparing the AWS EC2 Instance
First, create an EC2 instance through the AWS Management Console.
Open the Amazon EC2 dashboard and select Launch Instance.
2.1 Choose an Operating System
For this tutorial, we will use Ubuntu Server LTS.
Choose a supported Ubuntu LTS image available in your AWS region.
The exact image version may change, so use the current supported release rather than copying an outdated AMI identifier.
2.2 Select an Instance Type
Your instance type depends on the application's resource requirements.
For a small development or low-traffic application, a small general-purpose instance may be sufficient.
For production workloads, evaluate:
- CPU requirements.
- Available RAM.
- Expected traffic.
- Database connection count.
- Background jobs.
- WebSocket connections.
- Operating system overhead.
Do not choose an instance solely because it is inexpensive. Monitor actual resource usage and scale according to workload.
2.3 Configure Storage
Select an appropriate EBS volume.
Consider:
- Operating system requirements.
- Application dependencies.
- Log storage.
- Temporary build files.
- Deployment artifacts.
Monitor disk utilization because application logs and old deployment files can gradually consume available storage.
2.4 Create a Key Pair
Create an EC2 key pair and download its private key securely.
On Linux or macOS:
chmod 400 rjryt-server.pem
Do not upload your private key to GitHub or include it in your project.
2.5 Configure Security Groups
Security groups act as virtual firewalls for EC2 instances.
For a typical Nginx deployment, configure inbound rules similar to these:
| Type | Port | Source | Purpose |
|---|---|---|---|
| SSH | 22 | Your trusted IP | Server administration |
| HTTP | 80 | 0.0.0.0/0 | HTTP and certificate validation |
| HTTPS | 443 | 0.0.0.0/0 | Secure web traffic |
If IPv6 is enabled, configure the corresponding IPv6 rules as well.
Avoid exposing the Express port, such as 5000, directly to the internet.
SSH should ideally be restricted to a trusted IP address or accessed through AWS Systems Manager where appropriate.
Also consider using an Elastic IP or another stable public addressing arrangement if your DNS configuration requires a persistent address.
Official reference: AWS EC2 Security Groups.
3. Connecting to the EC2 Instance
After the instance is running, retrieve its public IP address or public DNS name.
Connect through SSH:
ssh -i rjryt-server.pem ubuntu@YOUR_EC2_PUBLIC_IP
The default username depends on the selected operating system image. For standard Ubuntu EC2 images, it is commonly ubuntu.
Once connected, update the package index and installed packages:
sudo apt update
sudo apt upgrade -y
Install basic utilities:
sudo apt install -y \
curl \
git \
unzip \
build-essential \
ca-certificates
It is also a good idea to verify that the system clock is synchronized and that the instance has sufficient disk space.
df -h
free -h
These commands help identify storage and memory constraints before deploying the application.
4. Installing Node.js
The backend requires Node.js to run.
Install a currently supported Node.js LTS release.
One convenient approach is to use Node Version Manager (NVM).
Install NVM using its official installation instructions:
After installation, load NVM into the current shell or reconnect to the instance.
Install the current Node.js LTS release:
nvm install --lts
nvm use --lts
nvm alias default 'lts/*'
Verify the installation:
node -v
npm -v
Using NVM allows you to manage Node.js versions without depending entirely on the operating system's package repository.
Remember that a deployment service or PM2 startup configuration must use the correct Node.js environment. If NVM changes the Node.js installation path, revisit the PM2 startup configuration.
5. Installing and Configuring MongoDB
A MERN application needs a MongoDB database.
There are two common deployment choices.
Option A: MongoDB Atlas
MongoDB Atlas is a managed database service.
With Atlas:
- Create a cluster.
- Create a database user.
- Configure network access.
- Obtain the connection string.
- Add the connection string to the backend environment variables.
For an EC2 deployment, prefer restricting Atlas network access to the instance's stable outbound IP where practical.
Avoid allowing access from every IP address in production.
Option B: Self-Hosted MongoDB
You can also install MongoDB directly on an EC2 instance.
However, this means you are responsible for:
- Database installation and upgrades.
- Authentication.
- Storage management.
- Backups.
- Monitoring.
- Replication.
- Recovery procedures.
- Security configuration.
For production applications requiring high availability, a single MongoDB process on the same EC2 instance introduces a significant availability and recovery risk.
For many applications, using a managed database is a simpler operational choice.
Official reference: MongoDB Atlas Documentation.
6. Preparing the MERN Backend
Now we can deploy the Express application.
Connect your backend repository to the EC2 instance.
Create an application directory:
mkdir -p ~/apps
cd ~/apps
Clone the repository:
git clone https://github.com/USERNAME/PROJECT.git backend
Enter the backend directory:
cd backend
Install production dependencies:
npm ci --omit=dev
If your project requires a build step, such as compiling TypeScript, perform that build using an appropriate deployment process with the required development dependencies available.
For example:
npm ci
npm run build
npm prune --omit=dev
The correct commands depend on the project's build scripts and runtime output.
Do not assume every Express project needs a build step.
6.1 Configure the Backend Port
Your Express application should listen on a configurable port.
import express from 'express'
const app = express()
const PORT = process.env.PORT || 5000
app.use(express.json())
app.get('/api/health', (req, res) => {
res.status(200).json({
success: true,
message: 'API is running',
})
})
app.listen(PORT, '127.0.0.1', () => {
console.log(`Server running on port ${PORT}`)
})
Binding to 127.0.0.1 is suitable for an application accessed only through a local Nginx reverse proxy.
If the application needs to accept connections from other private hosts or load balancers, configure the appropriate network interface and firewall rules instead.
For a single-instance deployment, keeping the Express port private is a useful security boundary.
7. Configuring Environment Variables
Production secrets should never be committed to the Git repository.
Create an environment file outside the publicly served frontend directory.
For example:
nano .env
Example contents:
NODE_ENV=production
PORT=5000
MONGODB_URI=mongodb+srv://USER:[email protected]/myapp
JWT_SECRET=YOUR_LONG_RANDOM_SECRET
CLIENT_URL=https://example.com
Use your actual database connection string and secrets.
Protect the file:
chmod 600 .env
Add .env to .gitignore:
.env
.env.*
!.env.example
Be careful not to commit production secrets through other configuration files or deployment artifacts.
Important: Vite Environment Variables Are Different
Vite exposes variables prefixed with VITE_ to frontend code.
For example:
VITE_API_URL=https://api.example.com
These variables are embedded into the frontend build.
They are not secret.
Never place database credentials, JWT signing secrets, private API keys, or other sensitive server-side values inside VITE_ variables.
The backend should read its secrets at runtime, while the frontend should contain only values that are safe to expose publicly.
8. Testing the Backend Locally on EC2
Before configuring PM2 and Nginx, test the application.
Start the backend:
npm start
If your project uses a different entry point, use the correct start command.
Open another SSH session and test the health endpoint:
curl http://127.0.0.1:5000/api/health
Expected response:
{
"success": true,
"message": "API is running"
}
If the request fails, inspect:
- Application logs.
- Database connectivity.
- Environment variables.
- Port configuration.
- File permissions.
- Missing dependencies.
Stop the manually started process after testing.
9. Installing and Configuring PM2
Running Node.js directly in an SSH terminal is not suitable for production.
If the SSH session closes or the process exits, your application may stop.
PM2 is a process manager for Node.js applications.
It helps with:
- Process monitoring.
- Automatic restarts after crashes.
- Application logs.
- Startup scripts.
- Cluster mode.
- Process management.
Install PM2 globally:
npm install -g pm2
9.1 Start the Application
For a simple application:
pm2 start server.js --name my-backend
Replace server.js with your actual entry point.
Check the process:
pm2 status
View logs:
pm2 logs my-backend
Restart:
pm2 restart my-backend
Stop:
pm2 stop my-backend
9.2 Use a PM2 Ecosystem File
For a more maintainable setup, create an ecosystem configuration file.
Create ecosystem.config.cjs:
module.exports = {
apps: [
{
name: 'my-backend',
script: './server.js',
cwd: '/home/ubuntu/apps/backend',
instances: 1,
exec_mode: 'fork',
autorestart: true,
watch: false,
max_memory_restart: '500M',
env_production: {
NODE_ENV: 'production',
PORT: 5000,
},
time: true,
},
],
}
Start the application:
pm2 start ecosystem.config.cjs --env production
This keeps process configuration in a reusable file.
The example uses one process. Do not automatically increase the instance count without checking memory, CPU, database connection capacity, and application behavior.
9.3 Configure PM2 Startup
PM2 should automatically restore managed processes after an EC2 reboot.
Generate a startup script:
pm2 startup
PM2 prints a command that must be executed with elevated privileges.
Copy and run the exact command generated for your instance.
Then save the current process list:
pm2 save
Verify the setup by restarting the instance during a suitable maintenance window:
sudo reboot
Reconnect and check:
pm2 status
Official references:
10. Installing Nginx
Nginx will receive public HTTP and HTTPS traffic and forward API requests to Express.
Install it:
sudo apt install nginx -y
Start the service:
sudo systemctl start nginx
Enable automatic startup:
sudo systemctl enable nginx
Check its status:
sudo systemctl status nginx
If the EC2 security group allows port 80, opening the instance's public IP in a browser should display the Nginx welcome page.
11. Configuring Nginx as a Reverse Proxy
Assume your backend runs on:
http://127.0.0.1:5000
Your public API domain is:
api.example.com
Create an Nginx configuration file:
sudo nano /etc/nginx/sites-available/my-backend
Add:
server {
listen 80;
listen [::]:80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
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;
}
}
Enable the configuration:
sudo ln -s \
/etc/nginx/sites-available/my-backend \
/etc/nginx/sites-enabled/
Test the configuration:
sudo nginx -t
Reload Nginx:
sudo systemctl reload nginx
Now requests to api.example.com are forwarded to the Express application.
Why Use Nginx?
Nginx provides several useful capabilities:
- Reverse proxying.
- TLS termination.
- Static file delivery.
- Request buffering.
- Compression.
- Connection handling.
- Access logging.
- Routing to multiple backend services.
It also allows the Express application to remain inaccessible through its internal port.
Official reference: NGINX Reverse Proxy Documentation.
12. Deploying the React + Vite Frontend
The React application is different from the Express backend.
A standard Vite production build generates static files.
Build the frontend locally or through a CI/CD pipeline:
npm ci
npm run build
By default, Vite generates a dist directory.
frontend/
dist/
index.html
assets/
index-xxxx.js
index-xxxx.css
Vite's preview command is intended for local build verification, not as a production web server.
12.1 Copy the Build to EC2
For a simple single-server deployment, copy the generated files to the EC2 instance.
Create a frontend directory:
sudo mkdir -p /var/www/my-frontend
From your local machine, use SCP:
scp -i rjryt-server.pem -r \
dist/* \
ubuntu@YOUR_EC2_PUBLIC_IP:/tmp/frontend/
Prepare the temporary directory first if required:
ssh -i rjryt-server.pem ubuntu@YOUR_EC2_PUBLIC_IP \
"mkdir -p /tmp/frontend"
Then move the files into the web directory:
sudo rsync -av --delete \
/tmp/frontend/ \
/var/www/my-frontend/
Set appropriate ownership and permissions:
sudo chown -R www-data:www-data /var/www/my-frontend
sudo find /var/www/my-frontend \
-type d -exec chmod 755 {} \;
sudo find /var/www/my-frontend \
-type f -exec chmod 644 {} \;
The --delete option removes files that no longer exist in the source deployment directory. Use it only with a correctly prepared source directory.
12.2 Configure Nginx for React
Create a configuration file:
sudo nano /etc/nginx/sites-available/my-frontend
Add:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/my-frontend;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
Enable the configuration:
sudo ln -s \
/etc/nginx/sites-available/my-frontend \
/etc/nginx/sites-enabled/
Test and reload:
sudo nginx -t
sudo systemctl reload nginx
The try_files directive is particularly important for React applications using client-side routing.
For example, navigating directly to:
https://example.com/dashboard
should return the React application's index.html, allowing React Router to resolve the route.
Without the fallback, Nginx may return a 404 when users refresh nested routes.
Important: Cache Headers and SPA Deployments
The example gives versioned Vite assets a long cache lifetime.
However, the HTML entry point should generally be revalidated rather than cached indefinitely, because it references the current build's asset filenames.
You can add:
location = /index.html {
add_header Cache-Control "no-cache";
}
Also configure appropriate cache headers for other HTML documents and runtime-generated resources where necessary.
If the application uses a service worker, coordinate Nginx caching with the service worker's own update and cache policies.
13. Configuring HTTPS with Certbot
Production applications should use HTTPS.
Certbot can obtain and configure TLS certificates from Let's Encrypt.
Install Certbot and its Nginx integration using the official instructions for your Ubuntu release.
On supported Ubuntu packages, the APT installation method commonly looks like:
sudo apt update
sudo apt install certbot python3-certbot-nginx -y
Before requesting a certificate, ensure:
- Your domain points to the EC2 instance.
- Port 80 is accessible.
- Port 443 is accessible.
- Nginx is running.
- The Nginx server configuration includes the correct domain.
Request certificates for the frontend:
sudo certbot --nginx \
-d example.com \
-d www.example.com
Request a separate certificate for the API:
sudo certbot --nginx \
-d api.example.com
Certbot can update the Nginx configuration to enable HTTPS.
Test the automatic renewal process:
sudo certbot renew --dry-run
Do not assume certificates renew successfully just because the initial issuance worked. Verify the renewal process and monitor certificate expiration.
Official reference: Certbot Documentation.
14. Configuring CORS Correctly
If the frontend and backend use different origins, the backend may need a CORS configuration.
For example:
Frontend: https://example.com
Backend: https://api.example.com
Configure Express:
import cors from 'cors'
app.use(cors({
origin: 'https://example.com',
credentials: true,
}))
For requests involving cookies, the frontend must also send credentials.
With Axios:
import axios from 'axios'
const api = axios.create({
baseURL: 'https://api.example.com',
withCredentials: true,
})
export default api
Important considerations:
- Do not combine credentialed requests with
Access-Control-Allow-Origin: *. - Allow only trusted origins.
- Handle preflight requests correctly.
- Configure allowed methods and headers according to the application's needs.
- Add CSRF protection when using cookie-based authentication.
CORS is not a substitute for authentication or authorization.
If the frontend and API use the same origin through Nginx, you may not need CORS for those requests at all.
15. Supporting WebSockets and Socket.IO
Many MERN applications use Socket.IO for real-time communication.
When Nginx sits between the client and Express, it must forward WebSocket upgrade headers.
For example, if Socket.IO is served under /socket.io/, configure:
map $http_upgrade $connection_upgrade {
default upgrade;
'' '';
}
server {
listen 443 ssl;
server_name api.example.com;
location /socket.io/ {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
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;
}
location / {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
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;
}
}
The map directive belongs in the Nginx http context, not inside an individual server block.
If you already have an HTTPS server configuration generated by Certbot, add the relevant location to that existing configuration rather than creating a duplicate server block.
For Socket.IO applications, also consider:
- Appropriate proxy read timeouts.
- Correct CORS configuration.
- Sticky sessions when using multiple backend processes with polling.
- A suitable adapter when scaling across multiple instances.
- Graceful connection handling during deployment.
Nginx's WebSocket proxying requires explicit handling of the upgrade headers.
Reference: NGINX WebSocket Proxying.
16. Improving Backend Security
A successful deployment is not necessarily a secure deployment.
Consider the following production practices.
16.1 Keep Internal Ports Private
Do not expose the Node.js application port directly through the EC2 security group.
Nginx should be the public entry point.
16.2 Use Environment Variables for Secrets
Keep database credentials, signing keys, and private API credentials outside source control.
For larger deployments, consider AWS Secrets Manager or Systems Manager Parameter Store.
16.3 Use a Dedicated Linux User
Avoid running the application as root.
Use a dedicated non-root account with only the permissions needed to run and maintain the application.
16.4 Configure Express Security Middleware
Consider using:
- Helmet.
- Rate limiting.
- Request size limits.
- Strict input validation.
- Secure authentication.
- Authorization checks.
- Structured logging.
Example:
import express from 'express'
import helmet from 'helmet'
import rateLimit from 'express-rate-limit'
const app = express()
app.use(helmet())
app.use(express.json({
limit: '1mb',
}))
app.use('/api/', rateLimit({
windowMs: 15 * 60 * 1000,
limit: 100,
standardHeaders: 'draft-8',
legacyHeaders: false,
}))
The rate-limit configuration is only an example. Tune limits according to the endpoint and traffic profile.
16.5 Use IAM Roles Where Appropriate
When an application needs access to AWS services, prefer an IAM role attached to the EC2 instance instead of hardcoding long-lived AWS access keys.
Grant only the permissions the application needs.
For example, an application uploading files to S3 should receive permissions restricted to the required bucket and operations.
Official reference: IAM Roles for Amazon EC2.
17. Logging and Monitoring
Production applications need visibility into their health.
PM2 Logs
View application logs:
pm2 logs
View a specific process:
pm2 logs my-backend
Monitor processes:
pm2 monit
For production, configure log rotation and retention. Do not allow log files to grow indefinitely.
Nginx Logs
Common Nginx log locations on Ubuntu are:
/var/log/nginx/access.log
/var/log/nginx/error.log
Inspect errors:
sudo tail -f /var/log/nginx/error.log
Inspect incoming requests:
sudo tail -f /var/log/nginx/access.log
System Resources
Monitor memory and CPU:
htop
Check disk usage:
df -h
Check running processes:
ps aux
For more complete monitoring, consider Amazon CloudWatch metrics, log collection, alarms, and application-level health checks.
A production health endpoint should provide useful operational information without exposing sensitive configuration or infrastructure details.
18. Deploying the Frontend Separately with S3 and CloudFront
Serving the React frontend from Nginx is convenient for a single-instance deployment.
However, a static React application does not need to run on the same EC2 server as the API.
A common alternative is:
Internet
|
DNS
|
+-----+------+
| |
CloudFront Nginx
| |
S3 EC2
| |
React/Vite PM2
|
Express
|
MongoDB
In this architecture:
- S3 stores the static frontend build.
- CloudFront distributes frontend assets.
- EC2 hosts the Express API.
- Nginx handles API reverse proxying and HTTPS, depending on the chosen edge architecture.
- MongoDB remains in a managed or separately hosted database environment.
Build the frontend:
npm ci
npm run build
Upload the build:
aws s3 sync dist/ s3://YOUR_BUCKET_NAME \
--delete
Configure CloudFront to use the S3 bucket as its origin.
For production, use an appropriate private S3 origin configuration such as Origin Access Control (OAC), rather than making the bucket publicly readable.
After uploading a new build, invalidate the relevant CloudFront paths when required.
For example:
aws cloudfront create-invalidation \
--distribution-id YOUR_DISTRIBUTION_ID \
--paths "/*"
A full invalidation is simple, but a more efficient strategy is to use content-hashed assets with long cache lifetimes and revalidate the HTML entry point.
Which Deployment Model Should You Choose?
| Requirement | Nginx + EC2 frontend | S3 + CloudFront |
|---|---|---|
| Simple single-server setup | Excellent | More configuration |
| Static asset delivery | Good | Excellent |
| Global content distribution | Requires additional infrastructure | Built in |
| Frontend scaling | Tied to EC2 capacity | Managed distribution |
| API hosting | EC2 | EC2 |
| Infrastructure management | More server responsibility | Managed static hosting |
Both are valid deployment strategies.
The best choice depends on application traffic, budget, operational preferences, and scaling requirements.
19. Automating Deployments with GitHub Actions
Manually connecting to EC2 and pulling the latest code works for small projects, but repeated manual deployment becomes inconvenient.
A CI/CD pipeline can automate the process.
A simple deployment workflow might look like this:
Developer pushes code
|
GitHub Repo
|
GitHub Actions
|
Run Tests
|
Install Dependencies
|
Build Application
|
Deploy to EC2
|
Restart
|
Verify Health
19.1 Example GitHub Actions Workflow
Create:
.github/workflows/deploy-backend.yml
name: Deploy Backend
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Deploy to EC2
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_SSH_KEY }}
script: |
cd /home/ubuntu/apps/backend
git pull origin main
npm ci --omit=dev
pm2 restart my-backend --update-env
This is a minimal illustrative workflow, not a complete zero-downtime deployment system.
Before using it:
- Pin third-party GitHub Actions to reviewed commit SHAs.
- Configure GitHub repository secrets securely.
- Ensure the EC2 deployment user has only the required permissions.
- Configure Git authentication on the instance.
- Ensure the server has the correct runtime dependencies.
- Verify the deployed application after restart.
- Add rollback behavior.
The workflow assumes that the backend does not require a separate compilation step.
If your backend uses TypeScript or another build process, adapt the deployment commands accordingly.
19.2 Avoid Storing Production Credentials in Git
Store deployment secrets in GitHub Actions secrets or use a short-lived identity mechanism where practical.
For AWS deployments, consider GitHub Actions OpenID Connect (OIDC) with an appropriately restricted IAM role instead of storing long-lived AWS access keys.
For SSH-based deployment, protect the private key carefully and restrict the deployment account.
20. Improving Deployment Reliability
A deployment should not become a high-risk operation every time new code is released.
Consider the following practices.
Use a Staging Environment
Test application changes in a staging environment before deploying to production.
Keep Deployment Releases Separate
Instead of overwriting the current application directory directly, consider a release-based directory structure:
/home/ubuntu/apps/backend/
releases/
20261201-100000/
20261202-120000/
shared/
.env
current -> releases/20261202-120000/
Each deployment creates a new release directory.
After verification, update the current symlink to point to the new release.
This makes rollback easier because the previous release remains available.
Use Graceful Shutdown
The backend should handle termination signals and close resources cleanly.
Example:
const server = app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`)
})
async function shutdown(signal) {
console.log(`${signal} received`)
server.close(async () => {
try {
await mongoose.disconnect()
process.exit(0)
} catch (error) {
console.error(error)
process.exit(1)
}
})
setTimeout(() => {
process.exit(1)
}, 10000).unref()
}
process.on('SIGTERM', () => shutdown('SIGTERM'))
process.on('SIGINT', () => shutdown('SIGINT'))
This is a simplified example. A real application should also stop accepting new work, handle active requests, close queues and other connections, and use an appropriate timeout strategy.
Be Careful with Database Migrations
When deploying changes that modify database schemas or document structures, ensure old and new application versions can coexist during the deployment process when necessary.
For MongoDB, schema changes often need to be backward-compatible while multiple application versions are active.
21. Common Deployment Problems
Problem 1: 502 Bad Gateway
Nginx returns a 502 error when it cannot obtain a valid response from the upstream application.
Check:
pm2 status
Test the backend directly:
curl http://127.0.0.1:5000/api/health
Inspect Nginx logs:
sudo tail -f /var/log/nginx/error.log
Possible causes:
- Backend process stopped.
- Incorrect upstream port.
- Incorrect proxy configuration.
- Application startup failure.
- Resource exhaustion.
Problem 2: Frontend Routes Return 404
If the root route works but refreshing /dashboard returns 404, the Nginx SPA fallback may be missing.
Check:
location / {
try_files $uri $uri/ /index.html;
}
Problem 3: CORS Errors
Check:
- Frontend origin.
- Backend allowed origins.
- Credential settings.
- Preflight response.
- Cookie attributes.
- HTTPS configuration.
Problem 4: MongoDB Connection Failure
Check:
- Connection string.
- Database credentials.
- Atlas network access.
- Outbound connectivity.
- DNS resolution.
- Database user permissions.
Problem 5: Application Stops After Reboot
Verify the PM2 startup hook and saved process list:
pm2 startup
pm2 save
pm2 status
Problem 6: HTTPS Certificate Renewal Fails
Check:
- DNS records.
- Port 80 accessibility.
- Nginx configuration.
- Certbot renewal status.
Run:
sudo certbot renew --dry-run
Problem 7: Application Runs Out of Memory
Check:
free -h
pm2 monit
Possible solutions include optimizing application memory usage, reducing process count, choosing an appropriate EC2 instance, or moving to a more scalable deployment architecture.
22. Production Deployment Checklist
Before considering your MERN application production-ready, review the following.
AWS infrastructure
- EC2 instance uses a supported operating system.
- Security groups expose only required ports.
- SSH access is restricted.
- Stable DNS configuration is in place.
- Storage and memory are monitored.
- IAM permissions follow least privilege.
Backend
- Node.js LTS is installed.
- Production dependencies are installed.
- Environment variables are protected.
- Database connectivity is verified.
- Express listens on an appropriate interface.
- Health endpoint is available.
- Graceful shutdown is implemented.
PM2
- Application runs under PM2.
- Ecosystem configuration is maintained.
- Restart policy is configured.
- Startup hook is installed.
- Process list is saved.
- Logs are rotated and monitored.
Nginx and HTTPS
- Reverse proxy is configured.
- SPA routing fallback is configured where required.
- Static asset caching is configured appropriately.
- WebSocket proxying works if required.
- HTTPS is enabled.
- Certificate renewal is tested.
Security
- Production secrets are not committed.
- CORS is restricted appropriately.
- Authentication and authorization are implemented.
- Request validation is enabled.
- Rate limiting is configured.
- Internal application ports are not publicly exposed.
- Backups are configured.
Deployment and maintenance
- CI/CD pipeline is configured.
- Deployment is tested in staging.
- Rollback strategy exists.
- Logs and monitoring are available.
- Database changes are handled safely.
- Recovery procedures are documented.
Conclusion
Deploying a MERN stack application on AWS EC2 involves more than starting a Node.js process on a virtual machine.
A reliable deployment needs a coordinated setup:
- EC2 provides the compute environment.
- Node.js and Express run the backend.
- MongoDB stores application data.
- PM2 manages application processes.
- Nginx handles reverse proxying and static files.
- Certbot enables HTTPS.
- GitHub Actions can automate deployments.
- Monitoring and logging help maintain production reliability.
For smaller applications, a single EC2 instance with Nginx and PM2 can be a practical starting point.
As traffic grows, consider separating the frontend, introducing load balancing, running multiple backend instances, using managed databases, and adopting more comprehensive monitoring and deployment practices.
The goal is not to build the most complicated infrastructure from day one. It is to build a secure, maintainable foundation that can evolve as the application grows.
Official References
- Amazon EC2 Documentation
- AWS EC2 Security Groups
- AWS IAM Roles for EC2
- PM2 Documentation
- PM2 Ecosystem Files
- Nginx Reverse Proxy Documentation
- Nginx WebSocket Proxying
- Certbot Documentation
- Vite Production Build
- Vite Static Deployment
- MongoDB Atlas Documentation
- GitHub Actions Documentation
- AWS CloudFront Documentation



