October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Install Express and Set Up Socket.IO on a VPS

A complete VPS deployment guide for Express and Socket.IO: wire both to one Node HTTP server, proxy WebSocket upgrades through Nginx, keep the process alive with PM2 or systemd, and verify reboot-safe operation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run Express and Socket.IO on the same Node.js HTTP server, keep that server bound to localhost, place Nginx in front of it, and use one process supervisor to recover the app after crashes and reboots. The procedure below covers installation, proxying WebSocket upgrades, proxy-aware Express settings, verification, and the limits of scaling beyond one process.

What the finished deployment looks like

A reliable VPS deployment has four layers:

  • Node.js application: Express handles HTTP routes and Socket.IO handles realtime connections on one shared HTTP server.
  • Process supervisor: PM2 or systemd starts the process at boot, restarts it after a failure, and exposes logs.
  • Nginx: The public listener terminates TLS (when configured), forwards normal HTTP requests, and passes WebSocket upgrade headers to Node.
  • Network boundary: The Node port listens on 127.0.0.1, so clients cannot bypass Nginx directly.

For a single VPS running one Node process, Socket.IO does not need a multi-process adapter. That changes if you use cluster mode or more than one host.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prerequisites before installing the application

  • A VPS with a supported Linux distribution, a non-root administrative account, and enough memory for your Node application and Nginx.
  • A domain name whose DNS record points to the VPS. Use the final hostname in the Nginx server_name directive and in your browser or Socket.IO client.
  • Node.js installed using the VPS provider’s supported method. This keeps the binary, package manager, and security updates aligned with that provider’s images and documentation.
  • Firewall rules allowing public HTTP (port 80) and HTTPS (port 443, once TLS is enabled). Do not expose the internal application port publicly when Nginx is the entry point.

Check the runtime after installation:

node --version
npm --version

The exact Node.js major version is not fixed by this guide; use a version supported by your application dependencies and VPS image, and keep it updated through the same installation method.

Create the Express and Socket.IO application

Initialize a project

Create a directory owned by the account that will run the service, then install the two runtime dependencies:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
mkdir my-realtime-app && cd my-realtime-app
npm init -y
npm install express socket.io

This creates package.json and a lockfile. Keep both under version control so deployments can reproduce the dependency tree with npm ci when your workflow is ready.

Attach Socket.IO to the Express HTTP server

Save the following as server.js:

const express = require('express');
const { createServer } = require('node:http');
const { Server } = require('socket.io');

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: { origin: process.env.CLIENT_ORIGIN || false }
});

app.get('/health', (_req, res) => res.json({ ok: true }));

io.on('connection', (socket) => {
  console.log('connected', socket.id);
  socket.on('disconnect', (reason) => {
    console.log('disconnected', reason);
  });
});

const port = process.env.PORT || 3000;
httpServer.listen(port, '127.0.0.1', () => {
  console.log(`listening on ${port}`);
});

The important wiring is createServer(app) followed by new Server(httpServer). Do not start Express with a separate app.listen() and then expect Socket.IO to receive those connections; Socket.IO must be attached to the HTTP server that accepts the traffic.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

CLIENT_ORIGIN should contain the exact browser origin that is allowed to connect, such as https://app.example.com. Avoid a broad wildcard when your application uses credentials. If the client and server are intentionally same-origin, leaving the variable unset keeps the example restrictive; set it explicitly when the frontend is hosted elsewhere.

Run a local smoke test on the VPS

Start the program temporarily to catch syntax and environment errors:

node server.js

In a second SSH session, request the private health endpoint:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
curl -s http://127.0.0.1:3000/health

The expected response is JSON containing ok set to true. Stop the foreground process with Ctrl+C before handing it to a supervisor.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep Node running after crashes and reboots

Running node server.js in an SSH shell is a development convenience, not a production recovery strategy. Select one supervisor. Running PM2 and systemd against the same process creates competing restart and boot policies.

Option A: PM2

Install PM2 globally, start the application, and save the process list:

sudo npm install -g pm2
pm2 start server.js --name realtime-app
pm2 save
pm2 startup

pm2 startup prints a command that must be run with the privileges it requests. Execute that printed command, then run pm2 save again if prompted so the current process list is restored during boot.

Useful operational commands are:

pm2 status
pm2 logs realtime-app
pm2 restart realtime-app
pm2 stop realtime-app

PM2 is convenient when you want an application-oriented command line, quick restarts, and an eventual path to cluster mode. Keep the PM2 process under the intended service account; do not start it once as root and later as another user, because each account has a separate process list and startup configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Option B: systemd

systemd is the operating system’s service manager. Create a unit such as /etc/systemd/system/realtime-app.service, adjusting the account, directory, and Node path for your VPS:

[Unit]
Description=Express Socket.IO application
After=network.target

[Service]
Type=simple
User=YOUR_APP_USER
WorkingDirectory=/path/to/my-realtime-app
ExecStart=/usr/bin/node /path/to/my-realtime-app/server.js
Environment=NODE_ENV=production
Environment=PORT=3000
Environment=CLIENT_ORIGIN=https://app.example.com
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

On distributions where Node is installed somewhere other than /usr/bin/node, use the path returned by command -v node for the service account. Reload units, enable the service at boot, and start it:

sudo systemctl daemon-reload
sudo systemctl enable --now realtime-app
sudo systemctl status realtime-app
sudo journalctl -u realtime-app -f

The unit’s Restart=always setting asks systemd to bring the process back after an exit. Restricting the service to a dedicated unprivileged user limits the impact of an application compromise. Add environment values through the unit, an environment file, or your deployment secret mechanism rather than hard-coding credentials in source.

PM2 or systemd: which fits a single VPS?

Concern PM2 systemd
Crash recovery Managed by PM2’s process supervisor. Managed by the operating system with Restart=always (or a more specific restart policy).
Boot persistence pm2 startup plus a saved process list. systemctl enable registers the unit with the boot target.
Logs pm2 logs and PM2’s log files. journalctl -u realtime-app and the system journal.
Deployment ergonomics Short commands for start, reload, status, and application-focused workflows. Declarative unit files, explicit users, environment, limits, and dependency ordering.
Privilege boundary Run PM2 as the application user; global installation normally needs administrative privileges. The unit can state the exact User, working directory, and executable.
Cluster mode PM2 can launch multiple workers, which introduces Socket.IO affinity and adapter requirements. Multiple workers require a separate design (for example, templated units or another supervisor) and the same Socket.IO coordination requirements.

Configure Nginx as the public reverse proxy

Forward HTTP and WebSocket upgrades

With Node listening on 127.0.0.1:3000, configure a server block similar to this one:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name example.com;

    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 "upgrade";
        proxy_read_timeout 75s;
    }
}

Place the file in the location used by your distribution, test the configuration, and reload Nginx through its service manager. The exact enablement path differs between distributions.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

proxy_http_version 1.1, Upgrade, and Connection are required for an HTTP connection to switch to WebSocket. The forwarded host, address, and protocol headers preserve the original request context for the application.

Set a timeout longer than Socket.IO’s heartbeat

Socket.IO’s documented defaults add up to 45 seconds for pingInterval + pingTimeout. Nginx documents a 60-second default for proxy_read_timeout; that is too close to the heartbeat boundary, so the example uses 75 seconds. Keep the proxy timeout greater than the sum of the values your Socket.IO server actually uses. If you later change either heartbeat setting, recalculate this margin and reload Nginx.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A premature timeout usually appears as regular disconnects after an idle period, even though the initial connection succeeds. Check the browser and Node logs, then compare the observed interval with both Socket.IO heartbeat settings and Nginx’s read timeout.

Add HTTPS and redirect plain HTTP

Use the certificate tooling supported by your VPS distribution to obtain a certificate, then configure Nginx to listen on 443 with that certificate and redirect port 80 to HTTPS. Once HTTPS is active, set CLIENT_ORIGIN to the HTTPS origin and have the client connect using that same public origin. Do not leave a production realtime endpoint on an unencrypted public connection when users or credentials cross it.

Tell Express which proxy headers it may trust

Nginx is a proxy, so Express may need to use its forwarded values for secure-cookie decisions and for req.ip, req.protocol, or req.hostname. Trust only the proxy addresses that actually sit in front of the application. When Nginx runs on the same VPS, a narrow setting is:

app.set('trust proxy', 'loopback');

If a separate load balancer or proxy connects to Node over a private address, configure that address or subnet instead of blindly trusting every hop. The correct value depends on your topology and the number of proxies.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Your proxy should overwrite, rather than blindly pass through, X-Forwarded-For, X-Forwarded-Host, and X-Forwarded-Proto. If an untrusted client can supply those headers and Express trusts them, the client may influence the apparent IP address, protocol, or hostname. A wrong trust setting can also cause HTTPS redirects, secure cookies, rate limits, and audit logs to behave incorrectly.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Verify each layer in order

  1. Check Node directly: On the VPS, run curl -s http://127.0.0.1:3000/health. Confirm the JSON health response before involving Nginx.
  2. Check the supervisor: With PM2, inspect pm2 status and pm2 logs. With systemd, use systemctl status realtime-app and journalctl -u realtime-app. Resolve startup errors before moving on.
  3. Check Nginx locally or externally: Request https://example.com/health from a client that resolves the public hostname. A successful response proves that DNS, TLS (if enabled), Nginx routing, and the Node health route work together.
  4. Check a Socket.IO connection: Configure a client to use the public HTTPS origin and confirm its connect event. Watch both browser developer tools and the Node log for the connection ID.
  5. Check an idle connection: Leave the client idle beyond the normal heartbeat interval. It should remain connected; repeated disconnects point to a heartbeat, proxy timeout, network, or process problem.
  6. Check recovery: During controlled maintenance, reboot the VPS once. Verify that the supervisor starts the application, Nginx serves /health, and a new Socket.IO client can connect.

Troubleshoot common deployment failures

HTTP health check works, but Socket.IO fails

  • Confirm Nginx uses proxy_http_version 1.1 and forwards both upgrade headers exactly as shown.
  • Check that the client uses the public hostname and the correct scheme. A page loaded over HTTPS should not try to open an insecure WebSocket endpoint.
  • Inspect the browser’s Network panel for the Socket.IO polling request and upgrade response. A 404 usually means the request is reaching the wrong location or application; a 400/403 can indicate origin or application-level rejection.
  • Make sure the Node process actually owns port 3000 and that Nginx’s proxy_pass points to the same port.

Connections drop after roughly a minute

  • Compare proxy_read_timeout with the current pingInterval + pingTimeout. Increase the proxy value above that sum, then test and reload Nginx.
  • Look for another load balancer, firewall, or idle connection policy between the client and Nginx. Every intermediary must allow the heartbeat traffic.
  • Check supervisor logs for process restarts. A Node crash can look like a network disconnect from the browser.

req.ip or HTTPS detection is wrong

  • Verify that Nginx sets the forwarded headers and that Express trusts only the real proxy address or subnet.
  • Remove any client-supplied forwarded headers at the edge or configure the proxy to overwrite them.
  • Do not solve an incorrect topology by setting app.set('trust proxy', true) indiscriminately; that can make spoofed values appear authoritative.

The service starts manually but not at boot

  • For PM2, run the command printed by pm2 startup with the requested privileges, then save the process list again as the same account that owns the application.
  • For systemd, check the unit’s absolute ExecStart path, WorkingDirectory, User, and environment values. Run systemctl status and journalctl to see the first boot error.
  • Ensure the application does not depend on an interactive shell profile to find Node or secrets.

Deploy updates without creating a second process

Keep the application directory, lockfile, and service configuration separate from transient logs. A typical update sequence is:

  1. Fetch the new application revision into the deployment directory.
  2. Run npm ci to install the lockfile’s exact dependencies.
  3. Run a local or staging health check and verify environment variables.
  4. Restart the one supervisor-managed process: pm2 restart realtime-app or sudo systemctl restart realtime-app.
  5. Request the public /health endpoint and open a new Socket.IO connection.

Existing realtime clients may disconnect during a process restart. If uninterrupted connections are a requirement, design a rolling or redundant deployment deliberately; do not assume that restarting a single VPS process preserves sockets.

Know when one process is no longer enough

One VPS, one Node process

Characteristic Single process
Routing Every client reaches the same Socket.IO instance through Nginx.
Sticky sessions Not required.
Cross-worker adapter Not required.
Failure scope A process failure disconnects its clients, but the supervisor can restart it.
Operational complexity Lowest; suitable for an initial VPS deployment.

PM2 cluster mode or multiple hosts

Adding workers changes Socket.IO’s assumptions. Polling requests from one client must reach the same worker, so the front end needs sticky sessions (connection affinity). Broadcasts emitted by one worker must also reach clients connected to other workers, so Socket.IO needs a cross-worker adapter. A multi-host design may use a shared adapter such as Redis, but compatibility, network access, persistence, authentication, and failure behavior must be verified for your chosen adapter before treating it as a default.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Concern Single process Cluster or multiple hosts
Connection affinity All requests already reach one worker. Sticky sessions are required when polling can occur across workers.
Broadcast delivery In-memory events reach every connected client in that process. A cross-worker adapter is required for events to cross process or host boundaries.
Failure isolation One process is a single failure domain. Workers can isolate some failures, but proxy and adapter failures add new dependencies.
Operations One supervisor and one log stream. Affinity, adapter health, worker counts, deploy ordering, and shared infrastructure must be monitored.

Do not enable cluster mode merely to use more CPU without implementing both affinity and an adapter. Otherwise, clients may connect successfully yet miss broadcasts or fail during the polling-to-WebSocket transition.

Production hardening checklist

  • Bind Node to 127.0.0.1 (or an intentionally private interface) when Nginx is the public entry point.
  • Allow only the required public ports in the VPS firewall; keep port 3000 private.
  • Use HTTPS and set the allowed client origin explicitly.
  • Run the Node process as a dedicated unprivileged user.
  • Store secrets outside source control and provide them through the supervisor’s environment mechanism.
  • Set Express’s trust proxy value to match the actual proxy addresses, not to every possible address.
  • Set Nginx’s read timeout above the Socket.IO heartbeat sum and revisit it whenever heartbeat settings change.
  • Monitor supervisor status and logs, and test reboot recovery during a maintenance window.
  • When scaling to workers or hosts, implement sticky sessions and a compatible cross-worker adapter before production traffic arrives.

Final deployment sequence

Install Node.js through the VPS-supported method, create the project, and install Express and Socket.IO. Wire Socket.IO to the HTTP server created from the Express app, bind Node privately, and verify /health. Choose either PM2 or systemd for restart and boot persistence. Configure Nginx for HTTP/1.1 upgrades, forwarded headers, and a read timeout above the heartbeat period; then add HTTPS and set the correct client origin. Finally, test direct health, proxied health, a realtime connection, idle heartbeats, logs, and reboot recovery. Stay with one process until you are prepared to operate session affinity and a cross-worker adapter.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.