Home › Python

OSError: [Errno 98] Address already in use (Python) — how to fix

Traceback (most recent call last):
  File "server.py", line 6, in <module>
    s.bind(("0.0.0.0", 8000))
OSError: [Errno 98] Address already in use

Quick fix: Find what holds the port with sudo ss -ltnp 'sport = :8000' (or lsof -i :8000) and stop it (kill <PID>). For your own servers set SO_REUSEADDR before bind(): s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1). Or use another port.

What it means

bind() failed because the address/port pair is taken. Errno 98 is Linux's EADDRINUSE (on macOS it is [Errno 48], on Windows [WinError 10048]). Frameworks show the same thing in their own words: Flask/Werkzeug says "Address already in use ... Port 5000 is in use by another program", Django's runserver says "Error: That port is already in use."

Cause 1: a previous run is still running

The most common case: the old server is still alive in another terminal, in the background, in a crashed IDE run, or as a zombie child of a reloader.

Find it:

sudo ss -ltnp 'sport = :8000'
# or
sudo lsof -i :8000

Stop it:

kill <PID>          # polite
kill -9 <PID>       # if it ignores SIGTERM

If you started it with Ctrl+Z, it is suspended, not stopped. Run fg and then Ctrl+C, or kill %1.

Cause 2: socket stuck in TIME_WAIT after a restart

After a server closes connections, the kernel keeps the port in TIME_WAIT for a while. Restarting immediately then fails even though nothing is running. ss -tan | grep 8000 shows TIME-WAIT entries.

Set SO_REUSEADDR before bind():

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 8000))
s.listen()

For socketserver / http.server subclasses, set the class attribute:

import socketserver

class Server(socketserver.TCPServer):
    allow_reuse_address = True

SO_REUSEADDR does not let two live servers share a port; it only skips the TIME_WAIT wait.

Cause 3: another service already uses the port

Ports like 80, 5000, 8000 and 8080 are popular. On macOS Monterey and later, the AirPlay Receiver listens on port 5000, which breaks Flask's default port. Either stop the other service or pick another port:

flask run --port 5001
python manage.py runserver 8001
uvicorn main:app --port 8001
python -m http.server 8001

Cause 4: binding twice in the same program

Calling bind() on the same port twice (for example, in a loop, or once at import time and again in main) fails on the second call. Debug reloaders also start the app twice; with Flask, starting your own background server at import time collides with the reloader's child process. Guard such code with if __name__ == "__main__": or run with use_reloader=False.

Cause 5: a Docker container published the port

If ss shows docker-proxy holding the port, a container maps it. List and stop it:

docker ps --filter "publish=8000"
docker stop <container>

Last updated 2026-12-03.