AboutProjectsWorkBlogContact
Home / Blog / AWS, Deployment & DevOps

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.

By Hamza JanzaibNovember 28, 202618 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • aws
  • ec2
  • node.js
  • nginx
  • pm2
  • deployment
On this page · 18 sections
  • The architecture you are building
  • Why first deployments go wrong
  • Step 1: Launch the EC2 instance
  • Step 2: Connect over SSH
  • Step 3: Install Node.js and Git
  • Step 4: Get your code onto the server
  • Step 5: Configure environment variables
  • Step 6: Run the app with PM2
  • Step 7: Put Nginx in front
  • Step 8: Point your domain at the server
  • Step 9: Add HTTPS with Let's Encrypt
  • Step 10: Deploy updates
  • Security considerations
  • Troubleshooting
  • Testing the deployment
  • Production considerations
  • Best practices
  • Conclusion

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

  1. 1Browser

    HTTPS on port 443

  2. 2Nginx

    TLS certificate, reverse proxy

  3. 3Node.js app (PM2)

    listens on localhost:3000

Only Nginx is exposed to the internet; port 3000 stays closed

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.js in an SSH session, so the app dies when the session closes.
  • Forgetting environment variables, so the app boots with undefined secrets.
  • 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:

  1. Name: something descriptive such as my-api-prod.
  2. 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.
  3. Instance type: a small general-purpose type (t3.small is a comfortable start for a Node API).
  4. Key pair: create a new RSA or ED25519 key pair and download the .pem file. AWS shows it only once, so store it safely.
  5. 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
  6. 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:

bash
chmod 400 ~/Downloads/my-key.pemssh -i ~/Downloads/my-key.pem ubuntu@YOUR_ELASTIC_IP

Once connected, update the system and enable a basic firewall as a second layer on top of the security group:

bash
sudo apt update && sudo apt upgrade -ysudo ufw allow OpenSSHsudo ufw allow 'Nginx Full'sudo ufw enable

Allow OpenSSH before enabling ufw, 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:

bash
sudo apt install -y git curl build-essentialcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bashsource ~/.bashrcnvm install --ltsnode -v

Install PM2 globally:

bash
npm install -g pm2

Step 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:

bash
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 settings
bash
git clone git@github.com:your-user/my-api.git ~/apps/my-apicd ~/apps/my-apinpm cinpm run build

Use 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:

bash
nano ~/apps/my-api/.envchmod 600 ~/apps/my-api/.env
ini
NODE_ENV=productionPORT=3000DATABASE_URL=postgresql://app:strong-password@db-host:5432/appdbJWT_SECRET=replace-with-a-long-random-value

Make 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:

ts
// 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:

js
// 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:

bash
pm2 start ecosystem.config.cjspm2 savepm2 startup systemd   # run the command it prints, then: pm2 save

Check it:

bash
pm2 statuspm2 logs my-api --lines 50curl http://localhost:3000/health

cluster 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

bash
sudo apt install -y nginxsudo nano /etc/nginx/sites-available/my-api
nginx
server {    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:

bash
sudo ln -s /etc/nginx/sites-available/my-api /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl reload nginx

Because Nginx sits in front, tell Express to trust the proxy so req.ip and req.secure are correct:

ts
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:

bash
dig +short api.example.com

Step 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:

bash
sudo snap install --classic certbotsudo ln -s /snap/bin/certbot /usr/bin/certbotsudo certbot --nginx -d api.example.com

Certbot edits the Nginx config, adds a redirect from HTTP to HTTPS and installs a renewal timer. Verify renewal works:

bash
sudo certbot renew --dry-run

Step 10: Deploy updates

Put the update steps in a script so they are repeatable:

bash
#!/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 save

pm2 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 .pem file.
  • 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

SymptomLikely causeCheck
Browser times outSecurity group or ufw blocks the portInbound rules for 80/443, sudo ufw status
502 Bad GatewayApp down or wrong portpm2 status, port in proxy_pass
EADDRINUSEAnother process holds the portsudo lsof -i :3000
Works by IP, not by domainDNS or server_name mismatchdig +short, Nginx config
Certbot failsDNS not pointing at the server, port 80 closedSecurity group, dig
App crashes on bootMissing env vars or failed buildpm2 logs, .env loading
Build killedOut of memoryBuild in CI or add swap

Useful commands while debugging:

bash
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/health

Testing 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:

bash
sudo reboot# wait a minute, reconnectpm2 status

Production 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 -t before every reload.
  • Use npm ci and a committed lockfile.
  • Keep secrets out of Git and out of logs.
  • Log to stdout and rotate with PM2's pm2-logrotate module.
  • Add a /health endpoint 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.

Further reading

  • docs.aws.amazon.com/ec2/
  • nginx.org/en/docs/
  • certbot.eff.org/

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

AWS, Deployment & DevOpsNovember 28, 202615 min readBeginner

Hosting a Static Website on AWS S3

Create a bucket, allow public reads, enable website hosting and deploy a build with one CLI command.

AWS, Deployment & DevOpsNovember 28, 202617 min readIntermediate

Configuring AWS CloudFront With S3 for Static Website Delivery

Keep the bucket private, serve through CloudFront, add HTTPS and a custom domain, and invalidate cleanly.

Backend, Node.js, NestJS & APIsNovember 28, 202616 min readIntermediate

Implementing Secure JWT Authentication in Node.js

Access and refresh tokens done properly: rotation, reuse detection, cookies and password hashing in Express.

Built by Hamza Janzaib