Add port availability checking to avoid port conflicts
This commit is contained in:
parent
ca3feba815
commit
d90ef349f8
29
main.py
29
main.py
@ -1,4 +1,6 @@
|
|||||||
import os
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
|
||||||
import uvicorn
|
import uvicorn
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
@ -33,10 +35,31 @@ app.include_router(health_router.router, prefix="/api", tags=["health"])
|
|||||||
async def startup():
|
async def startup():
|
||||||
create_tables()
|
create_tables()
|
||||||
|
|
||||||
|
def is_port_in_use(port, host='0.0.0.0'):
|
||||||
|
"""Check if a port is in use."""
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||||
|
try:
|
||||||
|
s.bind((host, port))
|
||||||
|
return False
|
||||||
|
except OSError:
|
||||||
|
return True
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# Get port from environment variable or use default of 8002
|
# Get port from environment variable or use default of 8000
|
||||||
# This avoids the conflict with port 8001 which is already in use
|
port = int(os.environ.get("PORT", 8000))
|
||||||
port = int(os.environ.get("PORT", 8002))
|
|
||||||
host = os.environ.get("HOST", "0.0.0.0")
|
host = os.environ.get("HOST", "0.0.0.0")
|
||||||
|
|
||||||
|
# If the preferred port is in use, try to find an available port
|
||||||
|
if is_port_in_use(port, host):
|
||||||
|
print(f"Port {port} is already in use. Trying alternative ports...")
|
||||||
|
for alt_port in [8001, 8002, 8003, 8004, 8005]:
|
||||||
|
if not is_port_in_use(alt_port, host):
|
||||||
|
port = alt_port
|
||||||
|
print(f"Found available port: {port}")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
print("No available ports found between 8000-8005. Exiting.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"Starting server on {host}:{port}")
|
||||||
uvicorn.run("main:app", host=host, port=port, reload=True)
|
uvicorn.run("main:app", host=host, port=port, reload=True)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user