Deploying a Node.js Application on AWS EC2 From Scratch
The full path from an empty EC2 instance to a Node.js app behind Nginx and HTTPS, with troubleshooting.
- aws
- ec2
- node.js
- nginx
- pm2
- deployment
On this page · 18 sections
Getting a Node.js app running on your laptop is easy. Getting it to run reliably on a server, behind HTTPS, restarting itself after crashes and reboots, and updating without a mess, is where most first deployments stall. This guide walks through the whole path on a single AWS EC2 instance: launching and securing the server, running the app with PM2, putting Nginx in front, adding a free TLS certificate and shipping updates.
The examples use placeholder names (example.com, my-api). Replace them with your own values. Commands target Ubuntu Server LTS, which is the most common choice and has the best documentation.
The architecture you are building
- 1Browser
HTTPS on port 443
- 2Nginx
TLS certificate, reverse proxy
- 3Node.js app (PM2)
listens on localhost:3000
Only Nginx is reachable from the internet. Node.js listens on localhost:3000, and the security group never opens that port. This keeps the attack surface small and lets you add more apps behind the same server later.
Why first deployments go wrong
Most failed deployments come from a short list of mistakes:
- Opening port 3000 to the world instead of putting a reverse proxy in front.
- Running
node server.jsin an SSH session, so the app dies when the session closes. - Forgetting environment variables, so the app boots with
undefinedsecrets. - Pointing DNS at a public IP that changes when the instance restarts.
- Building a large frontend on a tiny instance that runs out of memory.
Each step below avoids one of these.
Step 1: Launch the EC2 instance
In the EC2 console choose Launch instance and set:
- Name: something descriptive such as
my-api-prod. - AMI: Ubuntu Server LTS (64-bit x86 or Arm). Arm (Graviton) instances are usually cheaper for the same performance if all your dependencies support them.
- Instance type: a small general-purpose type (
t3.smallis a comfortable start for a Node API). - Key pair: create a new RSA or ED25519 key pair and download the
.pemfile. AWS shows it only once, so store it safely. - Network settings → security group: create a group that allows
- SSH (22) from your IP only, not
0.0.0.0/0 - HTTP (80) from anywhere
- HTTPS (443) from anywhere
- SSH (22) from your IP only, not
- Storage: 20–30 GB gp3 is plenty for most apps.
Launch the instance, then allocate an Elastic IP and associate it with the instance. Without it, the public IP changes after a stop/start and your DNS breaks.
Step 2: Connect over SSH
On your local machine, restrict the key's permissions (SSH refuses keys that are too open) and connect:
chmod 400 ~/Downloads/my-key.pemssh -i ~/Downloads/my-key.pem ubuntu@YOUR_ELASTIC_IPOnce connected, update the system and enable a basic firewall as a second layer on top of the security group:
sudo apt update && sudo apt upgrade -ysudo ufw allow OpenSSHsudo ufw allow 'Nginx Full'sudo ufw enableAllow
OpenSSHbefore enablingufw, or you will lock yourself out of the server.
Step 3: Install Node.js and Git
Use nvm so you can pin the Node version your app was built for and upgrade it without touching system packages:
sudo apt install -y git curl build-essentialcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bashsource ~/.bashrcnvm install --ltsnode -vInstall PM2 globally:
npm install -g pm2Step 4: Get your code onto the server
Clone the repository. For private repos, create a read-only deploy key instead of using your personal credentials:
ssh-keygen -t ed25519 -C "my-api-deploy" -f ~/.ssh/deploy_keycat ~/.ssh/deploy_key.pub # add as a read-only Deploy key in the repo settingsgit clone git@github.com:your-user/my-api.git ~/apps/my-apicd ~/apps/my-apinpm cinpm run buildUse npm ci rather than npm install for deployments: it installs exactly what is in the lockfile and fails if the lockfile and package.json disagree.
Step 5: Configure environment variables
Create a .env file that is not committed to Git and lock down its permissions:
nano ~/apps/my-api/.envchmod 600 ~/apps/my-api/.envNODE_ENV=productionPORT=3000DATABASE_URL=postgresql://app:strong-password@db-host:5432/appdbJWT_SECRET=replace-with-a-long-random-valueMake sure the app actually loads it. With Node 20.6 or later you can start it with node --env-file=.env dist/main.js, or use dotenv in your entry file. Fail fast when something is missing instead of booting with undefined:
// src/config.tsconst required = ["DATABASE_URL", "JWT_SECRET"] as const;for (const key of required) { if (!process.env[key]) { throw new Error(`Missing required environment variable: ${key}`); }}export const config = { port: Number(process.env.PORT ?? 3000), databaseUrl: process.env.DATABASE_URL!, jwtSecret: process.env.JWT_SECRET!,};Step 6: Run the app with PM2
An ecosystem file keeps the process definition in version control:
// ecosystem.config.cjsmodule.exports = { apps: [ { name: "my-api", script: "dist/main.js", node_args: "--env-file=.env", instances: "max", exec_mode: "cluster", max_memory_restart: "400M", env: { NODE_ENV: "production" }, }, ],};Start it and make sure it survives reboots:
pm2 start ecosystem.config.cjspm2 savepm2 startup systemd # run the command it prints, then: pm2 saveCheck it:
pm2 statuspm2 logs my-api --lines 50curl http://localhost:3000/healthcluster mode starts one worker per CPU core, which matters on multi-core instances because a single Node process uses one core. On a single-vCPU instance set instances: 1.
Step 7: Put Nginx in front
sudo apt install -y nginxsudo nano /etc/nginx/sites-available/my-apiserver { listen 80; server_name api.example.com; client_max_body_size 10m; location / { proxy_pass http://127.0.0.1:3000; 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; # Needed only if you use WebSockets proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }}Enable the site, test the configuration before reloading, then reload:
sudo ln -s /etc/nginx/sites-available/my-api /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl reload nginxBecause Nginx sits in front, tell Express to trust the proxy so req.ip and req.secure are correct:
app.set("trust proxy", 1);Step 8: Point your domain at the server
In your DNS provider (Route 53 or any other), create an A record for api.example.com pointing to the Elastic IP. Confirm it resolves before continuing:
dig +short api.example.comStep 9: Add HTTPS with Let's Encrypt
Certbot proves you control the domain over port 80, so DNS must already point at the server and port 80 must be open:
sudo snap install --classic certbotsudo ln -s /snap/bin/certbot /usr/bin/certbotsudo certbot --nginx -d api.example.comCertbot edits the Nginx config, adds a redirect from HTTP to HTTPS and installs a renewal timer. Verify renewal works:
sudo certbot renew --dry-runStep 10: Deploy updates
Put the update steps in a script so they are repeatable:
#!/usr/bin/env bash# ~/apps/my-api/deploy.shset -euo pipefailcd ~/apps/my-apigit fetch --allgit reset --hard origin/mainnpm cinpm run buildpm2 reload ecosystem.config.cjs --update-envpm2 savepm2 reload restarts cluster workers one at a time so the app keeps answering requests. For database changes, run migrations as a separate, deliberate step before reloading rather than on every boot.
Security considerations
- Keep SSH restricted to your IP, disable password authentication, and never share the
.pemfile. - Run the app as a normal user, never as
root. - Do not open port 3000 (or any app port) in the security group.
- Prefer an IAM role attached to the instance for AWS access instead of storing access keys on disk.
- Enable automatic security updates (
unattended-upgrades) and review them periodically. - Back up data outside the instance. A database or S3 bucket should hold anything you cannot lose.
Troubleshooting
| Symptom | Likely cause | Check |
|---|---|---|
| Browser times out | Security group or ufw blocks the port | Inbound rules for 80/443, sudo ufw status |
502 Bad Gateway | App down or wrong port | pm2 status, port in proxy_pass |
EADDRINUSE | Another process holds the port | sudo lsof -i :3000 |
| Works by IP, not by domain | DNS or server_name mismatch | dig +short, Nginx config |
| Certbot fails | DNS not pointing at the server, port 80 closed | Security group, dig |
| App crashes on boot | Missing env vars or failed build | pm2 logs, .env loading |
| Build killed | Out of memory | Build in CI or add swap |
Useful commands while debugging:
pm2 logs my-api --lines 100sudo tail -f /var/log/nginx/error.logsudo journalctl -u nginx --since "10 min ago"curl -I https://api.example.com/healthTesting the deployment
After each deploy, check three things: the app answers locally (curl localhost:3000/health), it answers through Nginx over HTTPS (curl -I https://api.example.com/health), and it survives a reboot. The last one is easy to skip and catches missing pm2 startup configuration:
sudo reboot# wait a minute, reconnectpm2 statusProduction considerations
A single instance is a single point of failure. When uptime matters, add a second instance behind an Application Load Balancer, move TLS termination to the load balancer with an ACM certificate, store state in a managed database, and automate deployments through a CI/CD pipeline rather than SSH. Add CloudWatch alarms on CPU, memory (via the CloudWatch agent) and status checks.
Best practices
- Use an Elastic IP and keep the server definition in code (Terraform, CDK) once it matters.
- Run
nginx -tbefore every reload. - Use
npm ciand a committed lockfile. - Keep secrets out of Git and out of logs.
- Log to stdout and rotate with PM2's
pm2-logrotatemodule. - Add a
/healthendpoint and monitor it.
Conclusion
A reliable Node.js deployment on EC2 is a small number of well-understood pieces: a locked-down instance, a process manager that restarts the app, a reverse proxy that owns the public ports, and a certificate that renews itself. Once those are in place, shipping an update is one script. From here, the natural next steps are automating this script in a CI/CD pipeline and tuning Nginx for your traffic.
Frequently asked questions
+Which EC2 instance type should I use for a small Node.js app?
Start with a small general-purpose instance such as a t3.micro or t3.small and watch memory and CPU in CloudWatch. Node.js apps are usually memory-bound before they are CPU-bound, and building a frontend on the server can need more RAM than running it, so add swap or build in CI if the build gets killed.
+Do I really need Nginx if Node.js can already listen on a port?
You can expose Node directly, but you should not. Nginx terminates TLS, serves as a stable front door on ports 80 and 443, buffers slow clients, handles compression and lets you run several apps on one server. It also lets the Node process run as an unprivileged user on a high port.
+Why does my site work on the public IP but not on my domain?
Usually DNS. Check that the A record points at the instance's current public IP (use an Elastic IP so it never changes), that the record has propagated, and that the server_name in your Nginx config matches the domain you are requesting.
+PM2 or systemd for running Node.js on EC2?
Both work. PM2 gives you zero-downtime reloads, log management and cluster mode with little setup. systemd is built in and has no extra dependency. If you use PM2, register it with pm2 startup so it comes back after a reboot.
+How do I update the app without downtime?
Pull the new code, install dependencies, build, then run pm2 reload. In cluster mode PM2 restarts workers one at a time so requests keep being served. For stricter guarantees, put the instance behind a load balancer and deploy with a rolling or blue/green strategy.
+Where should I store environment variables and secrets?
Keep them out of the repository. A .env file with 600 permissions owned by the app user is acceptable for a single server. For anything more serious use AWS Systems Manager Parameter Store or Secrets Manager and load values at startup, with an IAM role on the instance instead of access keys.
+How do I fix a 502 Bad Gateway from Nginx?
It means Nginx could not get a valid response from your app. Confirm the process is running (pm2 status), that it listens on the same port as proxy_pass, and read the Nginx error log. A crash loop or a wrong port covers most cases.