How to Fix Node.js Port Already in Use
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
.envfile to configure the port number. - Use
process.env.PORTwith a fallback. - Add a pre-start script that kills existing processes.
- Use
nodemonwith the--delayflag to allow port release. - In Docker, ensure containers are stopped before restarting.
Common Mistakes with port in use
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro