Node.js Tutorial

71 lessons

0 / 71 completed0%
Beginner Basics
Intermediate Topics
Advanced Concepts
Lesson 1 of 71
Step 1 of 714 min

Error: listen EADDRINUSE - Port Already in Use in Node.js

When you start your Node.js server and see this error, another process is already using that port.

Error Message:

Example
Error: listen EADDRINUSE: address already in use :::3000

Quick Solution

Mac/Linux

Find the process:

Example
lsof -i :3000

Output shows:

Example
node    12345 user   23u  IPv6 ... TCP *:3000 (LISTEN)

Kill it:

Example
kill -9 12345

One-liner:

Example
kill -9 $(lsof -t -i:3000)

Windows

Find the process:

Example
netstat -ano | findstr :3000

Kill it:

Example
taskkill /PID 12345 /F

Better Solution: Auto Port Selection

Instead of hardcoding port 3000, try the next available port:

Example
const http = require('http');

function startServer(port) {
  const server = http.createServer(app);
  
  server.listen(port)
    .on('listening', () => {
      console.log(`Server on port ${port}`);
    })
    .on('error', (err) => {
      if (err.code === 'EADDRINUSE') {
        console.log(`Port ${port} busy, trying ${port + 1}`);
        startServer(port + 1);
      }
    });
}

startServer(3000);

Environment Variables

Use flexible port configuration:

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

Run with custom port:

Example
PORT=3001 node server.js

Common Causes

Cause Solution
Previous server still running Kill the process
Multiple server instances Check running processes
Docker container active Stop container
nodemon didn't clean up Restart nodemon

Proper Server Cleanup

Add signal handlers to close server properly:

Example
const server = app.listen(3000);

process.on('SIGINT', () => {
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});

process.on('SIGTERM', () => {
  server.close(() => {
    process.exit(0);
  });
});

Now Ctrl+C properly shuts down the server.

NPM Script Helper

Add to package.json:

Example
{
  "scripts": {
    "kill-port": "kill -9 $(lsof -t -i:3000) 2>/dev/null || true",
    "start": "npm run kill-port && node server.js"
  }
}

Docker Issues

If using Docker and port is still busy:

Example
docker ps                    # List containers
docker stop <container-id>   # Stop specific container
docker rm <container-id>     # Remove container

Prevention Tips

  1. Always handle SIGINT and SIGTERM signals
  2. Use environment variables for ports
  3. Implement auto port selection for development
  4. Clean up Docker containers regularly
  5. Use process managers like PM2 in production

This error usually means a previous instance didn't shut down cleanly. The solutions above handle both the immediate fix and prevention.