When we start a service, we often get the error address already in use. This error indicates that the port in use is occupied by a process. As a result, the service cannot be started. Generally, a port is occupied for two reasons:

  1. This port is also used by a started service
  2. The current service did not exit properly after the last startup

This article will take you through the problem.

Check the port usage

First, you need to determine which process is currently occupying the port you want to use.

  • macOS

    Open the terminal and enter lsof -I :port to change port to the port number, for example, 8080

    $ lsof -i :8080
    COMMAND  PID      USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
    main    6667 zhangpeng    7u  IPv6 0x645a94383c79337f      0t0  TCP *:http-alt (LISTEN)
    Copy the code
  • Linux

    Input netstat tunlp | egrep PID | “port”, to replace the port with the port number, such as: 8080

    $ netstat -tunlp | egrep "PID|8080"Proto Recv -q Send -q Local Address Foreign Address State PID/Program name TCP 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 131/nginx: master pCopy the code
  • Windows

    1. Start command window

      Press the Windows and R keys at the same time, enter CMD in the input box, and press Enter

    2. In the command window type netstat ano | findstr searches “PID port, the port to port, such as: 8080

      $ netstat -ano | findstr "PID 8080"Protocol Local ADDRESS External address PID TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 16248 TCP [::]:8080 [::]:0 LISTENING 16248 TCP [::1]:8080 [::1]:51273 ESTABLISHED 16248Copy the code

Once you find the process that occupies the port, you need to determine whether the process can be terminated. If no, use another port to start the service. If so, read on.

Terminates the process that occupies the port

From above, the process that occupies the port has been found. Next, we’re going to terminate it.

  • macOS

    Run the kill -9 PID command to kill the process that occupies the port and replace its PID with that of the process to be terminated

    kill -9 6667
    Copy the code
  • Linux

    Run the kill -9 PID command to kill the process that occupies the port and replace its PID with that of the process to be terminated

    kill -9 131
    Copy the code
  • Windows

    Run the taskkill /PID processid /t /f command to terminate the process that occupies the port and change processid to the PID of the process to be terminated

    taskkill /PID 16248 /t /f
    Copy the code

At this point, the processes that occupied our port have been terminated and we can happily start the service.

Title: How to solve the port occupation problem

Date: 2021.07.22

Author: zhangpeng

Making: github.com/gh-zhangpen…