如何用gunicorn让FastAPI在K8s下同时运行无重定向的HTTP和HTTPS服务
适配需求的完整实现方案
前置依赖
安装所需服务包:pip install fastapi gunicorn uvicorn
核心逻辑说明
无需借助NGINX,直接通过FastAPI中间件做端口隔离,同时让Gunicorn监听两个独立端口:
- 8000端口:HTTP协议,仅开放健康检查接口,无任何重定向逻辑,专门供K8s liveness probe调用
- 8443端口:HTTPS协议,使用企业指定的固定端口,对外提供所有业务服务,不存在HTTP转HTTPS的重定向配置
FastAPI 代码实现
from fastapi import FastAPI, Request from fastapi.responses import PlainTextResponse app = FastAPI() # 健康检查接口,适配K8s探针要求,直接返回200 @app.get("/health/liveness", response_class=PlainTextResponse, status_code=200) async def liveness_probe(): return "ok" # 端口安全校验中间件 @app.middleware("http") async def port_validate_middleware(request: Request, call_next): # 按企业要求配置端口参数 HTTP_HEALTH_CHECK_PORT = 8000 HTTPS_FIXED_BUSINESS_PORT = 8443 request_port = request.url.port # HTTP健康检查端口逻辑 if request_port == HTTP_HEALTH_CHECK_PORT: # 仅允许访问健康检查路径,其他路径返回403,无重定向 if request.url.path != "/health/liveness": return PlainTextResponse("Only health check allowed on this port", status_code=403) return await call_next(request) # HTTPS业务端口逻辑,直接放行所有请求 if request_port == HTTPS_FIXED_BUSINESS_PORT: return await call_next(request) # 其他端口直接拒绝访问 return PlainTextResponse("Forbidden", status_code=403) # 业务接口示例,仅可通过HTTPS端口访问 @app.get("/api/v1/demo") async def demo_api(): return {"msg": "This is business service, only accessible via HTTPS"}
Gunicorn 启动命令
同时绑定两个端口,HTTPS端口配置对应的证书:
gunicorn main:app \ --workers 4 \ --worker-class uvicorn.workers.UvicornWorker \ --bind 0.0.0.0:8000 \ --bind 0.0.0.0:8443 \ --keyfile /your/cert/path/private.key \ --certfile /your/cert/path/fullchain.crt \ --ssl-version TLSv1_2
注意将端口、证书路径替换为企业实际配置的值。
Kubernetes Liveness Probe 配置
直接调用HTTP健康检查端口的对应接口,不会触发重定向:
livenessProbe: httpGet: path: /health/liveness port: 8000 initialDelaySeconds: 15 periodSeconds: 30 failureThreshold: 3
方案适配性说明
- 完全符合健康检查要求:HTTP端口无任何重定向逻辑,探针请求直接返回200状态码
- HTTPS端口使用预先指定的固定端口,符合企业安全规范
- 无需依赖NGINX,全部逻辑由Gunicorn+FastAPI原生实现
- 业务接口仅可通过HTTPS访问,不会出现HTTP明文传输业务数据的风险
内容的提问来源于stack exchange,提问作者Anirban Saha
相关产品推荐
相关产品推荐

