Verified guide
This guide was verified by creating a cloud server and running every command in it, from start to finish, exactly as written.
- OS
- Ubuntu 26.04.1 LTS · x86_64
- Installed version
- Nginx 1.28.3 (1.28.3-2ubuntu1.12), Node.js 24.22.1 (nvm 0.40.8), ws 8.22
- Test server
- DigitalOcean · 1 vCPU / 2 GB RAM / 50 GB SSD (s-1vcpu-2gb, sgp1)
- Last checked
- 2026-10-27
This guide contains affiliate links. If you sign up through them, Codesand may earn a commission. This doesn't affect the content or our assessments.
This guide puts a Node.js app behind Nginx on an Ubuntu 26.04 server and connects it with a reverse proxy. It covers proxy_pass and header settings, the Upgrade settings needed when WebSocket does not connect, the 502 error when the app is down, and keeping the app running with systemd.
1. Requirements
- One Ubuntu 26.04 LTS server with Nginx installed (see How to Install Nginx on Ubuntu 26.04 and Open the Firewall; port 80 allowed in ufw)
- Node.js installed with nvm (see How to Install Node.js with nvm on Ubuntu 26.04)
- SSH access with a regular user account that has
sudoprivileges - A PC to test access from outside
If you don't have a server, try creating a DigitalOcean Droplet (1 vCPU, 2 GB). Every step in this guide was verified on a Droplet (1 vCPU, 2 GB memory, 50 GB SSD, Ubuntu 26.04, Singapore) with Nginx 1.28.3, using a regular user account (devuser) running Node.js 24.22.1 installed with nvm. External access was tested from another PC (example IP 203.0.113.10) to the server (example IP 203.0.113.20).
2. Create a Node.js app for testing
Check the installed Node.js version.
node -vv24.22.1Create the app folder and a package.json file. The output of npm init -y (the contents of package.json) is omitted.
mkdir ~/myapp && cd ~/myapp
npm init -yInstall the ws package, which creates a WebSocket server.
npm install wsadded 1 package, and audited 2 packages in 1s
found 0 vulnerabilitiesThis app returns the request headers it received for HTTP requests. For WebSocket connections, it sends connected and then returns each received message with echo: in front. The app accepts connections only on 127.0.0.1:3000, so it can be reached from outside only through Nginx. The command prints nothing.
cat > ~/myapp/app.js <<'EOF'
const http = require('http');
const { WebSocketServer } = require('ws');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(
`Hello from Node.js ${process.version}\n` +
`Host: ${req.headers.host}\n` +
`X-Real-IP: ${req.headers['x-real-ip']}\n` +
`X-Forwarded-For: ${req.headers['x-forwarded-for']}\n` +
`X-Forwarded-Proto: ${req.headers['x-forwarded-proto']}\n`
);
});
const wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
ws.send('connected');
ws.on('message', (msg) => ws.send(`echo: ${msg}`));
});
server.listen(3000, '127.0.0.1', () => {
console.log('Listening on http://127.0.0.1:3000');
});
EOFRun the app. Keep this terminal open while the app is running.
cd ~/myapp
node app.jsListening on http://127.0.0.1:3000Open a new terminal (for SSH, connect once more) and send a request directly to the app. Because the request did not go through a proxy, all headers starting with X- are undefined.
curl http://127.0.0.1:3000Hello from Node.js v24.22.1
Host: 127.0.0.1:3000
X-Real-IP: undefined
X-Forwarded-For: undefined
X-Forwarded-Proto: undefinedPort 3000 is open only on the server itself (127.0.0.1).
sudo ss -tlnp | grep 3000LISTEN 0 511 127.0.0.1:3000 0.0.0.0:* users:(("MainThread",pid=5890,fd=21))Check WebSocket from inside the server as well. Node.js 24 includes a WebSocket client, so there is nothing else to install.
node -e "const ws = new WebSocket('ws://127.0.0.1:3000'); ws.onmessage = (e) => { console.log(e.data); if (e.data === 'connected') ws.send('hello'); else ws.close(); };"connected
echo: hello3. Configure the Nginx reverse proxy
First, create a site file with a basic configuration that passes only HTTP. The command prints nothing.
sudo tee /etc/nginx/sites-available/myapp > /dev/null <<'EOF'
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
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;
}
}
EOFproxy_pass: The address of the app that receives the requests.Host: Passes the domain (or IP) requested by the browser to the app as is. Without it, the app receives127.0.0.1:3000.X-Real-IP,X-Forwarded-For: The real IP of the visitor. Without them, every request appears to the app to come from Nginx (127.0.0.1).X-Forwarded-Proto: Tells the app whether the browser connected over http or https.
Enable the site and remove the link to the default site. If both sites are marked default_server, the configuration test fails.
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/ && sudo rm /etc/nginx/sites-enabled/default
sudo nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulsudo systemctl reload nginxConnect to the server IP from the PC (203.0.113.10). The Host and IP that the app received now show the values sent from the PC.
curl http://203.0.113.20Hello from Node.js v24.22.1
Host: 203.0.113.20
X-Real-IP: 203.0.113.10
X-Forwarded-For: 203.0.113.10
X-Forwarded-Proto: http4. Configure WebSocket connections
Try connecting over WebSocket from the PC. This PC has no WebSocket client, so a Node.js image was run with Docker to use wscat. -x hello sends hello after connecting, and -w 1 waits 1 second for a reply after sending and then exits. Because of the --rm option, the container is deleted automatically when it finishes. The line about a new npm version is omitted.
docker run --rm -t node:24-alpine npx -y wscat -c ws://203.0.113.20 -x hello -w 1Unexpected server response: 200WebSocket first connects over HTTP and then asks to switch the connection protocol with the Upgrade: websocket header. Nginx does not pass this header to the app, so the app treats it as a normal HTTP request and returns 200. The client never receives the response saying the protocol has switched (101), so it closes the connection. The Nginx access log also records 200.
sudo tail -n 1 /var/log/nginx/access.log203.0.113.10 - - [27/Oct/2026:08:40:50 +0000] "GET / HTTP/1.1" 200 143 "-" "-"Add the WebSocket settings to the configuration file. The command prints nothing.
sudo tee /etc/nginx/sites-available/myapp > /dev/null <<'EOF'
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
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;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 3600s;
}
}
EOFmap: Sets theConnectionvalue toupgradeif the request has anUpgradeheader, and tocloseif it does not. This lets the same location handle both normal HTTP requests and WebSocket requests.proxy_http_version 1.1: Nginx uses HTTP/1.1 when sending requests to the app. Switching protocols (Upgrade) is a feature of HTTP/1.1.Upgrade,Connection: Pass the browser's request to switch to WebSocket on to the app.proxy_read_timeout 3600s: The connection is closed only after nothing has come from the app for one hour. The default is 60 seconds; if no data comes from the app in that time, Nginx closes the connection.
sudo nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulsudo systemctl reload nginxConnect from the PC again, and you see connected sent by the app and the reply to hello.
docker run --rm -t node:24-alpine npx -y wscat -c ws://203.0.113.20 -x hello -w 1connected
echo: helloThe status code in the access log has changed to 101 (Switching Protocols).
sudo tail -n 1 /var/log/nginx/access.log203.0.113.10 - - [27/Oct/2026:08:41:10 +0000] "GET / HTTP/1.1" 101 26 "-" "-"Normal HTTP requests still work.
curl http://203.0.113.20Hello from Node.js v24.22.1
Host: 203.0.113.20
X-Real-IP: 203.0.113.10
X-Forwarded-For: 203.0.113.10
X-Forwarded-Proto: http5. When the app is down: 502 Bad Gateway
If you stop the app by pressing Ctrl+C in the terminal where you ran node app.js and then connect from the PC, you get a 502 error. This means Nginx is working, but there is no app to pass the request to.
curl -i http://203.0.113.20HTTP/1.1 502 Bad Gateway
Server: nginx/1.28.3 (Ubuntu)
Date: Tue, 27 Oct 2026 08:41:26 GMT
Content-Type: text/html
Content-Length: 166
Connection: keep-alive
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.28.3 (Ubuntu)</center>
</body>
</html>The Nginx error log records that it could not connect to 127.0.0.1:3000 (111: Connection refused).
sudo tail -n 1 /var/log/nginx/error.log2026/10/27 08:41:26 [error] 7151#7151: *12 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.10, server: _, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "203.0.113.20"An app started from a terminal stops when you close the terminal or reboot the server. If you register it as a systemd service as in the next step, the app keeps running. Other causes of 502 are covered in How to Fix Nginx 502 Bad Gateway.
6. Keep the app running with systemd
The systemd service file must contain the full path to node. This is because Node.js installed with nvm lives in your user folder, and systemd does not read the nvm settings. Check the path with which node.
which node/home/devuser/.nvm/versions/node/v24.22.1/bin/nodeCreate the service file. Replace devuser in User and in the paths with your own user name. Restart=on-failure restarts the app if it stops because of an error. The command prints nothing.
sudo tee /etc/systemd/system/myapp.service > /dev/null <<'EOF'
[Unit]
Description=myapp (Node.js)
After=network.target
[Service]
User=devuser
WorkingDirectory=/home/devuser/myapp
ExecStart=/home/devuser/.nvm/versions/node/v24.22.1/bin/node app.js
Restart=on-failure
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
EOFHave systemd read the new file, then start the service and make it start automatically on reboot. enable --now does both at once.
sudo systemctl daemon-reload
sudo systemctl enable --now myappCreated symlink '/etc/systemd/system/multi-user.target.wants/myapp.service' → '/etc/systemd/system/myapp.service'.systemctl status myapp --no-pager | head -4● myapp.service - myapp (Node.js)
Loaded: loaded (/etc/systemd/system/myapp.service; enabled; preset: enabled)
Active: active (running) since Tue 2026-10-27 08:41:41 UTC; 959ms ago
Invocation: 9185fc7b0eab4a63bea8654a295031f3curl http://203.0.113.20Hello from Node.js v24.22.1
Host: 203.0.113.20
X-Real-IP: 203.0.113.10
X-Forwarded-For: 203.0.113.10
X-Forwarded-Proto: httpCheck that the app restarts when it stops unexpectedly. kill -9 forcibly ends the app process. $(systemctl show -p MainPID --value myapp) is replaced with the process ID of the service. The command prints nothing.
sudo kill -9 $(systemctl show -p MainPID --value myapp)Check the status a few seconds later, and the app is running again.
systemctl is-active myappactiveYou can see the app's output (console.log) and the restart record with journalctl.
sudo journalctl -u myapp --no-pager -n 6Oct 27 08:41:41 opendoc-nginx-10271716 node[7859]: Listening on http://127.0.0.1:3000
Oct 27 08:41:43 opendoc-nginx-10271716 systemd[1]: myapp.service: Main process exited, code=killed, status=9/KILL
Oct 27 08:41:43 opendoc-nginx-10271716 systemd[1]: myapp.service: Failed with result 'signal'.
Oct 27 08:41:44 opendoc-nginx-10271716 systemd[1]: myapp.service: Scheduled restart job, restart counter is at 1.
Oct 27 08:41:44 opendoc-nginx-10271716 systemd[1]: Started myapp.service - myapp (Node.js).
Oct 27 08:41:44 opendoc-nginx-10271716 node[7987]: Listening on http://127.0.0.1:30007. Troubleshooting
Unexpected server response: 200
This means the WebSocket client was waiting for the protocol switch response (101) but received a normal response (200). Check that the Nginx configuration has proxy_http_version 1.1, proxy_set_header Upgrade $http_upgrade, and proxy_set_header Connection $connection_upgrade. After editing the configuration, run sudo nginx -t and sudo systemctl reload nginx to apply it. Step 4 shows the actual message and the result after the fix.
connect() failed (111: Connection refused) while connecting to upstream
This message is written to error.log together with a 502 Bad Gateway response. It means no program is accepting connections at the address in proxy_pass. It happens when the app is stopped, or when the port the app uses differs from the port in proxy_pass. Check with sudo ss -tlnp | grep 3000 that the app is running on that port, and if you run it with systemd, check why the app stopped in sudo journalctl -u myapp --no-pager -n 20.
curl: (28) Connection timed out after 5009 milliseconds
This appears when you connect from the PC directly to the app port, as in http://203.0.113.20:3000. The app accepts connections only on 127.0.0.1, and ufw does not open port 3000 either, so the PC cannot connect to http://203.0.113.20:3000. This is intended, so connect to the Nginx address (port 80) instead. --max-time 5 waits for at most 5 seconds.
curl --max-time 5 http://203.0.113.20:3000curl: (28) Connection timed out after 5009 milliseconds8. Uninstall
Stop the service and disable automatic start.
sudo systemctl disable --now myappRemoved '/etc/systemd/system/multi-user.target.wants/myapp.service'.Delete the service file and have systemd read the files again. The commands print nothing.
sudo rm /etc/systemd/system/myapp.service
sudo systemctl daemon-reloadDelete the Nginx site configuration and enable the default site again.
sudo rm /etc/nginx/sites-enabled/myapp /etc/nginx/sites-available/myapp
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/
sudo nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulsudo systemctl reload nginxDelete the app folder. The command prints nothing. To remove Node.js and nvm as well, follow the Uninstall section of the nvm guide.
rm -rf ~/myappsystemctl status myapp --no-pagerUnit myapp.service could not be found.Connect from the PC, and the Nginx default page is shown.
curl -s http://203.0.113.20 | grep -o "<title>.*</title>"<title>Welcome to nginx!</title>Try it yourself
No server yet? You can spin up an Ubuntu server in a few minutes with one of these providers. We verified this guide on DigitalOcean.
Was this guide helpful? Let us know if anything is wrong or out of date.
Request a correction