Explain Codes LogoExplain Codes Logo

Node.js Port 3000 already in use, but it isn't?

javascript
port-management
process-termination
nodemon
Alex KataevbyAlex Kataev·Sep 29, 2024
TLDR

For a quick fix of the EADDRINUSE error indicating that port 3000 is already in use, use lsof -i :3000 to identify the rogue processes. Terminate these processes with kill -9 \lsof -t -i:3000` ` in your terminal. Alternatively, run your Node.js application on a different port, such as 3001 by changing it in your application's code.

Commands:

  • Detect process: lsof -i :3000
  • Force kill: kill -9 $(lsof -t -i:3000)
  • Switch port in app:
    // Guess we're the new neighbors at 3001! const port = 3001; app.listen(port); // Listening on port 3001

In-depth troubleshooting

  • Check Your Configuration : Ensure your app.js is configured to use the right port. If any background services like Nodemon are running, they could be quietly squatting on your port.
  • Restart Woes : Rebooting may not always release the port. Yes, Windows turns into a nagging landlord sometimes.
  • Knowing Your Toolset : kill -9 is your go-to on Linux or Mac. On Windows, the equivalent is taskkill /F /PID PID.
  • Simplify with npx kill-port : If shuffling between lsof and netstat feels burdensome, switch to npx kill-port <port>, your magic wand to zap processes off any port.
  • Prevention is Better than Cure : Implement a port checking mechanism in your app's startup script to ward off the EADDRINUSE specter.

Deep look into Port Liberation

  • Visual Process Management with TCPView : On Windows, netstat -ano | findstr :3000 or TCPView can help find the PID to kill.
  • Superuser Power : Linux or Mac users can flex their authority by prefixing sudo to commands and get things done.
  • Verify Process Termination : Once a process is killed, a good habit is to ensure with ps aux or Windows Task Manager that no trace of it remains.
  • Shell Environment Awareness : While navigating Git Bash on Windows, remember tskill and taskkill work differently.
  • Be Cautious of Tooling Issues : Tools like Nodemon could have minor quirks leading to occupying port 3000 inadvertendly, so watch out for those.