DEV Community

Cover image for Deploy a Node.js API to Ubuntu with PM2, Nginx, MySQL and Let's Encrypt
Saurabh Bag
Saurabh Bag

Posted on Edited on AI-assisted

Deploy a Node.js API to Ubuntu with PM2, Nginx, MySQL and Let's Encrypt

This is a complete guide to deploying a Node.js app to production on an Ubuntu server: PM2 to keep it running, Nginx as a reverse proxy, MySQL, and free SSL with Let's Encrypt and Certbot. Every step has a filled-in example, and the troubleshooting tables cover the errors that break most first deployments: the PM2 restart loop, 502 Bad Gateway, certbot NXDOMAIN, and env files that crash the app on startup.

It works on any Ubuntu VPS (22.04 or 24.04), on AWS EC2, DigitalOcean, Linode, Hetzner or any other host, and for any Node.js framework: Express, NestJS, Fastify or plain Node.

What you'll have at the end

  • Your Node.js API running under PM2, restarting on crashes and starting again after a server reboot
  • Nginx in front of it as a reverse proxy
  • Free HTTPS (SSL certificate) from Let's Encrypt, renewing automatically
  • A MySQL database with its own user
  • A firewall that only lets in SSH, HTTP and HTTPS

It works for any environment: staging, production, UAT or a fresh server.

How to use this guide

The stack is Node.js, PM2, Nginx, MySQL, Let's Encrypt and a DNS A record. Fill in the worksheet first. Each step then shows the command with <placeholders>, followed by an example using the sample values below. Never write real secrets into notes or guides: keep them in a password manager.

Placeholder Meaning Example value used in this guide
<app> App name, also the PM2 process name orders-api
<env> Environment, the value of NODE_ENV staging
<env-file> Env file the app reads for <env> .env.staging
<server-ip> Server public IP (curl -4 ifconfig.me) 203.0.113.10
<ssh-user> Linux user that runs the app ubuntu
<app-dir> Folder the app lives in /home/ubuntu/orders-api
<port> Local port the app listens on; must be free 4000
<api-domain> Public domain for the API api-staging.example.com
<ui-origin> Frontend URL allowed by CORS https://staging.example.com
<git-host> Git provider host bitbucket.org
<repo> Repository path acme/orders-api.git
<branch> Branch to deploy main
<node-version> Node major version from package.json engines 24
<db-name> / <db-user> Database and its dedicated user orders_staging / orders_app
<build-command> Compiles the app npm run build
<migration-command> Applies database migrations npm run migration:run
<seed-command> Creates first-login data npm run seed:admin
<start-file> Compiled entry file dist/server.js
<health-path> Health-check URL path api/v1/health

Before starting, find your app's real values for the last six rows in its README or package.json.

Before you start

Most setup delays come from missing access or missing values, not from the commands. Collect these before you touch the server.

  • SSH access to the server, and an SFTP client such as FileZilla as a fallback
  • Admin on the git repository, to add a read-only deploy (access) key for the server
  • Access to the DNS provider for the domain (for example AWS Route 53), to add the A record
  • Access to the server firewall or cloud security group, with ports 22, 80 and 443 open
  • Database admin access on the server, to create the database and its user
  • A free port: sudo ss -ltnp | grep <port> prints nothing
  • The app's full list of environment variables (usually .env.example), with a value for every required one
  • New random secrets for this environment, each from openssl rand -hex 32; never reuse another environment's secrets
  • Credentials for every third-party service the app calls in this environment (cloud storage, SMS, email, CAPTCHA, payment and so on), or a decision to use the app's fake provider where it allows one
  • Seed data the app needs for its first login, such as an admin user

Step-by-step setup

Do the steps in order: each needs the one before it. DNS must resolve before HTTPS, and the env file must pass the app's checks before PM2 runs it.

Step 1. Install Node.js, PM2, Nginx and MySQL on Ubuntu

Skip what is already installed. Check with node -v, pm2 -v, nginx -v and mysql --version.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
source ~/.bashrc
nvm install <node-version>
npm install -g pm2
sudo apt update
sudo apt install -y git nginx mysql-server certbot python3-certbot-nginx
Enter fullscreen mode Exit fullscreen mode

Example:

nvm install 24
node -v        # v24.x.x
pm2 -v         # 6.x.x
Enter fullscreen mode Exit fullscreen mode

Step 2. Create the MySQL database and user

CREATE DATABASE <db-name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
CREATE USER '<db-user>'@'localhost' IDENTIFIED BY '<strong-password>';
GRANT ALL PRIVILEGES ON <db-name>.* TO '<db-user>'@'localhost';
FLUSH PRIVILEGES;
Enter fullscreen mode Exit fullscreen mode

Example: open MySQL with sudo mysql, then:

CREATE DATABASE orders_staging CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
CREATE USER 'orders_app'@'localhost' IDENTIFIED BY '<output of: openssl rand -base64 24>';
GRANT ALL PRIVILEGES ON orders_staging.* TO 'orders_app'@'localhost';
FLUSH PRIVILEGES;
EXIT;
Enter fullscreen mode Exit fullscreen mode

The app never connects as root. The user is created for localhost, so set the app's DB host to localhost: MySQL may not match it for a TCP connection to 127.0.0.1.

Step 3. Add a deploy key so the server can pull from GitHub or Bitbucket

Without this, git clone and git pull fail with Permission denied (publickey). Use one key per repository, so this app's key never affects other apps on the server.

ssh-keygen -t ed25519 -C "<env>-<app>" -f ~/.ssh/<app> -N ""
cat ~/.ssh/<app>.pub
Enter fullscreen mode Exit fullscreen mode

Add the printed public key to the repository as a read-only key. In Bitbucket: Repository settings, Access keys. In GitHub: Settings, Deploy keys. Then add a host alias to ~/.ssh/config, lock the files down and test.

Example:

ssh-keygen -t ed25519 -C "staging-orders-api" -f ~/.ssh/orders-api -N ""
cat ~/.ssh/orders-api.pub
# ssh-ed25519 AAAAC3Nza...  staging-orders-api   <- paste this into Bitbucket
Enter fullscreen mode Exit fullscreen mode

~/.ssh/config:

Host git-orders-api
    HostName bitbucket.org
    User git
    IdentityFile ~/.ssh/orders-api
    IdentitiesOnly yes
Enter fullscreen mode Exit fullscreen mode
chmod 600 ~/.ssh/config ~/.ssh/orders-api
ssh -T git@git-orders-api
# authenticated via a deploy key.
Enter fullscreen mode Exit fullscreen mode

Step 4. Clone the code onto the server

git clone git@git-<app>:<repo> <app-dir>
cd <app-dir>
git checkout <branch>
npm ci
Enter fullscreen mode Exit fullscreen mode

Example:

git clone git@git-orders-api:acme/orders-api.git /home/ubuntu/orders-api
cd /home/ubuntu/orders-api
git checkout main
npm ci
Enter fullscreen mode Exit fullscreen mode

No repository access yet? Upload src/, package.json, package-lock.json, the build config and ecosystem.config.cjs with SFTP (for example FileZilla) to /home/ubuntu/orders-api. Then check the files landed where expected: ls /home/ubuntu/orders-api/src must list the source files, not another src folder.

Step 5. Create the production .env file

The env file never goes through git. Create it on the server, or upload it with SFTP, then lock it down. Start from the app's .env.example and follow the Env file rules section below.

nano <app-dir>/<env-file>
chmod 600 <app-dir>/<env-file>
Enter fullscreen mode Exit fullscreen mode

Example:

nano /home/ubuntu/orders-api/.env.staging
chmod 600 /home/ubuntu/orders-api/.env.staging
Enter fullscreen mode Exit fullscreen mode
NODE_ENV=staging
PORT=4000
CORS_ORIGIN=https://staging.example.com
TRUST_PROXY=1

DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=orders_app
DB_PASSWORD=<the password from step 2>
DB_DATABASE=orders_staging

JWT_SECRET=<output of: openssl rand -hex 32>

SMS_PROVIDER=fake
# SMS_API_KEY=
Enter fullscreen mode Exit fullscreen mode

The last two lines show rule 2 below: an unused key is commented out, not left blank.

Step 6. Build the app and run database migrations

Prefix every server command with NODE_ENV=<env>. Without it, the app may read the wrong env file or the wrong database. Take a database backup first if the database already holds data.

cd <app-dir>
<build-command>
NODE_ENV=<env> <migration-command>
NODE_ENV=<env> <seed-command>
Enter fullscreen mode Exit fullscreen mode

Example:

cd /home/ubuntu/orders-api
npm run build
NODE_ENV=staging npm run migration:run
NODE_ENV=staging npm run seed:admin
Enter fullscreen mode Exit fullscreen mode

Step 7. Keep the Node.js app running with PM2 (and start it on reboot)

A hand run shows any startup error directly, instead of hiding it in a PM2 restart loop. Wait for the app's "listening" line, then press Ctrl+C.

cd <app-dir>
NODE_ENV=<env> node <start-file>
Enter fullscreen mode Exit fullscreen mode

Example:

cd /home/ubuntu/orders-api
NODE_ENV=staging node dist/server.js
# orders-api listening on port 4000 (staging)   <- press Ctrl+C
Enter fullscreen mode Exit fullscreen mode

Then start it under PM2, from the app folder. If the app has no ecosystem.config.cjs, create one:

module.exports = {
  apps: [
    {
      name: '<app>',
      script: './<start-file>',
      cwd: __dirname,
      autorestart: true,
      max_restarts: 10,
      restart_delay: 5000,
      max_memory_restart: '512M',
      env_<env>: { NODE_ENV: '<env>', PORT: <port> },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode
cd <app-dir>
pm2 start ecosystem.config.cjs --env <env>
pm2 save
pm2 startup
Enter fullscreen mode Exit fullscreen mode

Example:

module.exports = {
  apps: [
    {
      name: 'orders-api',
      script: './dist/server.js',
      cwd: __dirname,
      autorestart: true,
      max_restarts: 10,
      restart_delay: 5000,
      max_memory_restart: '512M',
      env_staging: { NODE_ENV: 'staging', PORT: 4000 },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode
cd /home/ubuntu/orders-api
pm2 start ecosystem.config.cjs --env staging
pm2 save
pm2 startup     # then run the sudo command it prints
pm2 list        # orders-api  online  restarts 0  mem 95mb
Enter fullscreen mode Exit fullscreen mode

In pm2 list, the restart count must stay at 0 and memory must be above 0.

Step 8. Point your domain to the server (DNS A record)

At the DNS provider, create an A record from the API domain to the server IP, then wait until it resolves. In Route 53, use simple routing with alias off. In Cloudflare, set it to "DNS only" until HTTPS works.

Field Value
Type A
Name subdomain part of <api-domain>
Value <server-ip>
TTL 300
nslookup <api-domain> 8.8.8.8
Enter fullscreen mode Exit fullscreen mode

Example: in the example.com zone, add type A, name api-staging, value 203.0.113.10, TTL 300. Then:

curl -4 ifconfig.me                          # 203.0.113.10  (run on the server)
nslookup api-staging.example.com 8.8.8.8
# Name:    api-staging.example.com
# Address: 203.0.113.10
Enter fullscreen mode Exit fullscreen mode

Step 9. Configure Nginx as a reverse proxy for Node.js

sudo nano /etc/nginx/sites-available/<api-domain>
Enter fullscreen mode Exit fullscreen mode
server {
    listen 80;
    server_name <api-domain>;
    client_max_body_size 60M;

    location / {
        proxy_pass http://127.0.0.1:<port>;
        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;
    }
}
Enter fullscreen mode Exit fullscreen mode
sudo ln -s /etc/nginx/sites-available/<api-domain> /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
Enter fullscreen mode Exit fullscreen mode

Example: /etc/nginx/sites-available/api-staging.example.com:

server {
    listen 80;
    server_name api-staging.example.com;
    client_max_body_size 60M;

    location / {
        proxy_pass http://127.0.0.1:4000;
        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;
    }
}
Enter fullscreen mode Exit fullscreen mode
sudo ln -s /etc/nginx/sites-available/api-staging.example.com /etc/nginx/sites-enabled/
sudo nginx -t
# nginx: configuration file /etc/nginx/nginx.conf test is successful
sudo systemctl reload nginx
Enter fullscreen mode Exit fullscreen mode

Reload only when nginx -t reports success. Set client_max_body_size above the app's largest upload. Behind Nginx, the app must trust one proxy hop (in Express: app.set('trust proxy', 1)), or rate limits and client IPs will be wrong.

Step 10. Add free SSL with Let's Encrypt and Certbot

Run this only after step 8 resolves. Certbot gets the certificate, edits the Nginx site, adds the HTTP-to-HTTPS redirect and schedules renewal.

sudo certbot --nginx -d <api-domain>
sudo certbot renew --dry-run
Enter fullscreen mode Exit fullscreen mode

Example:

sudo certbot --nginx -d api-staging.example.com
# Successfully received certificate.
# Successfully deployed certificate for api-staging.example.com
sudo certbot renew --dry-run
# Congratulations, all simulated renewals succeeded
Enter fullscreen mode Exit fullscreen mode

Step 11. Secure the server with the UFW firewall

Only SSH, HTTP and HTTPS stay open. Never open the app port or the database port to the internet: Nginx is the only way in.

sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status
Enter fullscreen mode Exit fullscreen mode

Example: sudo ufw status on a correct server:

Status: active
To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
Nginx Full                 ALLOW       Anywhere
Enter fullscreen mode Exit fullscreen mode

Port 4000 and port 3306 must not appear in the list. If the server also has a cloud security group, allow only 22, 80 and 443 there too.

Env file rules

A wrong env file is the most common reason a new server fails: the app exits at startup, and PM2 restarts it in a loop. These rules apply to every app and environment.

Rule Example
1. One file per environment, picked by NODE_ENV. Run every command from the folder that holds the file. NODE_ENV=staging reads .env.staging; NODE_ENV=production reads .env.production
2. Blank is not the same as missing. An empty value is an empty string, which strict validation rejects. Wrong: SMS_API_KEY= · Right: # SMS_API_KEY=
3. A real provider needs its credentials. Switching a service from fake to real makes its keys required. SMS_PROVIDER=twilio also needs SMS_API_KEY and SMS_SENDER; SMS_PROVIDER=fake needs neither
4. Env files stay out of git. Keep them on the server with chmod 600, and in a password manager. If one is committed, change every secret in it: git history keeps it. .gitignore holds .env.* and !.env.example; ls -l .env.staging shows -rw-------
5. Each environment gets its own secrets. Staging JWT_SECRET and production JWT_SECRET are two separate openssl rand -hex 32 outputs
6. An encryption key is permanent. Changing it later makes data already encrypted with it unreadable. Set DATA_ENCRYPTION_KEY once, before the first real record is saved
7. Paired settings change together. Where the frontend and the API share a setting, change both. API CORS_ORIGIN=https://staging.example.com and frontend VITE_API_URL=https://api-staging.example.com
8. Restart after every change. A frontend setting needs a rebuild instead, because build tools bake it into the bundle. API: pm2 restart orders-api --update-env · Frontend: npm run build again, then deploy

Verify the deployment

Check from the inside out: the first check that fails tells you which layer to fix. Each example uses the sample values.

Check Example command Expected result If it fails
1. App is running pm2 list, twice, 10 seconds apart orders-api online, restart count unchanged, memory above 0 pm2 logs orders-api --err --lines 60 --nostream
2. App answers locally curl http://127.0.0.1:4000/api/v1/health {"success":true,...} App or database: read the logs
3. DNS nslookup api-staging.example.com 8.8.8.8 Address: 203.0.113.10 Add or fix the A record (step 8)
4. HTTP through Nginx curl -I http://api-staging.example.com/api/v1/health 301 Moved Permanently to HTTPS sudo nginx -t, the site file, port 80
5. HTTPS curl https://api-staging.example.com/api/v1/health Same as check 2 certbot, port 443
6. Frontend reaches the API Browser DevTools, Network tab, make a request Requests to api-staging.example.com succeed Match the error in Troubleshooting
7. Survives a reboot (only on a server you may reboot) sudo reboot, then pm2 list orders-api online pm2 startup, then pm2 save

Troubleshooting common Node.js deployment errors

Each row is a real problem from a past setup. Find your symptom, then apply the fix.

The app won't start

Symptom Cause Fix
pm2 list: restart count climbing, blank status, 0b memory The app exits at startup; PM2 restarts it in a loop pm2 logs <app> --err --lines 60 --nostream, fix what it names
pm2 reload or pm2 restart says Process <id> not found The process is dead mid-restart pm2 delete <app>, fix the cause, pm2 start ecosystem.config.cjs --env <env>
pm2 start crashes with Cannot read properties of undefined (reading 'pm2_env') PM2 is tripping over the crash-looping process pm2 delete <app>, then start again
Config error: Too small: expected string to have >=1 characters A variable is present but blank Comment the line out with #
Config error: required when <PROVIDER>=... A real provider is set without its credentials Fill the credentials, or use the fake provider where the environment allows it
Config error: fake is not allowed in <env> The environment's safety rules refuse a fake provider, or the server runs an old build Use the real provider, or deploy the build that allows it
EADDRINUSE Another app already uses <port> `sudo ss -ltnp \
{% raw %}Cannot find module .../dist/server.js No build on the server npm ci && npm run build
ECONNREFUSED ...:3306 or Access denied for user Database down or wrong credentials sudo systemctl status mysql; test with mysql -u <db-user> -p <db-name>
Table ... doesn't exist Migrations not run NODE_ENV=<env> npm run <migration-command>

Deploys that don't take effect

Symptom Cause Fix
pm2 start ecosystem.config.cjs started a different app Run from the wrong folder, which held another app's ecosystem file Always cd <app-dir> first
New source uploaded, nothing changed PM2 runs the compiled dist/, not the source npm run build, then pm2 restart <app> --update-env
Env change ignored PM2 kept the old environment pm2 restart <app> --update-env, or delete and start again
git pull fails with Permission denied (publickey) The server has no key the repository accepts Add a deploy key (step 3); meanwhile upload with SFTP

The domain doesn't work

Symptom Cause Fix
Browser: net::ERR_NAME_NOT_RESOLVED No DNS record for the domain Add the A record (step 8)
certbot: DNS problem: NXDOMAIN looking up A certbot ran before DNS resolved Wait for nslookup to return the IP, run certbot again
certbot: timeout or connection error Port 80 is closed Open 80 and 443 in the firewall and security group
502 Bad Gateway Nginx is up but the app is not, or the port is wrong pm2 list; check proxy_pass uses <port>
413 Request Entity Too Large Upload is bigger than Nginx allows Raise client_max_body_size, nginx -t, reload
Browser: CORS error The API doesn't allow the frontend's origin Set the app's CORS origin to <ui-origin>, restart
Frontend shows a blank page after deploy The frontend's own config check fails, for example a provider set with an empty key Fix the frontend env file and rebuild it

Never run on a shared server: pm2 kill (stops every app), pm2 delete all, or sudo systemctl reload nginx without a passing sudo nginx -t first.

Redeploying an update

An update is pull, build, migrate, restart, check. Run it from the app folder.

cd <app-dir>
git pull
npm ci
<build-command>
NODE_ENV=<env> <migration-command>
pm2 restart <app> --update-env
pm2 logs <app> --lines 20 --nostream
curl https://<api-domain>/<health-path>
Enter fullscreen mode Exit fullscreen mode

Example:

cd /home/ubuntu/orders-api
git pull
npm ci
npm run build
NODE_ENV=staging npm run migration:run
pm2 restart orders-api --update-env
pm2 logs orders-api --lines 20 --nostream
curl https://api-staging.example.com/api/v1/health
Enter fullscreen mode Exit fullscreen mode

Not every change needs every command:

What changed What to run Example
Code only Pull, build, restart git pull && npm run build && pm2 restart orders-api
Dependencies (package.json) Add npm ci before the build git pull && npm ci && npm run build && pm2 restart orders-api
Database schema Back up, then migrate before the restart mysqldump orders_staging > ~/backup-$(date +%F).sql, then NODE_ENV=staging npm run migration:run
Env file only Restart with --update-env; no build pm2 restart orders-api --update-env
Nginx site Test, then reload sudo nginx -t && sudo systemctl reload nginx

Without repository access on the server, replace git pull with an SFTP upload of the changed files, and still build.

Environments compared

The setup steps are the same for every environment. What changes is how strict the settings are and what data the server may hold.

Area Development (local) Staging Production
Purpose Building features Testing a release on a real server Real users and real data
Env file .env.local .env.staging .env.production
Third-party services Fake providers Fake where the app allows it, real where testing needs it Real only
Login shortcuts (fixed OTP, test logins) Allowed Only if the app allows it and staging holds no real data Never
Data Seed or test data Test data only Real data
Secrets Local values Own values Own values, never shared
HTTPS Not needed Required Required
Backups None Optional Daily, tested restores, plus one before every migration
Monitoring and alerts None Logs Logs, uptime check, disk and certificate expiry alerts

Production checklist

  • Every provider is real; no fake providers or login shortcuts
  • New secrets, created only for production and stored in the password manager
  • Env file is chmod 600 and not in git
  • Database user has access to its own database only; MySQL is not reachable from the internet
  • Automated daily database backup, with a restore tested once
  • Firewall allows only 22, 80 and 443; SSH by key only
  • pm2 startup and pm2 save done, and the app survives a reboot
  • Log rotation on (pm2 install pm2-logrotate)
  • sudo certbot renew --dry-run passes
  • An uptime check on the health URL alerts someone when it fails

FAQ

How do I keep a Node.js app running after I close the SSH session?

Run it with PM2 instead of node: pm2 start ecosystem.config.cjs --env production. PM2 runs it in the background, restarts it if it crashes, and pm2 startup plus pm2 save bring it back after a server reboot (step 7).

Why does Nginx show 502 Bad Gateway for my Node.js app?

Nginx is running, but it can't reach your app. Either the app isn't running (check pm2 list and pm2 logs), or proxy_pass in the Nginx site points to a different port than the one the app listens on.

Do I need Nginx in front of Node.js?

For production, yes. Nginx handles HTTPS, redirects HTTP to HTTPS, limits upload size and lets several apps share ports 80 and 443 on one server. Your Node.js app stays on a local port that the internet can't reach.

How do I get a free SSL certificate for a Node.js app?

Use Let's Encrypt with Certbot's Nginx plugin: sudo certbot --nginx -d api.example.com. The domain's DNS must point to the server first, or certbot fails with NXDOMAIN (step 10).

How do I renew a Let's Encrypt certificate?

You don't need to do it by hand. Certbot installs a scheduled task that renews certificates before they expire. Test it with sudo certbot renew --dry-run.

Why does PM2 say "Process not found" when I restart my app?

The app is crashing at startup, so PM2 has no running process to restart. Run pm2 logs <app> --err, fix the error it shows, then pm2 delete <app> and start it again.

How do I deploy updates to a Node.js app without breaking it?

Pull, install, build, run migrations, then restart with pm2 restart <app> --update-env, and check the health URL. Back up the database first when the update changes the schema (see Redeploying an update).


If this saved you a debugging session, leave a comment with the error that cost you the most time on your own setup, and I'll add it to the troubleshooting tables.

Top comments (0)