From 3a49d82d04e72f2352c91559c0fe56879b58ffd6 Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 30 Sep 2025 12:20:11 +0100 Subject: [PATCH] Added healthcheck, Added readyz, livez endpoints --- app/main.py | 28 +++++++++++++++++++++++++--- docker-compose.yml.example | 5 +++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 4a1414c..529e656 100644 --- a/app/main.py +++ b/app/main.py @@ -1,7 +1,11 @@ from fastapi import FastAPI +from sqlalchemy import text +from sqlalchemy.exc import SQLAlchemyError +from starlette.responses import JSONResponse from app.api.v1 import auth, keys from app.core.config import settings +from app.db.session import AsyncSessionLocal app = FastAPI( title=settings.PROJECT_NAME @@ -9,7 +13,25 @@ app = FastAPI( app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["auth"]) app.include_router(keys.router, prefix=f"{settings.API_V1_STR}/keys", tags=["keys"]) -# Health endpoint (useful for docker, agent and uptime) +# Is the API running? +@app.get("/livez") +async def livez(): + return {"status": "ok"} + +# Is the application ready (including db)? +@app.get("/readyz") +async def readyz(): + try: + async with AsyncSessionLocal() as session: + await session.execute(text("SELECT 1")) + return {"status": "ok", "db": "up"} + except SQLAlchemyError: + return JSONResponse( + status_code=503, + content={"status": "degraded", "db": "down"}, + ) + +# Is the application healthy (ready)? @app.get("/healthz") -def healthz(): - return {"ok": True} \ No newline at end of file +async def healthz(): + return await readyz() # alias \ No newline at end of file diff --git a/docker-compose.yml.example b/docker-compose.yml.example index 9ff930d..de36bde 100644 --- a/docker-compose.yml.example +++ b/docker-compose.yml.example @@ -43,6 +43,11 @@ services: # ports: # - "8000:8000" command: uvicorn app.main:app --host 0.0.0.0 --port 8000 + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/healthz"] + interval: 10s + timeout: 5s + retries: 5 volumes: pgdata: \ No newline at end of file