Cloud Explainers

How to Fix Python 'Address Already in Use' Errors

Python8 min video

'Address already in use' (OSError: [Errno 98]) means another socket already holds the port your Python app wants. On a real Ubuntu machine we find who holds it with sudo ss -ltnp and lsof, show why Ctrl+Z leaves a paused server holding the port, pick another port when it isn't yours to stop, and fix the error that comes right after a restart (TIME-WAIT) with SO_REUSEADDR.

Port 5000 is taken

Your Python app won't start: address already in use. At a small greenhouse, Ana runs a dashboard that shows the temperature on each bench. She starts it, and Flask says port five thousand is in use by another program. Flask is polite enough not to say which one. Nothing of hers is running. So what is holding port five thousand? There are four usual reasons, and if you're on a Mac, one of them is the Mac itself. By the end you'll know which one is yours, and how to fix it.

Ana: the dashboard window
python3 dashboard.py * Serving Flask app 'dashboard'
 * Debug mode: off
Address already in use
Port 5000 is in use by another program. Either identify and stop that program, or start the server with a different port.

One program per port

A port is a numbered way into a computer. A server claims one, and listens on it for a browser to knock. Think of a hotel room: one guest per room. When a second program asks Linux for the same number, Linux refuses, with error ninety-eight: address already in use. It says address because a server claims two things at once: the computer's network address, and the port number. So first, we find who's in the room and clear it. Then a stranger case: the same error, with nobody in the room at all.

One port, one program listening: diagram of A browser, Port 5000, Another program, Ana's copy, Linux, The greenhouse computer

Find who holds the port

The greenhouse computer is shared: Ben, who works there too, logs in to it as well. To find out who holds the port, Ana uses ss, a tool that lists network connections. She asks who's listening on port five thousand. The L asks for listeners, and the P asks for the program's name. It shows a listener, but no name. That's a clue: ss only names your own programs, so this one belongs to someone else. So she runs it again with sudo, as the administrator, who can see everyone's programs. Now ss names it: python three, process number 14. And ps, the tool that lists running programs, says whose it is: Ben's. He started his own copy earlier, to try a change, and left it running.

Ana: the dashboard window
ss -ltnp 'sport = :5000'State  Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process
LISTEN  0  128  127.0.0.1:5000  0.0.0.0:*
Ana: the dashboard window
sudo ss -ltnp 'sport = :5000'State  Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process
LISTEN  0  128  127.0.0.1:5000  0.0.0.0:*  users:(("python3",pid=14,fd=3))
Ana: the dashboard window
ps -o user,pid,etime,cmd -p 14USER         PID     ELAPSED CMD
ben           14       00:07 python3 dashboard.py

Ana checks with Ben, then stops his copy with kill and that process number. It needs sudo too, because the program is Ben's, not hers. kill asks the program to stop, and a Flask server does. ss shows the port free again.

Ana: the dashboard window
sudo kill 14
Ana: the dashboard window
sudo ss -ltnp 'sport = :5000'State  Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process

The two steps are the same everywhere: find the process number, then stop it. This table has the commands for Linux, Mac, and Windows. On a Mac, the finding tool is called lsof. Pause here if you need yours. If a program ignores a plain kill, use kill dash nine. That ends it at once, but skips its clean-up, so always try the plain kill first.

Find who holds the port, then stop it: comparison table of Find it vs Stop it, Linux, macOS, Windows, Last resort

Paused is not stopped

Ana starts her dashboard, and it runs. To stop it, she presses Ctrl+Z. The terminal says: stopped, and gives her the prompt back. Guess first: is port five thousand free now? No. Starting it again gives the same error as before.

Ana: the dashboard window
python3 dashboard.py * Serving Flask app 'dashboard'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
^Z

[1]+  Stopped                 python3 dashboard.py
Ana: the dashboard window
python3 dashboard.py * Serving Flask app 'dashboard'
 * Debug mode: off
Address already in use
Port 5000 is in use by another program. Either identify and stop that program, or start the server with a different port.

The terminal said stopped, but it really means paused. Ctrl+Z doesn't end a program. The jobs command lists it: stopped, but still there. Like a guest asleep in the room: the room is taken, and nobody answers the door. curl, which fetches a page from the terminal, knocks on the port. Nobody answers, so after three seconds it gives up. fg brings the paused program back to the front. It wakes up, answers the knock that was still waiting, and logs it, and then Ctrl+C really stops it.

Ana: the dashboard window
jobs[1]+  Stopped                 python3 dashboard.py
Ana: the dashboard window
curl -m 3 localhost:5000curl: (28) Operation timed out after 3007 milliseconds with 0 bytes received
Ana: the dashboard window
fgpython3 dashboard.py
127.0.0.1 - - [26/Nov/2026 23:56:29] "GET / HTTP/1.1" 200 -
^C

When it's not yours to stop

Sometimes the program on the port isn't yours to stop. Flask's own docs say what to do: stop the other program, or pick a different port. On a Mac, it's often the Mac itself: since macOS Monterey, a built-in service called AirPlay Receiver uses port five thousand. Turn it off in System Settings, or move your app to another port.

When it's not yours to stop: browser screenshot from the video

Moving is one command. Instead of python three, Ana uses Flask's own command, flask run, because it can take a port number. Dash dash app names the file, and dash dash port picks five thousand and one. It starts at once. Just remember to open it at port five thousand and one in your browser now.

Ana: a second window
flask --app dashboard run --port 5001 * Serving Flask app 'dashboard'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5001
Press CTRL+C to quit
^C

It fails right after a restart

Now the strange one. The greenhouse has a second program, the collector. It's written with Python's socket module. That's the basic building block for network programs, without any of Flask's extras. It takes a reading from each bench's sensor on port nine thousand. Ana stops it properly, with Ctrl+C, and starts it again straight away. This time it's plain Python's error: error ninety-eight. And with sudo, ss finds nobody listening on port nine thousand at all.

Ana: the collector window
python3 collector.pycollector listening on port 9000
bench 2: 22.5 C
bench 3: 20.9 C
bench 1: 22.4 C
bench 2: 21.5 C
bench 3: 21.4 C
^C
collector stopped
Ana: the collector window
python3 collector.pyTraceback (most recent call last):
  File "/home/ana/greenhouse/collector.py", line 5, in <module>
    server.bind(("0.0.0.0", 9000))
OSError: [Errno 98] Address already in use
Ana: the collector window
sudo ss -ltnp 'sport = :9000'State  Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process

Earlier, Ana asked ss only for listeners. This time she swaps the L for an A, for all connections, and adds an O, for timers. There they are: connections from the sensors, each in a state called time wait, with a timer. Guess first: how long until port nine thousand frees itself? About a minute. Ana waits, and 61 seconds after she stopped it, the port is free.

Ana: the collector window
ss -tano 'sport = :9000' | head -4State  Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
TIME-WAIT 0  0  192.168.40.10:9000 192.168.40.21:54072 timer:(timewait,56sec,0)
TIME-WAIT 0  0  192.168.40.10:9000 192.168.40.21:54104 timer:(timewait,59sec,0)
TIME-WAIT 0  0  192.168.40.10:9000 192.168.40.21:54074 timer:(timewait,57sec,0)

Why wait? Each sensor sends a reading, and the collector says ok and hangs up first. The side that hangs up first keeps a note of that connection for a minute, so a delayed message from it can't land in a new conversation by mistake. It's the room being cleaned after checkout: the guest is gone, but nobody gets the room for a while.

Who hangs up first keeps a note for a minute: diagram of Bench sensor, Collector:9000, bench 1: 21.4 C, ok, bye, bye, late message, Port 9000 held until the minute is up

The fix for your own server

Waiting a minute after every restart gets old fast, especially while you're testing changes. Python's socket docs name this exact error, and the fix: a socket option called SO_REUSEADDR, which tells Linux it's fine to reuse a port that's only in time wait.

The fix for your own server: browser screenshot from the video

In the collector, it's one line. It goes just before bind, which is the call that claims the port. The call is setsockopt, short for set socket option, and the number one at the end turns this option on. It never lets two programs listen on one port. It only stops old connections in time wait from blocking a restart. Flask and Python's own http server already set it for you. Your own socket servers don't.

One line: reuse a port in time wait: code change of ~/greenhouse/collector.py, server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) (set before bind()), Flask and http.server set it for you; your own socket servers don't

One catch: right after the change, it fails once more. The connections still waiting were made by the old version, without the option, so they block this one last start. So just this once, Ana waits out the minute, starts the new version, and stops it with Ctrl+C. From then on, she can stop the collector and restart it straight away. The time wait lines are still there, and it starts anyway.

Ana: the collector window
python3 collector.pyTraceback (most recent call last):
  File "/home/ana/greenhouse/collector.py", line 5, in <module>
    server.bind(("0.0.0.0", 9000))
OSError: [Errno 98] Address already in use
Ana: the collector window
python3 collector.pycollector listening on port 9000
bench 2: 21.8 C
bench 3: 22.5 C
bench 1: 21.6 C
bench 2: 22.0 C
bench 3: 22.4 C
^C
bench 1: 22.2 C
collector stopped
Ana: the collector window
ss -tan 'sport = :9000' | head -3State  Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
TIME-WAIT 0  0  192.168.40.10:9000 192.168.40.21:36662
TIME-WAIT 0  0  192.168.40.10:9000 192.168.40.21:36704
Ana: the collector window
python3 collector.pycollector listening on port 9000
bench 2: 21.5 C
bench 3: 21.6 C
bench 1: 22.4 C
^C
bench 2: 20.8 C
collector stopped

Recap

So, which one is yours? Run ss with sudo. If it names someone else's program, stop it, or move to another port. On a Mac, it may be the Mac itself: turn off AirPlay Receiver, or move ports. If it's your own paused one, use fg, then Ctrl+C. And if nobody is listening, it's time wait: wait a minute, or give your server SO_REUSEADDR before bind.

Address already in use: which one is yours?: diagram of Ask who holds it, Someone else's program, Your own, paused, Nobody listening: time wait

If your server starts on the first try now, a like helps YouTube show this to more beginners, and subscribing gets you the next fix, tested on a real machine.

Every error and timer in this video came from a real Ubuntu machine, and the commands and lab files are linked in the description. Thanks for watching Cloud Explainers.

Sources

Demos: two containers on our own Mac standing in for a greenhouse's small computer and its bench sensors; the greenhouse and its people are made up. Every error and timer was real. Watch the full video on YouTube.

More videos

PostgreSQL9 min

Every PostgreSQL Setting to Change After You Install It

Docker9 min

What Happens When You Install Docker on Ubuntu

Go (Golang)5 min

Golang Interfaces and Mocks in 5 Minutes

Git7 min

How to Fix Git 'Detached HEAD' State

Linux21 min

Linux Firewall with ufw: Full Tutorial for Beginners

Go (Golang)5 min

Golang defer Statements in 5 Minutes

Auth (OAuth, JWT)9 min

How to Fix OAuth 'invalid_grant' Errors

Databases & SQL11 min

The SQL Roadmap for Beginners

Go (Golang)5 min

Golang make() for Slices and Maps in 5 Minutes

Networking7 min

How to Fix Network 'No Route to Host' Errors on Linux

Linux6 min

How to Fix Linux 'Too Many Open Files' Errors

Django (Python web framework)11 min

Every Django Concept a Beginner Needs to Know

Linux24 min

SSH on Linux: Full Tutorial for Beginners

Go (Golang)5 min

Golang for range Loops in 5 Minutes

Databases & SQL10 min

SQL Databases: SQLite vs PostgreSQL

Django (Python web framework)10 min

The Django Roadmap for Beginners

Go (Golang)5 min

Golang Structs in 5 Minutes

Caching & Redis22 min

Redis: Full Tutorial for Beginners

Go (Golang)5 min

Golang context.Context in 5 Minutes

Databases & SQL7 min

How to Fix MySQL Database Error 1045: Access Denied for User

Go (Golang)5 min

Golang Method Receivers in 5 Minutes

Python8 min

How to Fix Python SSL: CERTIFICATE_VERIFY_FAILED Errors

Django (Python web framework)9 min

How to Fix Django Static Files Not Loading in Production

OpenRouter (one API for many AI models)8 min

OpenRouter vs Direct API Keys: Which One Should You Use?

Go (Golang)5 min

Golang if err != nil Checks in 5 Minutes

Go (Golang)8 min

How to Fix Golang 'go.mod File Not Found' Errors

AI agents & MCP22 min

MCP Servers: Full Tutorial for Beginners

Go (Golang)5 min

Golang Error Return Values in 5 Minutes

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index