Skip to content

How to Fix Node.js Port Already in Use

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Node.js Port Already in Use. We cover key concepts, practical examples, and best practices.

The Problem

Node.js throws Error: listen EADDRINUSE: address already in use :::3000 when starting a server on a port that is already occupied by another process.

Quick Fix

Step 1: Find and kill the process using the port

On Linux/Mac:

lsof -i :3000
COMMAND   PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node     12345 user   12u  IPv6 0x1234567      0t0  TCP *:3000 (LISTEN)

Kill the process:

kill -9 12345

On Windows:

netstat -ano | findstr :3000
taskkill /PID 12345 /F

Step 2: Use a different port

Modify your application to use a different port:

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Step 3: Enable SO_REUSEADDR

For development, allow immediate port reuse:

const server = app.listen(0); // Use port 0 for auto-assignment
server.on('listening', () => {
    console.log(`Server running on port ${server.address().port}`);
});

Step 4: Handle the error gracefully in code

Catch the EADDRINUSE error and try alternative ports:

function startServer(port = 3000) {
    const server = app.listen(port);
    server.on('error', (err) => {
        if (err.code === 'EADDRINUSE') {
            console.log(`Port ${port} in use, trying ${port + 1}`);
            startServer(port + 1);
        } else {
            console.error('Server error:', err);
        }
    });
    server.on('listening', () => {
        console.log(`Server running on port ${port}`);
    });
}
startServer();

Step 5: Check for zombie processes

Sometimes Node processes are not killed properly:

ps aux | grep node
kill $(pgrep node)

Prevention

  • Use a .env file to configure the port number.
  • Use process.env.PORT with a fallback.
  • Add a pre-start script that kills existing processes.
  • Use nodemon with the --delay flag to allow port release.
  • In Docker, ensure containers are stopped before restarting.

Common Mistakes with port in use

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world NODE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does the port stay in use after my app crashes?

The OS keeps the port in TIME_WAIT state for a short period to ensure any in-flight packets are delivered. This typically lasts 1-2 minutes. SO_REUSEADDR allows a new process to bind to the port even while it is in TIME_WAIT.

How do I set SO_REUSEADDR in Node.js?

const server = app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});
server.on('connection', (socket) => {
    socket.setNoDelay(true);
});

By default, Node.js sets SO_REUSEADDR on the server socket. If you still get EADDRINUSE, the port is genuinely in use and you need to kill the process.

Can I check if a port is available before listening?

const net = require('net');
function isPortAvailable(port) {
    return new Promise((resolve) => {
        const server = net.createServer();
        server.once('error', () => resolve(false));
        server.once('listening', () => {
            server.close();
            resolve(true);
        });
        server.listen(port);
    });
}

This checks availability without binding permanently.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro