Learning objectives
After reading this article you will be able to:
- Find which process holds a port on Linux, macOS and Windows
- Understand the difference between 127.0.0.1, localhost and 0.0.0.0
- Write a Node.js and a Python server that read the port from PORT
On this page
- What does EADDRINUSE look like?
- How do you find what is using the port?
- Why do you get a 502 after the deploy if the app started?
- What is the difference between 127.0.0.1, localhost and 0.0.0.0?
- How do you listen on the right port in Node.js and Python?
- How do you keep it from coming back?
- How to do this on Square Cloud
- FAQs
Two port errors show up at opposite moments. On your machine, the app will not even start: EADDRINUSE, because the port already has an owner. In production, it starts without a single error, the log says "listening on port 3000", and the browser still gets a 502 Bad Gateway.
Both share one root. An address and a TCP port accept a single listening process, and whoever connects has to hit exactly that address and port. Once that is clear, both fixes are short.
What does EADDRINUSE look like?#
In Node.js, the first line of the error is this one, followed by the stack trace and an object with the details:
Error: listen EADDRINUSE: address already in use :::3000
code: 'EADDRINUSE',
errno: -98,
syscall: 'listen',
address: '::',
port: 3000The :::3000 is the address :: followed by the port. When you pass no host to listen, Node.js listens on the unspecified IPv6 address (::), or on 0.0.0.0 when IPv6 is not available. The Node.js docs define the error as an attempt to bind a server to a local address that another server on the same system already occupies.
In Python, the same error comes from the operating system:
OSError: [Errno 98] Address already in useThe number depends on the system: 98 on Linux, 48 on macOS. On Windows the code is 10048 (WSAEADDRINUSE). Async servers such as uvicorn show the same exception with the text error while attempting to bind on address, followed by the address and port.
How do you find what is using the port?#
Find the process first, then decide whether it should die. Replace 3000 with your port.
On Linux:
sudo ss -ltnp 'sport = :3000'
# or
sudo lsof -nP -iTCP:3000 -sTCP:LISTENOn macOS:
lsof -nP -iTCP:3000 -sTCP:LISTEN
kill <PID> # asks the process to exit (SIGTERM)
kill -9 <PID> # only if it ignores the requestOn Windows, from PowerShell or Command Prompt:
Get-NetTCPConnection -LocalPort 3000 -State Listen | Select-Object LocalAddress, LocalPort, OwningProcess
Stop-Process -Id <PID>
# Command Prompt
netstat -ano | findstr :3000
taskkill /PID <PID> /FIn ss, -l shows only listening sockets, -t limits output to TCP, -n prints numbers instead of names and -p shows the process (without sudo, you only see your own). In netstat, -o adds the PID of each connection.
The PID points to the cause. The usual ones, from most to least frequent:
- A previous instance still running. Another terminal, a process left in the background, an editor terminal closed without stopping the server.
- Two
listencalls in the same code. The classic one: callingapp.listen(3000)and, further down, creating anhttp.createServer(app)for Socket.IO and callingserver.listen(3000)again. - Another program on the same port. A second project, a container publishing the port, a system service. Pick another port for development, and leave production's alone.
- Tests that start the server on import. Every test file imports the app, and the second one finds the port taken.
One side effect: Vite's dev server, by default, tries the next free port when the configured one is busy. Your front end can move to another port silently, and a CORS origin list stops matching. With strictPort: true, it exits instead of switching.
Why do you get a 502 after the deploy if the app started?#
On hosting with a reverse proxy, public traffic hits the proxy first, and the proxy opens a connection to your app on an agreed address and port. If nothing listens there, the connection is refused (ECONNREFUSED, the same reason behind ERR_CONNECTION_REFUSED in the browser) and the proxy returns 502. Your app logs show no error at all, because the request never reached it.
The two classic causes:
- Listening on loopback only.
app.listen(3000, "localhost"), Flask'sapp.run()and uvicorn without--hostlisten on127.0.0.1. Inside a container, loopback belongs to the container, and the proxy, which sits outside it, cannot reach it. - A port hardcoded in the code. The app listens on 3000 or 8000, while the platform forwards traffic to the port it announces in the
PORTvariable.
A third cause looks the same from outside: the app crashed right after starting, or is still loading. In that case your logs show the startup error. The full picture of 5xx codes is in 500, 502, 503 and 504 errors, and the other gaps between your laptop and the server are in works locally but not in production.
What is the difference between 127.0.0.1, localhost and 0.0.0.0?#
127.0.0.1(and::1in IPv6) is loopback: a virtual interface that only accepts connections from the same machine, or the same container.localhostis a name that resolves to loopback. Depending on the system it may resolve to127.0.0.1or to::1, and a client trying one can miss a server listening only on the other.0.0.0.0is not a destination, it is a wildcard forlisten: "accept connections on every IPv4 interface".::does the same for IPv6 and, on most systems, also covers IPv4.
The right address depends on where the connecting side lives:
- Container or hosting platform: the proxy is outside the container, so listen on
0.0.0.0. - VPS with nginx on the same machine: nginx connects over loopback, so
127.0.0.1works and keeps the app's port off the public internet. If you use0.0.0.0on a VPS, close the port in the firewall. - Your machine: loopback is enough.
0.0.0.0makes the app reachable on your local network, handy for testing on a phone, but visible to everyone on the same Wi-Fi.
How do you listen on the right port in Node.js and Python?#
The convention on hosting platforms is to announce the port in the PORT environment variable. Your code reads that value and keeps a default for development only.
In Node.js with Express 5 (in Express 5, listen errors reach the callback; in Express 4 they are thrown):
import express from "express";
const app = express();
app.get("/", (req, res) => res.send("ok"));
// The platform sets the port; 3000 is only the local default
const port = Number(process.env.PORT) || 3000;
const server = app.listen(port, "0.0.0.0", (error) => {
if (error) {
if (error.code === "EADDRINUSE") {
console.error(`Port ${port} is in use: stop the other process or set PORT.`);
process.exit(1);
}
throw error;
}
console.log(`Listening on ${JSON.stringify(server.address())}`);
});
// Release the port on SIGTERM (restart, deploy) or Ctrl+C
for (const signal of ["SIGTERM", "SIGINT"]) {
process.on(signal, () => server.close(() => process.exit(0)));
}In Python with FastAPI and uvicorn:
# main.py
import os
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"status": "ok"}
if __name__ == "__main__":
# The platform sets the port; 8000 is only the local default
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))From the command line, the equivalent is uvicorn main:app --host 0.0.0.0 --port $PORT. uvicorn defaults to 127.0.0.1:8000, so --host is required behind an external proxy.
In Flask, app.run() defaults to 127.0.0.1:5000, and the docs warn it is not meant for production. For a quick test, app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000"))). In production, use a WSGI server on the same address, such as gunicorn --bind 0.0.0.0:$PORT app:app. The full walkthrough is in how to host FastAPI, Flask and Django.
How do you keep it from coming back?#
- Read
PORTand listen on0.0.0.0behind an external proxy, or on127.0.0.1on a VPS with the proxy on the same machine. - One
listenper process. With Socket.IO orws, create thehttp.Server, hand it to the library and calllistenonce. - Shut down on signals. Handle
SIGTERMandSIGINTby closing the server, so the port is released before the next instance starts. - Keep the app apart from
listen. Export the app from a module and calllistenonly in the entry file; tests import the app without opening a port. - Test like production. Run with
PORT=8080set and connect from another device on your network: if it does not answer, the listen address is wrong.
How to do this on Square Cloud#
On Square Cloud, a web application must listen on 0.0.0.0 on the port from the PORT variable, which the platform sets along with HOST. Only port 80 receives traffic, published over HTTPS on the *.squareweb.app subdomain (or on your own domain, from the Standard plan up), so a port hardcoded in the code, like 3000 or 8000, gets no traffic. The examples above read PORT, so they already follow this rule.
If your server reads its address from another variable, adjust it in the start command (START), which runs as a shell command. For servers that read HOSTNAME as their bind address, such as Next.js standalone, begin the START command with HOSTNAME=0.0.0.0 (for example, HOSTNAME=0.0.0.0 node server.js, with the path to your project's server.js). With uvicorn, a START like uvicorn main:app --host 0.0.0.0 --port $PORT does the same. Bots, which have no subdomain, receive no inbound traffic and do not need to open a port.
If an EADDRINUSE shows up in the real-time logs, look for two listen calls in the same code or two servers started by the same START. PM2 is neither needed nor recommended: with automatic restart on, an app that exits with an error comes back on its own. See how to publish your API on the API hosting page.
API hosting
APIs in always-on containers, with no cold starts
FAQs
How do I free a port that is in use?
Find the PID of the process listening on it (lsof or ss on Linux and macOS, netstat -ano or Get-NetTCPConnection on Windows) and stop that process. If it is an old instance of your app, close it from the terminal that started it.
What is the difference between 127.0.0.1 and 0.0.0.0?
127.0.0.1 is the loopback interface: it only accepts connections from the same machine or container. 0.0.0.0 listens on every IPv4 interface, so it accepts connections from outside, such as the hosting provider's proxy.
Why does my app work locally but return 502 after deploying?
Usually it listens on localhost or on a fixed port that differs from what the platform expects. The proxy tries to connect, gets connection refused and returns 502. Read the port from PORT and listen on 0.0.0.0.
Does switching to port 3001 fix EADDRINUSE?
It fixes the symptom on your machine but hides the cause, which is often an old instance still running. In production the port comes from the platform, so changing it in code tends to create a 502.
More in APIs
See all 36 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How much does it cost to host an API?Hosting a small API costs a few to a few dozen dollars a month. See what goes into the bill (compute, database, bandwidth, requests, logs) and how to estimate it.
- CORS error (blocked by CORS policy): cause and fixA CORS error means the API did not allow your page's origin. Learn the causes, how to fix it in Express and FastAPI, and how to test the preflight with curl.