When deploying a server, it’s not uncommon to encounter the “address already in use” error. This issue arises when a process doesn’t terminate correctly, or another process is unintentionally bound to the desired port. In this article, we’ll explore a step-by-step guide on how to address this issue and reclaim the port for your server.
While automating the deployment of a server using Python and SSH, the following error might be observed:
Failed to listen listen tcp :8112: bind: address already in use
exit status 1
This indicates that port 8112
is occupied by some process.
To rectify this issue, follow these steps:
Use the lsof
command to list the processes that are utilizing port 8112:
lsof -i :8112
The output should look something like:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
server 12345 ubuntu 3u IPv6 45678 0t0 TCP *:8112 (LISTEN)
From this output, the PID
indicates the process ID, which is 12345
in our example.
Using the kill
command, terminate the identified process:
kill -9 12345
The -9
flag sends the SIGKILL
signal, which forces the process to stop instantly.
Note: You might also consider using the
-15
flag (i.e.,SIGTERM
), which permits the process to gracefully shut down.
Run the lsof
command again to ensure no process is occupying port 8112. If there’s no output, the port is free.
Now that the port is available, you can re-run your server setup function, and it should function without any hitches.
By following these steps, you can easily resolve the “address already in use” error when deploying a server. Always remember to ensure ports are properly closed when shutting down servers or services to avoid such issues in the future.
References: