Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js EADDRINUSE: address already in use on port 3000

Another socket owns the port: a stopped container, a watcher race or the IPv6 wildcard. Find the holder, then free it or bind elsewhere.

~5 min readNode.js
#Node.js#Networking#Ports#Troubleshooting
A Node network socket plug rejected at a cyan port gate, an amber process card and a container box beside it

Introduction & Quick Summary

text
Error: listen EADDRINUSE: address already in use :::3000 at Server.setupListenHandle [as _listen2] (node:net:1904:16) at listenInCluster (node:net:1961:12) at Server.listen (node:net:2063:7)

Another socket already owns the port, or your process is trying to bind a second time. The :: form in the message is not decoration: it means Node bound the IPv6 wildcard, which on Linux usually also accepts IPv4, so a supposedly free IPv4 port can still be taken.

Work through the four possibilities in order:

  • A live process. An earlier node, nodemon, ts-node-dev, next dev or PM2 worker survived the terminal closing.
  • A container. Docker publishes the port on the host; docker ps will show it even when lsof shows docker-proxy.
  • A double start. A watcher restarted before the old process released the socket, or cluster.fork() created workers that all call listen incorrectly.
  • A dual-stack collision. One process holds [::]:3000, another tries 0.0.0.0:3000.
Error codeMeaningTypical fix
EADDRINUSEPort already boundFree the port or bind elsewhere
EACCESPrivileged port without rightsUse port above 1024 or grant capability
EADDRNOTAVAILAddress not on this hostBind 0.0.0.0 or the right interface
ERR_SERVER_ALREADY_LISTENlisten() called twiceGuard the call
ENOTFOUNDHost name does not resolveFix host argument

Core Mechanics, Signatures & Reproducible Setup

server.listen(port, host) asks the kernel for an exclusive binding to the address. TCP allows one listening socket per address and port; the kernel returns EADDRINUSE on the second request. SO_REUSEADDR, which Node sets by default on Unix, lets a socket bind over a TIME_WAIT remnant but not over an active listener. Windows behaves differently: it allows two binds in some cases, and the failure appears later as refused or misrouted connections.

Reproduce on a free port:

js
// server.js const http = require("node:http"); const server = http.createServer((req, res) => res.end("ok")); server.on("error", (err) => { if (err.code === "EADDRINUSE") { console.error(`Port ${PORT} is busy`); process.exit(1); } throw err; }); const PORT = Number(process.env.PORT ?? 3000); server.listen(PORT, () => console.log("listening on", server.address()));

Run it twice and the second process exits with the handled message instead of an unhandled exception. Without the error handler, the error is emitted on the server object; an unhandled error event terminates the process with a stack trace that does not tell you how to fix it.

Find the owner of the port:

bash
# Linux ss -ltnp 'sport = :3000' lsof -nP -iTCP:3000 -sTCP:LISTEN # macOS lsof -nP -iTCP:3000 -sTCP:LISTEN # Windows (PowerShell) Get-NetTCPConnection -LocalPort 3000 -State Listen | Select-Object OwningProcess, LocalAddress

ss -ltnp shows both addresses; a [::]:3000 entry and a 0.0.0.0:3000 entry are two different sockets, and either one blocks a new wildcard bind.

For code that must run in parallel (tests, workers), request an ephemeral port and read it back:

js
const server = http.createServer(app); server.listen(0, "127.0.0.1", () => { const { port } = server.address(); console.log(`http://127.0.0.1:${port}`); });

Key Comparison Table

Binding formAccepts IPv4Accepts IPv6Blocks what
listen(3000)Usually yesYesBoth wildcards
listen(3000, "0.0.0.0")YesNoIPv4 wildcard
listen(3000, "::")Usually yesYesBoth on Linux
listen(3000, "127.0.0.1")Loopback onlyNoIPv4 loopback
listen(3000, "::1")NoLoopback onlyIPv6 loopback
listen(0)YesYesNothing, kernel chooses
SituationReliable detectionFix
Orphan dev serverss -ltnp, lsofkill <pid>
Watcher restart raceLogs show rapid restartsGraceful shutdown, then restart
Docker publishdocker ps --formatStop container or change -p
PM2 fork modepm2 list shows duplicatesexec_mode: "cluster"
Test suite parallelFails only in CIEphemeral port per test
Two apps in a monorepoBoth default to 3000Configure distinct ports

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: The dev server you thought you closed

bash
ss -ltnp 'sport = :3000' # LISTEN 0 511 *:3000 *:* users:(("node",pid=48213,fd=21)) kill 48213

If the process ignores SIGTERM, it is either blocked in a native addon or trapping the signal without exiting. Send SIGKILL only after checking that it is yours; a heavy-handed kill of a database or proxy leaves state behind.

bash
kill -TERM 48213 && sleep 1 kill -0 48213 2>/dev/null && kill -KILL 48213

Case 2: Watchers that restart before the socket is free

nodemon and ts-node-dev send a signal and spawn a new process quickly. If the old process holds open connections, the new one can hit EADDRINUSE before the old one exits. Make shutdown deterministic:

js
const server = http.createServer(app); function shutdown(signal) { console.log(`received ${signal}, closing`); server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 5000).unref(); } process.on("SIGTERM", () => shutdown("SIGTERM")); process.on("SIGINT", () => shutdown("SIGINT"));

server.close() stops accepting new connections and calls back once existing ones finish; the timer forces exit when a keep-alive client refuses to disconnect. Pair this with watcher settings that wait for exit:

{ "watch": ["src"], "signal": "SIGTERM", "delay": 500 }

Case 3: Cluster and PM2 workers

In Node's cluster module, the primary process owns the port and distributes connections; workers must not call listen on the same port with their own socket in a way that conflicts. The supported pattern is to let the primary listen and workers call listen(0) or simply let the primary route:

js
import cluster from "node:cluster"; import http from "node:http"; import { availableParallelism } from "node:os"; if (cluster.isPrimary) { for (let i = 0; i < availableParallelism(); i += 1) cluster.fork(); } else { http.createServer((req, res) => res.end(`worker ${process.pid}`)).listen(3000); }

Workers calling listen(3000) is correct here because the primary intercepts the call and shares the handle. With PM2, exec_mode: "cluster" does the same; exec_mode: "fork" with instances > 1 does not, and every extra instance fails with EADDRINUSE.

js
// ecosystem.config.cjs module.exports = { apps: [{ name: "api", script: "dist/server.js", exec_mode: "cluster", instances: "max" }], };

Case 4: Docker publishes the port on the host

bash
docker ps --format 'table {{.Names}}\t{{.Ports}}' # api-1 0.0.0.0:3000->3000/tcp

Stopping the container releases it. If lsof shows docker-proxy and docker ps shows nothing, a stopped container's proxy may still be shutting down; docker compose down clears the network and the proxy together. Also check for a second mapping on IPv6, which docker ps prints as [::]:3000->3000/tcp.

Case 5: Tests that bind a fixed port

js
// fragile: parallel test files collide beforeAll(() => new Promise((r) => server.listen(3000, r))); // robust: let the kernel assign a port let baseUrl; beforeAll(async () => { await new Promise((r) => server.listen(0, "127.0.0.1", r)); baseUrl = `http://127.0.0.1:${server.address().port}`; });

Supertest avoids the issue entirely by binding an ephemeral port per request:

js
import request from "supertest"; await request(app).get("/health").expect(200);

Case 6: A port picked at startup from an env var

js
const PORT = Number.parseInt(process.env.PORT ?? "3000", 10); if (!Number.isInteger(PORT) || PORT < 1 || PORT > 65535) { throw new Error(`Invalid PORT: ${process.env.PORT}`); }

Number("3000 ") is 3000, but Number("3000\n") is also 3000 while Number("3000abc") is NaN, and passing NaN to listen makes Node pick an ephemeral port silently, which then breaks health checks and container routing. Validate the value and log the resolved address.

Common Compilation/Runtime Mistakes & Version Gotchas

  • listen() without a callback hides the address. Always log server.address(); a NaN or undefined port means the kernel chose one, and the process is not where you think it is.
  • SO_REUSEADDR is not permission to double-bind. It handles TIME_WAIT on restart, not two live listeners. Expecting it to fix a running duplicate wastes time.
  • Windows allows overlapping binds. On Windows, a second bind to a specific interface can succeed while the wildcard is taken; the symptom becomes intermittent connection resets rather than EADDRINUSE. Test on the target platform.
  • IPv6-only containers. Some minimal base images disable IPv4-mapped addresses (net.ipv6.bindv6only=1), so listen(3000) accepts only IPv6 and a client on 127.0.0.1 gets ECONNREFUSED instead of the bind error. Bind both explicitly.
  • Node 18 versus 20+ error text. The stack frame names changed (_listen2, listenInCluster) but the code did not; searching the frame name instead of the code leads to unrelated issues.
  • reusePort is platform- and version-gated. The reusePort listen option distributes connections across processes on Linux and is not available everywhere; using it as a universal fix produces ERR_INVALID_ARG_VALUE on unsupported platforms.

To probe a running service before restarting it, send a request with the syntax in the curl builder and read the response class with the status code reference. When debugging a proxy in front of the app, the CIDR calculator helps confirm which loopback or subnet the listener should accept.

Primary references: net.Server.listen documents address resolution and the exclusive flag, and the Node.js error codes list EADDRINUSE, EACCES and EADDRNOTAVAIL with their system meanings.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.