Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
VGSOURCES
Get listed

NGINXPATCH 2026.10.15

How to Run a Node.js TCP Server with PM2 and Nginx on a VPS

By VGSources Team 9 min read

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.

Run the Node.js process on a private loopback port, let PM2 supervise it and restore it after reboots, then expose a different public port through Nginx’s stream {} context. This arrangement keeps the application port off the Internet, provides process and log management, and gives Nginx control over the public listener, timeouts and optional TLS.

The important distinction is protocol: a raw TCP service is not an HTTP application. Nginx must use a stream server, not an HTTP location block. The example below uses public port 4000 and a Node.js listener on private port 4001.

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.

What the finished deployment looks like

A client connects to the VPS on TCP port 4000. Nginx accepts that connection and proxies the byte stream to Node.js on 127.0.0.1:4001. PM2 starts the Node.js script, restarts it when it exits, exposes status and logs, and restores the saved process list during boot.

  • Public edge: Nginx listens on the firewall-exposed port.
  • Application: Node.js binds to loopback or another private interface.
  • Supervisor: PM2 manages the process independently of your SSH session.
  • Persistence: pm2 startup installs the boot hook and pm2 save records which processes to resurrect.

Do not bind Nginx and Node.js to the same address and port. The operating system can assign a listening socket only once, so use separate ports even when both services run on the same VPS.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses | Anti UV Ray, For Computers & Gaming, Square Frame, Eyewear for Men and Women
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Prerequisites and layout

You need a VPS with administrative access, Node.js and npm installed, Nginx installed with stream support, and a DNS name or client configuration that points to the VPS’s public address. The commands below assume a Debian-like filesystem and a project directory at /srv/my-tcp-app; adjust paths for your distribution.

Create the application directory and make sure the account that runs the service can read its files. A dedicated unprivileged service account is preferable to running the application as root. Keep the Node.js port private in the VPS firewall and expose only Nginx’s public port.

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

Build the Node.js TCP server

Node’s asynchronous node:net API supplies stream-based TCP servers and clients. net.createServer() receives each accepted socket; your callback then implements the application protocol.

Minimal server

// server.js
import net from 'node:net';

const host = process.env.HOST || '127.0.0.1';
const port = Number(process.env.PORT || 4001);

const server = net.createServer((socket) => {
  socket.setEncoding('utf8');
  socket.on('data', (chunk) => {
    // Replace this echo with your application protocol.
    socket.write(chunk);
  });
  socket.on('error', (err) => console.error('socket error', err));
});

server.on('error', (err) => {
  console.error('server error', err);
  process.exitCode = 1;
});

server.listen(port, host, () => {
  console.log(`TCP server listening on ${host}:${port}`);
});

The example echoes received text only to prove that the connection works. Replace the data handler with framing, authentication, validation and responses for your protocol. TCP delivers an ordered byte stream, not message boundaries; your application must decide how a message starts and ends.

The explicit default of 127.0.0.1:4001 prevents direct external connections when Nginx is the public edge. Set HOST to a private network address instead if another internal machine must connect directly. Binding to 0.0.0.0 makes the service listen on every interface and should be done only when that exposure is intentional.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Start it directly before adding supervisors

  1. Change to the application directory: cd /srv/my-tcp-app.
  2. Run node server.js.
  3. From the VPS, confirm the process is listening with sudo ss -ltnp | grep ':4001'.
  4. Open a second shell and make a test connection with a suitable TCP client. Stop the foreground process with Ctrl+C after confirming that the protocol responds.

If the file uses ECMAScript import syntax, configure the project as an ES module (for example, with the appropriate type field in package.json) or use the module-file convention supported by your Node.js installation. Resolve module-format errors before moving to PM2.

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

Install PM2 and supervise the process

Install PM2 globally, start the script with a stable name, and use its status and log commands for routine checks.

npm install --global pm2
cd /srv/my-tcp-app
pm2 start server.js --name tcp-server
pm2 status
pm2 logs tcp-server

pm2 status shows whether the process is online, stopped or repeatedly restarting. pm2 logs tcp-server follows the application’s standard output and error streams, including the startup line and socket errors.

PM2 also provides lifecycle commands such as pm2 restart tcp-server, pm2 reload tcp-server, pm2 stop tcp-server and pm2 delete tcp-server. A restart terminates and starts the process; a reload is useful when you have multiple workers and need a rolling replacement, but behavior depends on how your application handles existing connections.

Use an ecosystem file for repeatable settings

An ecosystem file records the working directory, script, environment and process mode in one place. PM2 expects the filename to end in .config.js.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
module.exports = {
  apps: [{
    name: 'tcp-server',
    script: './server.js',
    cwd: '/srv/my-tcp-app',
    instances: 1,
    exec_mode: 'fork',
    env_production: {
      NODE_ENV: 'production',
      HOST: '127.0.0.1',
      PORT: 4001
    }
  }]
};

Save this as /srv/my-tcp-app/ecosystem.config.js and start it with:

cd /srv/my-tcp-app
pm2 start ecosystem.config.js --env production

The cwd setting prevents relative paths from changing when PM2 launches the process. Keep the private port in the ecosystem file aligned with Nginx’s upstream target. You can also define arguments, an interpreter and other environment sets when the application needs them.

Make PM2 start after a reboot

PM2’s process list is separate from the operating system’s boot process. Register its startup integration, then save the processes that should be restored.

pm2 startup
# Run the exact sudo command printed by PM2
pm2 save

pm2 startup prints a command tailored to the current user, Node executable and init system. Copy and run that exact command with the requested privileges; do not substitute a different user or path. pm2 save writes the current process list so the startup hook can resurrect tcp-server.

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

Reboot the VPS and verify recovery with:

pm2 status
pm2 logs tcp-server
sudo systemctl status nginx

If Node.js was installed with NVM, its executable path can change when the shell environment differs from the boot service. Rerun the PM2 startup setup after changing Node versions or NVM paths, then run pm2 save again.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Configure Nginx for raw TCP

HTTP reverse-proxy directives such as location and proxy_pass inside an http {} block do not proxy an arbitrary TCP stream. Put a server inside Nginx’s top-level stream {} context. The installed Nginx build must include the stream core module (enabled with --with-stream) and the stream proxy module that supplies proxy_pass.

Check stream support

Inspect the build options with:

nginx -V 2>&1

Look for stream support in the configure arguments or install a distribution package that provides the stream modules. Module packaging differs by operating system, so confirm the module is loaded according to that distribution’s Nginx configuration before adding the proxy.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Minimal stream configuration

Add the following top-level block to /etc/nginx/nginx.conf, outside the existing http {} block:

stream {
    server {
        listen 0.0.0.0:4000;
        proxy_connect_timeout 5s;
        proxy_timeout 1h;
        proxy_pass 127.0.0.1:4001;
    }
}

Nginx accepts connections on public port 4000, attempts to connect to Node within five seconds, and allows an otherwise idle proxied session to remain for up to one hour. The one-hour value is only an example; select proxy_timeout from the idle behavior required by your protocol. A long-lived game session, a request/response protocol and a short-lived telemetry connection need different policies.

Validate and reload without dropping the master process:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
sudo nginx -t
sudo systemctl reload nginx
sudo ss -ltnp | grep -E ':4000|:4001'

The socket listing should show Nginx on 4000 and Node.js on 4001. If Nginx cannot start because the address is already in use, check for another listener with ss and correct the port assignment rather than enabling conflicting bind options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Firewall and security decisions

  • Allow the public TCP port, such as 4000, in the VPS firewall and provider security group.
  • Do not expose the Node.js port 4001 publicly when Nginx is the edge; allow loopback traffic and any deliberately required private network traffic only.
  • Run the application as a dedicated unprivileged user with least-privilege ownership and file permissions.
  • Keep secrets out of the ecosystem file when its permissions would expose them; use the VPS’s protected environment or secret-management mechanism.
  • Review PM2 output, Nginx error logs and systemd status after deployment and after each configuration change.

Decide where TLS belongs

Raw TCP is not encrypted merely because it passes through Nginx. If the protocol requires TLS, decide whether clients speak TLS end to end to Node.js or whether Nginx terminates TLS in the stream layer. Nginx provides a separate stream SSL module, which must also be present in the build. Certificate handling, client authentication and protocol policy remain application requirements; do not enable termination without confirming that the client protocol expects it.

Choose a scaling design

There are two separate scaling mechanisms: Nginx can distribute connections across explicitly listed backend ports, or PM2 can create multiple Node.js workers that share the listening port through cluster mode.

Design Configuration Best fit Important limitation
Single Node process One PM2 fork on 127.0.0.1:4001 Simplest deployment and protocols with centralized state One process handles all application connections
Nginx stream upstream Separate Node listeners, such as 4001 and 4002 Explicit backend selection, independent process ports or mixed implementations You must manage each listener and decide how connection distribution affects state
PM2 cluster mode pm2 start server.js --name tcp-server -i max Multiple workers accepting TCP connections through PM2’s cluster load balancing Workers must tolerate distributed connections and shared resources

Distribute with Nginx stream upstreams

stream {
    upstream tcp_backends {
        least_conn;
        server 127.0.0.1:4001;
        server 127.0.0.1:4002;
    }

    server {
        listen 0.0.0.0:4000;
        proxy_pass tcp_backends;
        proxy_timeout 1h;
    }
}

The stream upstream defines a backend group that the server’s proxy_pass references. Add health, backup or selection behavior only after deciding what a reconnect means for your protocol. A connection moved to another backend is not the same as preserving its in-memory session.

Use PM2 cluster mode

pm2 start server.js --name tcp-server -i max

Before using cluster mode, verify that the server is safe with multiple workers. In-memory connection state is local to one worker, ordering assumptions can break when related connections land on different workers, and shared files or databases need concurrency controls. If the protocol requires a particular client to stay with one worker, design sticky routing or move session state to an external store; PM2’s TCP-capable balancing does not automatically solve application-level state.

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

Test the complete path

  1. Check that PM2 reports the expected process: pm2 status.
  2. Check Node’s private listener: sudo ss -ltnp | grep ':4001'.
  3. Check Nginx’s public listener: sudo ss -ltnp | grep ':4000'.
  4. From an allowed client network, connect to the VPS on port 4000 using a TCP test client and send a protocol-valid message.
  5. Watch pm2 logs tcp-server and Nginx’s error log while connecting.
  6. Reboot during a maintenance window, then repeat the PM2, Nginx and connection checks.

A local connection to 4001 proves only that Node is running. A remote connection to 4000 proves the firewall, Nginx stream listener and upstream path as well.

Troubleshoot common failures

PM2 says the process is stopped or restarting

  • Run pm2 logs tcp-server and execute node server.js directly to expose syntax, module-format or environment errors.
  • Confirm the ecosystem file’s cwd, script path and PORT value.
  • Check that another process is not already using the private port.
  • After correcting the cause, restart the process and run pm2 save if the desired process list changed.

Nginx fails its configuration test

  • Run sudo nginx -t and fix the reported line before reloading.
  • Ensure stream {} is at the top level, not nested inside http {}.
  • Confirm the installed build has stream support and that the module is loaded when your distribution packages it separately.
  • Check for duplicate listen directives or a service already occupying port 4000.

Clients connect but then disconnect

  • Compare the client’s idle period with proxy_timeout; increase it only when the protocol genuinely needs longer idle sessions.
  • Look for application-level timeouts, socket errors and framing mistakes in PM2 logs.
  • Verify that TLS expectations match: a TLS client cannot speak to a plain-text endpoint unless TLS is terminated or passed through correctly.

The service works locally but not from the Internet

  • Confirm that Nginx is listening on the public address and port, not only on loopback.
  • Open the public port in both the VPS firewall and any provider security group.
  • Keep Node on the private port and ensure Nginx’s proxy_pass points to the same port that PM2 supplies through PORT.

Operational checklist

  • Node binds to an intentional private address and port.
  • PM2 has a stable process name and an ecosystem configuration where repeatability matters.
  • pm2 startup was completed with the exact generated command.
  • pm2 save was run after the final process list was started.
  • Nginx uses stream {}, not an HTTP reverse-proxy block.
  • Public and private ports are different and documented.
  • proxy_connect_timeout and proxy_timeout reflect the protocol’s actual behavior.
  • Only the Nginx port is exposed publicly.
  • Logs and reboot recovery have been checked before production traffic is accepted.

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.

NGINXNode.jsPM2server administrationTCP serverVPS

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.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.