Solving the "Error: EADDRINUSE" Issue in Node.js

Solving the "Error: EADDRINUSE" Issue in Node.js

The «Error: EADDRINUSE» error is a common issue that developers face when working with Node.js applications. This error occurs when a port is already in use by another process, and you're trying to start a new server on the same port. In this article, we'll discuss the possible reasons for this error and provide solutions to fix it.

1. Find the process using the port

First, you need to find the process that's currently using the port your Node.js application is attempting to use. You can do this using the following command:

For macOS and Linux:

  1. sudo lsof -i :<PORT>

For Windows:

  1. netstat -ano | findstr :<PORT>

Replace `<PORT>` with the port number you're trying to use. This command will display a list of processes using the specified port.

2. Terminate the conflicting process

Once you've identified the process using the port, you can either:

  • Terminate the conflicting process and free up the port. You can do this using the following command:

For macOS and Linux:

  1. sudo kill -9 <PID>

For Windows:

  1. taskkill /PID <PID> /F

Replace `<PID>` with the process ID of the conflicting process.

  • Modify your Node.js application to use a different port. You can do this by updating the port number in your server configuration:
  1. const port = process.env.PORT || 3001; // Use an alternative port number

3. Ensure proper server shutdown

Sometimes, the «Error: EADDRINUSE» issue can occur when the server is not shutting down properly. Make sure to close your server when exiting your application, by adding a process listener:

  1. process.on('SIGINT', () => {
  2. server.close(() => {
  3. console.log('Server closed');
  4. process.exit(0);
  5. });
  6. });

This code snippet listens for a SIGINT signal (generated when you press Ctrl+C to stop the application) and gracefully shuts down the server.

4. Use a dynamic port

If you're running multiple instances of your Node.js application, you can avoid the «Error: EADDRINUSE» issue by using a dynamic port instead of a fixed one. Simply set the port value to 0, and the operating system will assign an available port automatically:

  1. const port = process.env.PORT || 0;

By following these steps, you should be able to resolve the «Error: EADDRINUSE» issue in your Node.js application and continue development without any interruptions.

We use cookies to improve your browsing experience. By continuing to use this website, you consent to our use of cookies. Learn More