FastAPI lifespan event in docker container running, not executing the shutdown

505 Views Asked by At

The below code behaves differently when run under a containerised environment and when run normally in the terminal.

from contextlib import asynccontextmanager
from fastapi import FastAPI
from uvicorn import run



@asynccontextmanager
async def lifespan(app: FastAPI):
    # startup
    logger.info("[IN SYSTEM STARTUP]")     
    logger.info("[STARTUP DONE]")
    
    yield
    # shutdown
    logger.info("[IN SHUTDOWN]")
    logger.info("[IN SHUTDOWN] Done")


app = FastAPI(lifespan=lifespan)

when run in my docker container & when i issue a ctrl+c command, the below happens. The shudown part of the code doesnt get executed.

event_deliver | INFO:     Waiting for application startup.
event_deliver | 2023-09-05 02:50:22,092 - logger INFO - [IN SYSTEM STARTUP]
event_deliver | 2023-09-05 02:50:22,092 - logger INFO - [STARTUP DONE]
event_deliver | INFO:     Application startup complete.
event_deliver | INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
^CGracefully stopping... (press Ctrl+C again to force)
Stopping event_deliver   ... done
Stopping redis           ... done

where as when i run from my terminal using the uvicorn command, and then give a ctrl+c command, it runs my shutdown part of code like below.

2023-09-05 02:57:48,307 - logger INFO - [IN SYSTEM STARTUP]
2023-09-05 02:57:48,307 - logger INFO - [STARTUP DONE]
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
^CINFO:     Shutting down
INFO:     Waiting for application shutdown.
2023-09-05 02:57:52,523 - logger INFO - [IN SHUTDOWN]
2023-09-05 02:57:52,523 - logger INFO - [IN SHUTDOWN] Done
INFO:     Application shutdown complete.
INFO:     Finished server process [70464]

What's really happening here?

0

There are 0 best solutions below