Log inSign up

Putting an Express application behind Nginx

Bind the Express app to 127.0.0.1:3000, keep it running with systemd or PM2, and let Nginx listen on ports 80 and 443. Nginx serves the static folder directly, forwards everything else with proxy_pass, and Certbot adds a Let's Encrypt certificate. Only ports 22, 80 and 443 stay open in the firewall.

Topic: Node.js · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

Why put Nginx in front of Express?

Nginx takes care of the work that Node.js should not spend its event loop on: TLS handshakes, slow clients, compression and static files. It also lets you host several apps on one IPv4 address by name, and it keeps the app off the public interface entirely. Express then only answers proxied requests from the same machine. For more about proxy options in general, see Nginx as a reverse proxy.

Before you begin, point a DNS record such as app.example.net at the instance (A to 198.51.100.24, AAAA to 2001:db8:4f2a::24). The DNS records tutorial shows how. Certificates can only be issued once the name resolves to the server.

How do you create a small Express app?

Install Node.js as on installing Node.js and npm, then create the project as the deploy user.

mkdir -p ~/apps/hello && cd ~/apps/hello
npm init -y
npm install express
mkdir public
echo "<h1>static ok</h1>" > public/index.html

Write server.js:

const express = require("express");
const path = require("path");

const app = express();
const port = process.env.PORT || 3000;

app.set("trust proxy", "loopback");
app.disable("x-powered-by");
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));

app.get("/api/health", (req, res) => {
  res.json({ status: "ok", ip: req.ip });
});

app.listen(port, "127.0.0.1", () => {
  console.log("listening on 127.0.0.1:" + port);
});

The trust proxy setting tells Express to believe the forwarded headers that Nginx adds, so req.ip and req.protocol report the real visitor. Limiting it to loopback means nobody else can spoof them. Test locally with node server.js and, from a second SSH session, curl http://127.0.0.1:3000/api/health.

How do you keep the app running?

Use a systemd unit or PM2. A unit file is short and needs nothing extra:

sudo tee /etc/systemd/system/hello.service >/dev/null <<'EOF'
[Unit]
Description=Hello Express app
After=network.target

[Service]
User=deploy
WorkingDirectory=/home/deploy/apps/hello
Environment=NODE_ENV=production PORT=3000
ExecStart=/usr/bin/node server.js
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now hello
systemctl status hello --no-pager

Check the binary path with command -v node first. If you prefer PM2, the steps are on keeping apps running with PM2.

How do you install Nginx and write the site config?

Install Nginx from the distribution, enable it and create one server block for the app.

# Ubuntu and Debian
sudo apt install -y nginx
# Rocky and Alma
sudo dnf install -y nginx
sudo systemctl enable --now nginx

On Ubuntu and Debian save the following as /etc/nginx/sites-available/hello and link it into sites-enabled; on Rocky and Alma save it as /etc/nginx/conf.d/hello.conf.

server {
    listen 80;
    listen [::]:80;
    server_name app.example.net;

    root /home/deploy/apps/hello/public;

    location / {
        try_files $uri @node;
    }

    location @node {
        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;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
sudo ln -s /etc/nginx/sites-available/hello /etc/nginx/sites-enabled/   # Ubuntu, Debian
sudo nginx -t
sudo systemctl reload nginx

try_files sends requests for existing files straight from disk and passes the rest to Express. The Upgrade headers let WebSocket connections through.

What permissions and SELinux settings does Nginx need?

Nginx runs as www-data (Ubuntu, Debian) or nginx (Rocky, Alma) and needs to traverse the path to public. Home directories are often mode 750, so either grant execute on them or move the static files under /var/www.

chmod o+x /home/deploy /home/deploy/apps /home/deploy/apps/hello

On Rocky and Alma, SELinux blocks Nginx from opening outgoing connections and from reading files in home directories by default. Allow the proxy connection and label the static folder:

sudo setsebool -P httpd_can_network_connect 1
sudo semanage fcontext -a -t httpd_sys_content_t "/home/deploy/apps/hello/public(/.*)?"
sudo restorecon -Rv /home/deploy/apps/hello/public

If semanage is missing, install policycoreutils-python-utils. A 502 error with "permission denied" in /var/log/nginx/error.log almost always points to one of these two settings.

How do you open the firewall?

Allow SSH, HTTP and HTTPS only. Port 3000 stays closed because the app listens on loopback.

# Ubuntu and Debian
sudo ufw allow OpenSSH
sudo ufw allow "Nginx Full"
sudo ufw enable
sudo ufw status

# Rocky and Alma
sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --reload

Firewalls on BitcoinVPS live inside the operating system, so these rules are the whole policy. The firewall rules tutorial covers nftables if you prefer it.

How do you add HTTPS with Let's Encrypt?

Certbot with its Nginx plugin requests a certificate, edits the server block to listen on 443 and sets up automatic renewal.

# Ubuntu and Debian
sudo apt install -y certbot python3-certbot-nginx
# Rocky and Alma (from EPEL)
sudo dnf install -y epel-release
sudo dnf install -y certbot python3-certbot-nginx

sudo certbot --nginx -d app.example.net --redirect
sudo certbot renew --dry-run

Answer the prompts with a contact address for expiry notices. The --redirect flag adds a permanent redirect from HTTP to HTTPS. Renewal runs from a systemd timer, which you can list with systemctl list-timers | grep certbot. More options, including wildcard certificates, are on the Certbot page.

How do you verify the whole chain and deploy updates?

Request a static file and an API route from outside the server:

curl -I https://app.example.net/
curl https://app.example.net/api/health

The first response should come from Nginx with status 200, and the second should show your own public IP in the ip field, proving the forwarded headers work. To deploy a new version, pull the code, install dependencies and restart:

cd ~/apps/hello
git pull
npm ci --omit=dev
sudo systemctl restart hello

If the browser shows 502 Bad Gateway, the app is down or on another port: check journalctl -u hello -n 50 and ss -ltnp | grep 3000.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A1-2one Express app with Nginx1 vCPU, 2 GB RAM, 50 GB NVMe$7.20/mo$43.20 for 6 months
A2-4several apps or more traffic2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months

Questions about An Express app behind Nginx

Why bind Express to 127.0.0.1 and not 0.0.0.0?

So the app can only be reached through Nginx. Even if a firewall rule is wrong, nothing outside the server can talk to port 3000 directly.

Can one server host several Express apps?

Yes. Give each app its own port and its own Nginx server block with a different server_name, then run Certbot for each name.

Do I need express.static if Nginx serves the files?

Not strictly. Keeping it means the app also works when you run it alone in development; in production Nginx answers first through try_files.

Why does req.ip show 127.0.0.1?

Express does not trust proxy headers by default. Set trust proxy to loopback and make sure Nginx sends X-Forwarded-For.

Which Express version does npm install today?

Express 5 is the current major. It needs Node.js 18 or newer and changes some routing syntax, so check the migration notes if you move an older Express 4 app.