diff --git a/main.py b/main.py index 094d57b..1ada1d1 100644 --- a/main.py +++ b/main.py @@ -1,4 +1,6 @@ import os +import socket +import sys import uvicorn from fastapi import FastAPI @@ -33,10 +35,31 @@ app.include_router(health_router.router, prefix="/api", tags=["health"]) async def startup(): 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__": - # Get port from environment variable or use default of 8002 - # This avoids the conflict with port 8001 which is already in use - port = int(os.environ.get("PORT", 8002)) + # Get port from environment variable or use default of 8000 + port = int(os.environ.get("PORT", 8000)) 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)