Back to blog
Guides

Host Node.js apps next to PHP sites with Nginx and systemd

A client needs a small Node.js API or a websocket service next to their WordPress site. You don't need a second server or a process manager in a tmux session. Here's how to run Node apps properly with systemd, environment files and an Nginx reverse proxy, and the traps that cause 2 a.m. outages.

S
ShadowPanel Team
9 min read

Sooner or later a PHP server gets a Node.js guest. A client wants a small API behind their WordPress site, a booking widget needs a websocket backend, or the marketing team ships a Next.js landing page. The usual first attempt is node app.js & in an SSH session, or a process manager started by hand inside tmux. It runs fine for a week, then the server reboots for a kernel update and the app quietly never comes back. You don't need a second server for Node, and you don't need anything exotic. The tools already on every modern Linux box, systemd and Nginx, run Node apps reliably right next to your PHP sites. Here's how to do it properly.

The architecture in one picture

Browser  →  Nginx :443  -+-  /        →  PHP-FPM (WordPress)
                         +-  /api/    →  127.0.0.1:3001 (Node app)

Nginx stays the only thing listening on the public ports. It terminates TLS, serves static files, hands .php requests to PHP-FPM and proxies selected paths (or a whole domain) to a Node process listening on a local port. The Node app never faces the internet directly. That single rule makes everything else simpler: one certificate setup, one place for access logs, one firewall rule set.

Step 1: run the app as a systemd service

systemd is already managing every other service on your server. It starts things at boot, restarts them when they crash, collects their output into the journal and can cap their resources. A unit file for a Node app is short:

# /etc/systemd/system/booking-api.service
[Unit]
Description=Booking API (Node.js)
After=network.target

[Service]
Type=simple
User=siteuser
Group=siteuser
WorkingDirectory=/var/www/siteuser/booking-api
EnvironmentFile=/var/www/siteuser/booking-api/.env
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=5

# Hardening
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ReadWritePaths=/var/www/siteuser/booking-api/storage
MemoryMax=512M

[Install]
WantedBy=multi-user.target

Then:

systemctl daemon-reload
systemctl enable --now booking-api
journalctl -u booking-api -f

A few lines deserve a closer look:

  • User= is not optional. Run each app as the same unprivileged user that owns the site, never as root. A remote code execution bug in an npm dependency then stays inside that one user's files.
  • ExecStart needs an absolute path. systemd doesn't read your shell profile, so a Node installed through nvm in someone's home directory is invisible to it. Use the system Node, or the full path to the specific binary.
  • NoNewPrivileges and PrivateTmp are cheap wins: the process can't gain privileges through setuid binaries, and it gets its own /tmp that other users can't see. ProtectSystem=strict makes the whole filesystem read-only except the paths you list.
  • MemoryMax stops one leaking app from pushing the PHP sites into swap. Check what a unit is allowed to do with systemd-analyze security booking-api.

Do you still need PM2? For a single process, no. systemd already restarts, starts at boot and keeps logs. If you want multiple workers to use several CPU cores, Node's built-in cluster module or a second unit on another port behind the same Nginx upstream does the job.

Step 2: keep secrets in an environment file

API keys and database passwords belong in an environment file, not in the unit itself. Unit files in /etc/systemd/system are world-readable, and systemctl show prints Environment= lines to any local user. An EnvironmentFile can be locked down:

chown siteuser:siteuser /var/www/siteuser/booking-api/.env
chmod 600 /var/www/siteuser/booking-api/.env
PORT=3001
NODE_ENV=production
DATABASE_URL=postgres://booking:secret@127.0.0.1/booking

NODE_ENV=production matters more than it looks: Express, Next.js and many libraries switch off debug output and enable caching only when it's set. And keep this file out of Git.

Step 3: bind to localhost and assign ports deliberately

Have the app read its port from the environment and listen on the loopback interface only:

app.listen(process.env.PORT, '127.0.0.1');

If you write app.listen(3001), Node listens on every interface, and your app is reachable at http://your-ip:3001, bypassing TLS and anything Nginx enforces. Your firewall probably blocks it, but don't make the firewall your only line of defence. Check what's listening with ss -ltnp.

With several apps on one server, give ports a system: a fixed range (say 3001 to 3999), one port per app, written down somewhere. Two apps fighting for the same port is a classic "it worked yesterday" outage.

Step 4: the Nginx reverse proxy, websockets included

Inside the site's server block:

location /api/ {
    proxy_pass http://127.0.0.1:3001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    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_read_timeout 300s;
}

proxy_http_version 1.1 plus the Upgrade and Connection headers are what let websockets (Socket.IO, live dashboards, chat) through; without them the upgrade handshake fails and clients fall back to polling, or break. If many idle sockets stay open, raise proxy_read_timeout, because Nginx closes a proxied connection after 60 seconds of silence by default; or have the app send pings. The X-Forwarded-* headers tell the app the real client IP and that the original request was HTTPS. In Express, enable app.set('trust proxy', 'loopback') so req.ip and req.secure use them.

Step 5: whole domain or sub-path?

You can give the Node app an entire domain (its own location /) or mount it under a path of an existing PHP site. Sub-paths are handy, but they come with two traps.

First, the trailing slash on proxy_pass changes the URL the app receives. proxy_pass http://127.0.0.1:3001; passes /api/users through unchanged. proxy_pass http://127.0.0.1:3001/; strips the prefix, so the app sees /users. Either is fine, but the app has to agree: frameworks like Next.js have a basePath setting for exactly this, and links and asset URLs must include the prefix.

Second, location matching. A site that already has a location / block can't simply get a second one; Nginx rejects duplicates. And a regex location such as location ~ \.php$ wins over a plain prefix location, so a request to /api/test.php would go to PHP, not Node. Use location ^~ /api/ if your app path could ever match a regex.

The traps that cause 2 a.m. outages

  • Installing dependencies as root. Run npm ci --omit=dev as the site user, from the lockfile, so production gets exactly what you tested and nothing writes root-owned files into the app directory.
  • Listening on 0.0.0.0. Covered above; it's the most common one.
  • Logging to files nobody rotates. Write logs to stdout and let the journal handle storage and rotation. journalctl -u booking-api --since "1 hour ago" beats grepping a 6 GB app.log.
  • Restart loops. An app that crashes on startup gets restarted forever. systemd's StartLimitIntervalSec and StartLimitBurst stop it after a few attempts so the failure is visible in systemctl status.
  • Forgetting the restart after a deploy. Node keeps the old code in memory until the process restarts. Your deploy script ends with systemctl restart booking-api. (More on scripted deploys in Git push to deploy for PHP sites.)
  • Mixing tenants. Two clients' apps under one user can read each other's .env. One Linux user per site, as in hosting multiple client sites on one VPS.

If an app needs a different runtime entirely or system packages you don't want on the host, a container is the better fit; see Docker containers per website.

How ShadowPanel runs Node.js apps

ShadowPanel, a self-hosted hosting control panel, has Node.js app hosting built in on the Pro and Agency plans. It wires up exactly the setup described above:

  • A systemd unit per app, running as the site's own Linux user. You point the panel at your entry file inside the site's directory; it creates a unit that runs it with the server's Node.js (the installer sets up Node 22 LTS), restarts it automatically if it dies, and sets NoNewPrivileges and PrivateTmp.
  • Environment variables in a locked-down file. Variables you add in the panel go into an environment file with mode 600, owned by the site user. PORT and NODE_ENV=production are set for you.
  • Ports allocated automatically from the 3001 to 3999 range, so two apps never collide. Nginx proxies to 127.0.0.1 on that port; your app just listens on process.env.PORT, ideally bound to 127.0.0.1.
  • A websocket-capable proxy, mounted where you want. Mount the app at a sub-path of the site, or at / to have it serve the whole domain. Mounting at / takes over the site's default location /, keeps the original lines as comments and restores them exactly when you remove the app. A sub-path that another location already handles is refused rather than silently shadowed. The path is passed to the app unchanged, so a sub-path app should know its base path.
  • Safe changes. Every vhost change is checked with nginx -t; if Nginx rejects it, the previous config is restored and the new unit removed, so a bad setup never takes the PHP site down with it.
  • Start, stop, restart, status and logs (straight from the journal) from the site's page.

Installing dependencies and building the app stays your call: run npm ci over SSH before starting it, the same way you would by hand.

The bottom line

Running Node.js next to PHP is a solved problem: a systemd unit per app as an unprivileged user, secrets in a 600 environment file, the process bound to localhost on a known port, and Nginx in front with the websocket headers set. Get those right and your Node apps survive reboots, crashes and deploys as calmly as your PHP sites do. ShadowPanel turns all of it into a form: pick the entry file, choose where to mount it, add your variables, done.

curl -fsSL https://shadowpanel.de/install.sh | bash

See pricing and download →

We use cookies

We use cookies to improve your experience and remember your preferences. You can manage your choices below. Learn more.

ShadowPanel

Manage your cookie preferences below. Essential cookies are always active as they are required for the website to function.

Essential

Required for the site to work. These include session authentication and CSRF protection. Cannot be disabled.

Always on

Functional

Remembers your language preference so you do not need to reselect it on every visit.

Analytics

Helps us understand how visitors use the site so we can improve it. No personal data is sold.

Marketing

Used by Google Ads to measure ad conversions and improve campaign targeting. No personal data is sold.