Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Change the Port of a Node.js App on a VPS

A practical guide to moving a Node.js listener on a VPS, with environment-based configuration, systemd and NGINX examples, firewall alignment, verification commands, and fixes for EADDRINUSE, refusals, timeouts, and 502 errors.
Length12 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Change the port where Node listens, restart the process supervisor that launches the app, and verify the new socket locally and from the internet. The safest default for a production VPS is to keep Node on a private address such as 127.0.0.1 and let a reverse proxy handle public HTTP or HTTPS traffic. For direct exposure, bind Node to a reachable interface and open the selected TCP port in both firewall layers.

In an Express entry point, make the port an environment value rather than a hard-coded constant:

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.
const port = Number(process.env.PORT || 3000);
app.listen(port, '127.0.0.1', () => {
  console.log(`Listening on ${port}`);
});

What a port change actually changes

A Node.js application accepts TCP connections only on the address and port supplied to its listening call. Changing a DNS record, editing a browser URL, or changing a link in your frontend does not move that listener. The running Node process must call listen with the new value, and every component between the client and the process must agree with it.

Node exposes this through server.listen([port[, host[, backlog]]][, callback]). The API starts a server listening for connections on a given port and host. If the port is omitted or set to 0, the operating system selects an unused port; that behavior is useful for temporary or test servers, not for a VPS service that clients must reach at a predictable address. If the host is omitted, Node uses the unspecified IPv6 address when available or the unspecified IPv4 address otherwise. See the Node.js net documentation for the complete API contract.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • 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.

Express does not create a separate listening mechanism. Its app.listen() method is identical to Node’s http.Server.listen() and accepts a port plus an optional host, as documented in the Express application API. Consequently, the port can be changed in the same place whether the application uses Express directly or a lower-level HTTP server.

Choose the public exposure model first

Before editing code, decide whether clients should connect to Node itself or to a reverse proxy. This determines the host binding, firewall rules, TLS termination, and the file that must be updated when the port changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Design Node binding Public listener Firewall approach Operational characteristics
Direct Node exposure A reachable VPS interface, such as the server’s public address or an all-interfaces binding chosen deliberately Node listens on the application port Allow that TCP port in the provider firewall or security group and the VPS operating-system firewall Node receives internet traffic directly; you must handle the public attack surface, protocol configuration, and availability yourself
Reverse proxy 127.0.0.1 or another private interface NGINX listens on the public HTTP/HTTPS ports and proxies to Node’s private port Expose the proxy’s public ports; keep the Node port private NGINX can provide TLS termination, hostname routing, centralized access logs, and a single public entry point

The official NGINX Node.js deployment guide describes this reverse-proxy and load-balancing pattern. A port change in that design has two separate parts: Node must listen on the new private port, and NGINX’s upstream target must be changed to the same host and port.

Make the application read its port from the environment

Find the startup file and search for app.listen(, server.listen(, PORT, NODE_PORT, or a framework-specific setting. Prefer process.env.PORT so one build can run in development, staging, and production without source edits. Node defines process.env as the process environment object; its values are supplied by the shell, service manager, container, or hosting panel that starts the process. The definition is documented in the Node.js process documentation.

Use a numeric conversion and an intentional fallback. Environment variables arrive as strings, while the listening API expects a port number or a value it can convert. A fallback preserves the old development behavior when no deployment value is supplied:

const http = require('http');
const express = require('express');

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

app.get('/health', (req, res) => {
  res.send('ok');
});

const server = http.createServer(app);
server.listen(port, host, () => {
  console.log(`Listening on ${host}:${port}`);
});

If your application already calls app.listen, you do not need to introduce http.createServer; the shorter Express form is sufficient:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const port = Number(process.env.PORT || 3000);
app.listen(port, '127.0.0.1', () => {
  console.log(`Listening on ${port}`);
});

Do not silently accept an invalid value. A malformed environment value can produce an immediate startup failure or an unintended port. In production, validate that the resulting number is within the TCP range you intend to use and fail with a clear log message if it is not.

Set the value for the way you launch Node

One-time shell launch

For a quick test or a manually launched process, put the assignment before the command:

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
PORT=8080 node server.js

The assignment applies to that process and its children. It disappears when the shell command ends, so it is not a durable deployment setting. To confirm what the process receives before starting it, print the variable in the same shell or have the application log the selected port at startup.

systemd service

For a VPS service managed by systemd, put the port in the unit or in an environment file referenced by the unit. A complete example looks like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[Unit]
Description=Node application
After=network.target

[Service]
Type=simple
User=nodeapp
WorkingDirectory=/srv/myapp
Environment=NODE_ENV=production
Environment=PORT=8080
ExecStart=/usr/bin/node /srv/myapp/server.js
Restart=always

[Install]
WantedBy=multi-user.target

Adjust the user, working directory, Node binary path, and entry point to your installation. Express’s production guidance recommends an init system and shows systemd units using ExecStart, WorkingDirectory, Environment, and Restart=always; it identifies systemd as the main init system in use today. The guidance is available at Express production best practices.

If you keep values outside the unit, use an environment file and reference it with a line such as EnvironmentFile=/etc/myapp/myapp.env. Ensure the service account can read that file and that each assignment uses the syntax systemd expects. Editing a project-level .env file has no effect on an already running process unless the application loads that file and the supervisor recreates the process.

After changing a unit or its referenced environment file, apply and restart it:

sudo systemctl daemon-reload
sudo systemctl restart myapp.service
sudo systemctl status myapp.service
sudo journalctl -u myapp.service -e

daemon-reload is needed after editing the unit itself. A restart is still required after changing the environment file so systemd starts a new process with the new value. The status and journal commands reveal syntax errors, a wrong working directory, a missing Node binary, or an immediate crash.

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

Process managers, containers, and hosting panels

Other supervisors follow the same rule: set PORT in the supervisor’s environment, then restart or recreate the workload. For a container, change the container environment or compose/service definition and recreate the container rather than relying on a shell variable from the host. For a control panel, change the application’s runtime environment and use its restart or redeploy action. The important distinction is between changing configuration for the next process and changing the environment of a process that is already running.

Bind Node to the right host

The host argument controls which network interfaces accept connections. Use 127.0.0.1 when NGINX on the same VPS is the public entry point. That prevents ordinary external clients from reaching Node’s private port directly while still allowing the proxy to connect locally.

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)

For direct public access, bind to the interface required by your VPS design and confirm that the address is actually reachable. An application bound only to loopback will answer a local curl request but reject connections arriving through the server’s public address. Conversely, binding to every interface increases exposure and should be paired with deliberate firewall rules and application hardening.

Do not infer the bind address from the port number. Port 8080 on 127.0.0.1 and port 8080 on a public interface are different network endpoints even though the numeric port is identical.

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

Update NGINX when it is the public endpoint

Suppose Node moves from 3000 to 8080 and remains on loopback. The NGINX server block must point to 127.0.0.1:8080:

upstream node_app {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://node_app;
        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;
    }
}

Replace the hostname and preserve any existing TLS, WebSocket, upload, or timeout directives required by your application. Check the configuration before reloading:

sudo nginx -t
sudo systemctl reload nginx

Reloading NGINX does not restart Node. Restart the Node supervisor separately, then inspect both services if requests return an error. A 502 or 504 commonly means the proxy’s upstream still names the old port, the new Node process is not running, or the host in proxy_pass does not match Node’s bind address.

Align provider and operating-system firewalls

A VPS commonly has at least two independent network-policy layers: the cloud provider’s firewall or security group and the guest operating system’s firewall. Opening one does not automatically open the other.

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

Direct exposure

If clients connect straight to Node, allow the selected TCP port in both layers. For a system using UFW, an example rule is:

sudo ufw allow 8080/tcp
sudo ufw status verbose

Use the port you actually selected, restrict source addresses where your provider supports it, and retain access for SSH before changing firewall policy. The provider rule must allow the same destination port and protocol; a UFW rule cannot override a blocked security-group rule.

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

Reverse-proxy exposure

If NGINX is public, expose only the proxy’s public HTTP and HTTPS ports according to your deployment and keep the Node port bound privately. Do not open 8080 merely because NGINX proxies to it. This reduces the number of public listeners and ensures requests pass through the proxy’s routing, TLS, and logging layer.

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.

Firewall changes are not a substitute for a listening process. A permitted port with no socket produces a refusal, while a listening process behind a blocked provider rule appears to time out from the internet.

Restart the supervisor that owns the process

Identify how the application was started before issuing a restart. Restarting an unrelated shell, an old terminal session, or NGINX alone will leave the original Node process on its old port. Typical ownership patterns are:

  • systemd: restart the named unit with sudo systemctl restart unit-name.
  • Container runtime: recreate or restart the container after changing its environment or service definition.
  • Process manager: use that manager’s restart or reload operation so it creates workers with the new environment.
  • Hosting control panel: use the panel’s restart, redeploy, or application-reload action.
  • Interactive shell: stop the old process and launch a new command with the updated assignment.

A graceful reload may preserve workers that still carry the old environment, depending on the supervisor. When in doubt, perform a full restart or recreation and verify the resulting process rather than trusting the command’s exit status.

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

Verify the new listener from the VPS outward

Verification should proceed in layers so each failure points to a narrower cause.

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.
  1. Read the startup log. Confirm that the application reports the intended host and port, such as Listening on 127.0.0.1:8080. If the message still says 3000, the new environment did not reach the process or another entry point is running.
  2. Inspect listening sockets. On Linux, use the socket utility to identify the owning process:
sudo ss -ltnp | grep -E ':3000|:8080'

A healthy result should show the new port and the expected Node PID. If both old and new ports appear, more than one process is running; determine which supervisor owns each one before stopping anything.

  1. Test locally against the bind address. For a loopback service, request it directly:
curl -i http://127.0.0.1:8080/

Use an application health route if one exists. This test proves that Node accepts local connections, but it says nothing about the provider firewall or public routing.

  1. Test the proxy locally. If NGINX is involved, request the public virtual host through its local listener or use the hostname with the appropriate scheme. A successful Node test combined with a failed proxy test points to NGINX configuration, reload state, headers, or TLS rather than the Node listener.
  2. Test from an external network. Request the public hostname or IP with the correct scheme and port. A direct service might be tested as http://203.0.113.10:8080/; a proxy normally uses the public HTTP or HTTPS URL without the private Node port. An external result validates the path through routing and firewall policy, not just the application.

Record the final host, port, supervisor, and proxy target in the deployment notes. This prevents a later administrator from changing only one of the several values that form the connection path.

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.

Troubleshoot the common failure modes

EADDRINUSE during startup

EADDRINUSE means another server already owns the requested port or path. Node documents it as the common error when a second listener attempts to use an occupied endpoint. Find the owner first:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ss -ltnp | grep ':8080'

Then decide whether the existing process is the old application, a different service, or a duplicate worker. Stop or reconfigure the owner through its supervisor; do not kill an unknown process merely to make the error disappear. If the port is intentionally occupied, choose another free port and update every dependent configuration.

Connection refused

A refusal usually means the destination is reachable but no process is accepting connections there. Check the supervisor status and application log, then compare the requested host and port with the socket listing. Common causes are a restart that failed, a crash caused by an invalid environment value, a bind to loopback while testing the public address, or a proxy still targeting a port that is no longer used.

Internet requests time out

A timeout often indicates filtering or routing rather than an application-level response. Verify the provider firewall or security group, the guest firewall, the VPS route, and the bind address. A local curl success does not demonstrate that packets arriving on the public interface are permitted. For a reverse proxy, test the public proxy port instead of the private Node port.

NGINX returns 502 or 504

Check that the upstream target exactly matches Node’s current host and port, including whether Node uses 127.0.0.1 or an IPv6 address. Run sudo nginx -t, reload NGINX after correcting the configuration, and inspect the NGINX error log alongside the Node service log. A 502 generally means NGINX cannot establish the upstream connection; a 504 can additionally indicate an upstream response or timeout problem after the connection is established.

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

The shell works but systemd does not

Interactive shells and systemd can differ in user, working directory, PATH, Node binary location, and environment. Put the port in the unit’s Environment= line or its referenced environment file, use an absolute ExecStart path, and set WorkingDirectory explicitly. Restart the unit and read journalctl; do not assume that a command that succeeds as your login user will succeed under the service account.

The app still reports port 3000

Confirm which file is executing and whether a second copy of the application is running. Search all startup and configuration files for another listen call or a framework-specific port setting. Check the supervisor’s effective environment, restart the correct unit or container, and inspect the process list and socket owner. Editing a dormant source tree or an unused environment file cannot alter the process that is serving traffic.

A repeatable change procedure

  1. Identify the actual entry point and supervisor, then locate every listener and port setting.
  2. Choose direct exposure or a private Node listener behind NGINX.
  3. Change the code to read process.env.PORT and select a documented numeric port.
  4. Set that value in the shell, systemd unit or environment file, container definition, process manager, or hosting panel that launches the app.
  5. If using NGINX, change its upstream host and port and validate the configuration.
  6. Apply firewall changes only to the public endpoint required by the chosen design.
  7. Restart or recreate the supervisor that owns Node, then reload NGINX if its configuration changed.
  8. Verify logs, listening sockets, a local request, the proxy path, and finally an external request.

The change is complete only when the running process, bind address, proxy target, and relevant firewall rules all describe the same network path. No performance improvement or degradation should be assumed merely from selecting a different listening port; the primary effect is where traffic is accepted and how it is routed.

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.

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

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
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.