Jupyter重运行Plotly Dash应用遇OSError:端口已占用的解决求助
Hey there, I've run into this exact headache when working with Dash in a VM—super frustrating when you can't just flip to a new port! Let's break down why this happens and the practical fixes that work:
Why does this happen?
When you run Dash with debug=True, it uses an auto-reloader that spins up a secondary process to watch for code changes. Sometimes when you modify your code, this reloader fails to clean up the old process properly, leaving the port locked by a "zombie" process that's still hanging around.
Solution 1: Disable the auto-reloader (quick no-fuss fix)
If you don't mind manually restarting the app after code edits, you can turn off the reloader entirely. Just add use_reloader=False to your run_server call:
if __name__ == '__main__': app.run_server(port = 8021, debug = True, use_reloader=False)
Pros: No more port lock issues ever again.
Cons: You'll have to stop and restart the app every time you tweak your code.
Solution 2: Use a more reliable reloader (keep auto-updates working)
The default reloader can be flaky. Install the watchdog library, which provides a far more stable reloader that properly cleans up old processes when you make changes:
First install watchdog via pip:
pip install watchdog
Then update your run_server call to use it:
if __name__ == '__main__': app.run_server(port = 8021, debug = True, reloader_type='watchdog')
Pros: Keeps auto-reloading functional, and rarely leaves orphaned processes behind.
Cons: Requires installing one extra library (totally worth it for the peace of mind).
Solution 3: Manually kill the stuck process (emergency fix)
If you already have a locked port right now, you can find and kill the process using it directly in your VM:
- First, find the PID (process ID) of the process hogging port 8021:
lsof -i :8021
(If lsof isn't installed, run sudo apt install lsof for Debian/Ubuntu or sudo yum install lsof for RHEL/CentOS first.)
- Kill the process with the PID you found (replace
<PID>with the actual number from the previous step):
kill -9 <PID>
Pros: Fixes the immediate port lock problem.
Cons: It's a manual step you'll have to repeat every time the issue pops up.
Bonus: Switch to JupyterDash (if you're in a notebook environment)
I noticed you imported JupyterDash but are using dash.Dash—if you're running this in a Jupyter notebook/lab, switching to JupyterDash might help with process management:
# Replace dash.Dash with JupyterDash in your initialization app = JupyterDash("SimpleExample")
Then run it with your usual port setting:
if __name__ == '__main__': app.run_server(port=8021, debug=True)
JupyterDash handles process lifecycle differently in notebook environments, which can cut down on port lock issues entirely.
内容的提问来源于stack exchange,提问作者Manu Sharma

