How to solve “Port 5000 is in use by another program” when debug Python Flask code

Henry Wu
preprintblog
Published in
2 min readDec 28, 2023

When writing a python flask project, you always need to debug the code many times. However, sometimes, when you run the code in a short time, without close and restart the file, error happens: Address already in use :

“Port 5000 is in use by another program”

You need to identify and stop the program using that port, or you can choose a different port for your Flask application.

1. Kill the current process

You can use the lsof command to find the process using a specific port. Here's an example:

lsof -i :5000

Once you have the PID, you can use the kill command to stop the process. For example, if the PID is 1234:

kill -9 1234

After stopping the process using the port, you should be able to run your Flask application on port 5000 without encountering the “Address already in use” error.

This method works, but you need to manually deal with everytime. The follwoing are two ways to avoid the address conflict at the first place.

2. Random Port

If you want to use a random port, you can modify your __main__ block like this:

import random

if __name__ == '__main__':
# Generate a random port number between 5000 and 9999
random_port = random.randint(5000, 9999)
app.run(debug=True, port=random_port)

This code uses the random.randint function from the random module to generate a random integer between 5000 and 9999. Adjust the range as needed.

3. Dynamic Port

However, if you want to make it more controlled and avoid conflicts with other applications, you might want to consider using the socket library to find an available port dynamically:

import socket

def find_open_port():
# Create a socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a random available port
sock.bind(('127.0.0.1', 0))

# Get the port that was actually bound
_, port = sock.getsockname()

# Close the socket
sock.close()

return port

if __name__ == '__main__':
# Find an available port dynamically
dynamic_port = find_open_port()

app.run(debug=True, port=dynamic_port)

--

--

Henry Wu
preprintblog

Indie Developer/ Business Analyst/ Python/ AI/ Former Journalist/ Codewriter & Copywriter