FastAPI+Jinja渲染图片在AWS App Runner容器中无法显示
问题背景
本地通过uvicorn运行FastAPI+Jinja2服务时,静态图片显示正常,但将服务打包为Docker容器部署到AWS App Runner后,图片无法加载。
相关代码与配置
主文件main.py
from routers import routers_main app = FastAPI() # 挂载静态文件目录 app.mount("/static", StaticFiles(directory="static"), name="static") app.include_router(routers_main.router)
路由文件routers/routers_main.py
router = APIRouter() @router.get("/", response_class=HTMLResponse) def home_page(request: Request): image_url_1 = request.url_for("static", path=f"website_flow.png") return templates.TemplateResponse("home.html", {"request": request, "visits": visits, "image_1": image_url_1})
HTML图片引用
<img src="{{ image_1 }}" alt="Image 12" style="width: 100%; height: auto;">
容器启动命令
CMD ["gunicorn", "-b", "0.0.0.0:3400", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "main:app"]
目录结构
--- main.py --- routers/ ------ routers_main.py --- static/ ------ website_flow.png
报错信息
浏览器控制台输出:
Mixed Content: The page at 'https://nhs6qhaxjj.us-east-1.awsapprunner.com/' was loaded over HTTPS, but requested an insecure element 'http://nhs6qhaxjj.us-east-1.awsapprunner.com/static/telugu_dictionary_flowchart.png'. This request was automatically upgraded to HTTPS
website_flow.png:1Failed to load resource: the server responded with a status of 404 (Not Found)
已尝试无效方案
- 在HTML头部添加Content-Security-Policy标签
- 引入HTTPSRedirectMiddleware中间件
- 使用
--proxy-headers参数启动uvicorn和gunicorn
环境版本
FastAPI 0.100.0,Starlette 0.27.0
解决建议
修复代理协议识别
AWS App Runner的请求经过反向代理,FastAPI/Starlette可能无法正确识别外部HTTPS协议。修改Gunicorn启动命令,添加--forwarded-allow-ips='*'以允许接收代理转发头:CMD ["gunicorn", "-b", "0.0.0.0:3400", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "--forwarded-allow-ips='*'", "main:app"]同时在FastAPI初始化时开启信任环境变量:
app = FastAPI(trust_env=True)确认静态文件镜像复制
检查Dockerfile是否正确复制静态文件,添加以下指令确保静态目录完整进入镜像:WORKDIR /app COPY . .简化路径测试
暂时跳过request.url_for生成URL,直接在HTML中使用绝对路径验证:<img src="/static/website_flow.png" alt="Image 12" style="width: 100%; height: auto;">核对端口配置
确认AWS App Runner的端口设置与容器内部端口(3400)完全一致,避免端口映射错误导致资源无法访问。
内容的提问来源于stack exchange,提问作者Hrushi

