Most apps listen on a local port such as 3000. Nginx accepts the public connections on ports 80 and 443, handles HTTPS and passes the requests to your app. Before you start, point your domain's A record to the server's IPv4 address. If you are logged in as root, leave out sudo.
sudo apt update
sudo apt install -y nginx certbot python3-certbot-nginx
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
(Skip the ufw lines if you do not use ufw; see the firewall guide.)
Create /etc/nginx/sites-available/myapp:
server {
listen 80;
listen [::]:80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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 it and test before reloading:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginxsudo certbot --nginx -d example.com
Certbot gets a free Let's Encrypt certificate, edits the nginx configuration for HTTPS and redirects HTTP to HTTPS. Check the renewal: sudo certbot renew --dry-run. Renewal runs from a systemd timer (systemctl list-timers | grep certbot).
curl http://127.0.0.1:3000.What does a reverse proxy do?
It accepts public connections on ports 80 and 443, handles HTTPS and forwards the requests to your app on a local port.
How do I get a free HTTPS certificate?
Point your domain at the server and run certbot --nginx -d YOUR-DOMAIN; it uses Let's Encrypt.
Does the certificate renew by itself?
Yes, through a timer; check it with certbot renew --dry-run.
Why do I get 502 Bad Gateway?
Your app is not running on the port nginx forwards to.