I want the same port on uvicorn and eureka configuration, I have search a lot and only found this link https://github.com/encode/uvicorn/issues/761 but it doesn't work, this is my code:
import py_eureka_client.eureka_client as eureka_client
import uvicorn
from fastapi import FastAPI
from contextlib import asynccontextmanager
from com.controladores import controladorRouter
@asynccontextmanager
async def lifespan(app: FastAPI):
await eureka_client.init_async(
eureka_server="http://eureka-primary:8011/eureka/,http://eureka-secondary:8012/eureka/,http://eureka-tertiary:8013/eureka/",
app_name="msprueba",
instance_port=8000,
instance_host="localhost"
)
yield
app = FastAPI(lifespan=lifespan)
app.include_router(controladorRouter)
if __name__ == "__main__":
config = uvicorn.Config("com.main:app", host="localhost", port=0)
server = uvicorn.Server(config)
server.run()
I removed the code from the link only to show the actual code, I find it hard to believe that simple such task is so hard to do with fastapi. Don't get me wrong fastapi is a great tool, only thing is that I come from springboot and this task is much easier to do in springboot, any help?
I create a variable with the port like this:
import socket
sock = socket.socket()
sock.bind(('', 0))
APLICACION_PUERTO = sock.getsockname()[1]
sock.close()
I need to close the socket because if I try to use it on fastapi, it throws an error that is already in use.
My only doubt is if I run multiple microservices, and I close the socket, I don't know if is possible that another application use the same port that I'm trying to use.
I think the posibility of that is very close to zero, but it could happen.
Also now I cannot run the command uvicorn and I need to run my application with python3 -m main
, is not bad at all but I think is something I need to share.
If someone know another better way, please share the idea with me please.