HttpPlatformHandler Returns Random Port but Node is Set to 3000: A Fix

Abstract: Fix connection failures by setting the PORT environment variable to 3000 in web.config so HttpPlatformHandler aligns with Node.js.

Created: 2026-08-22 by
HttpPlatformHandler returns a random port because it reads the port from the PORT environment variable, which IIS Express assigns dynamically. To fix this, you must explicitly set the PORT variable to 3000 in your web.config file. This overrides the default behavior and forces Node.js to listen on the expected address.

Understanding the HttpPlatformHandler Configuration

The HttpPlatformHandler is an IIS module that allows you to run non-.NET applications, such as Node.js, behind IIS. When you deploy a Node.js application to Azure Web Apps or configure it locally with IIS Express, the handler acts as a reverse proxy. It forwards incoming HTTP requests from the public-facing URL to your local Node.js process. A common point of confusion arises when developers hardcode the port in their Node.js startup script but still experience connection failures. The issue is not with the code itself, but with how the environment is configured. IIS does not know which port your application is listening on unless you tell it. If you do not specify a port, the platform assigns a random available port for security and isolation reasons. Your Node.js app might be stuck listening on port 3000, while IIS is trying to connect to port 8421, resulting in a broken pipe or connection refused error. To resolve this, you need to align the port expectation of the handler with the actual port your application uses. This involves editing the web.config file located in the root directory of your web application. This XML file controls how IIS processes requests for your site.

Modifying web.config to Set the Port

The most reliable way to fix the random port issue is to add an environment variable entry in the web.config file. This ensures that every time the Node.js process starts, it receives the correct port number via the standard process.env.PORT mechanism. Open your web.config file in a text editor. You will see sections defining the handlers and modules. Locate the <system.webServer> section. Inside this section, you need to add an <environmentVariables> block. Here is the structure you should use:
<system.webServer>
    <handlers>
        <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
    </handlers>
    <httpPlatform processPath="node" arguments=".\server.js" stdoutLogEnabled="true" stdoutLogFile=".\\logs\\stdout" port="3000" />
</system.webServer>
Notice the port="3000" attribute inside the <httpPlatform> element. This tells the handler that the backend process (Node.js) is listening on port 3000. However, simply setting this attribute is often not enough for all platforms, especially if the application relies heavily on the PORT environment variable for dynamic routing. Therefore, it is best practice to also define the environment variable explicitly. Add the following block inside <system.webServer>:
<environmentVariables>
    <environmentVariable name="PORT" value="3000" />
</environmentVariables>
This combination ensures that both the IIS module knows where to send traffic and the Node.js process knows which port to bind to. After making these changes, save the file and restart your IIS Express instance or publish the application again.

Verifying the Node.js Startup Code

Once the configuration is updated, you must ensure your Node.js code actually respects the PORT environment variable. Many starter templates hardcode the port like this:
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
While this works locally, it will fail in production environments managed by HttpPlatformHandler because the hardcoded value ignores the environment variable. You should modify your startup logic to check for the environment variable first, falling back to 3000 only if it is undefined. Update your server initialization code to look like this:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
This pattern is robust and works across development, testing, and production environments. It allows IIS to control the port via configuration while maintaining a sensible default for local development. If you are using frameworks like Express, Hapi, or Koa, this approach remains valid as they all support binding to a specific port passed as an argument.

Troubleshooting Common Issues

If you have applied the fixes above and still face issues, consider the following diagnostic steps. First, check the stdout log file specified in your web.config. This file captures the console output from your Node.js process. Look for any errors indicating that port 3000 is already in use. If another process is occupying the port, change the value in web.config to an unused port, such as 3001, and update your Node.js code accordingly. Second, verify that IIS Express is actually reloading the configuration. Sometimes, cached configurations can persist even after you edit web.config. Restarting the application pool or stopping and starting IIS Express usually clears this state. Third, ensure that your firewall settings are not blocking localhost connections on port 3000. While rare in local development, some security software may interfere with loopback addresses. For related issues regarding Node.js permissions, you might find Access Denied Error: Node.js Works, but npm Commands Fail helpful if you encounter permission-related errors during deployment.

Frequently Asked Questions

Why does IIS assign a random port instead of using my code's port?

IIS assigns a random port to prevent conflicts between multiple applications running on the same server. Without explicit configuration, the HttpPlatformHandler cannot guess which port your specific Node.js instance is listening on. You must explicitly define the port in web.config to bridge this gap.

Can I use a different port than 3000?

Yes, you can use any available TCP port. Simply change the port attribute in <httpPlatform> and the value in <environmentVariable> to your desired number. Ensure your Node.js code uses the process.env.PORT variable to remain flexible.

What if I get a "Port Already in Use" error?

This error means another process is already bound to port 3000. Check your task manager for other Node instances or services. Change the port number in your web.config to something else, like 3001, and update your environment variable accordingly.

Does this fix work for Azure App Service?

Yes, Azure App Service uses HttpPlatformHandler under the hood for Linux containers and certain Windows scenarios. The same web.config modifications apply. Azure also injects the PORT environment variable automatically, so ensuring your code reads it is crucial.

How do I enable logging to debug port issues?

Set stdoutLogEnabled="true" and specify a stdoutLogFile path in your httpPlatform handler definition. This creates a log file that records the output of your Node.js process, allowing you to see exactly which port the server claims to be listening on at startup.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More