我有一个简单的 FastAPI 项目。它在 Pycharm 和 Docker 容器中运行正常。但通过 nginx 运行时,StaticFiles
无法交付。
结构是这样的:
├── app
│ ├── main.py
│ ├── static_stuff
│ │ └── styles.css
│ └── templates
│ └── item.html
├── Dockerfile
├── requirements.txt
主程序
from fastapi import Request, FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import os.path as path
ROOT_PATH = path.abspath(path.join(__file__ ,"../"))
app = FastAPI(title="my_app", root_path='/my_app')
app.mount("/static_stuff", StaticFiles(directory=f"/{ROOT_PATH}/static_stuff"), name="static")
templates = Jinja2Templates(directory=f"/{ROOT_PATH}/templates")
@app.get("/items/{id}", response_class=HTMLResponse, include_in_schema=False)
async def read_item(request: Request, id: str):
return templates.TemplateResponse(
request=request, name="item.html", context={"id": id}
)
该应用程序正在docker容器中运行:
Dockerfile:
FROM python:3.13-slim
WORKDIR /my_app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "app.main:app", "--bind", "0.0.0.0:6543"]
EXPOSE 6543
nginx 配置如下:
location /my_app {
proxy_pass http://my_host:6543;
include proxy_params;
}
当调用 nginx -> http://my_host/my_app/items/5
除了静态文件之外,一切正常。找不到styles.css。我做错了什么?
我尝试过类似的方法,但没有成功
location ~ /static_stuff/(.+) {
proxy_pass http://my_host:6543;
include proxy_params;
}
root_path
FastAPI 中挂载路径的参数似乎存在错误。如果您指定root_path
为参数,__init__
它会要求附加my_app/
路径。因此,您的文件可以在/my_app/my_app/static_stuff/
而不是上访问/my_app/static_stuff/
。尝试将其指定
root_path
为服务器的参数(例如,uvicorn main:app --root-path my_app
对于 uvicorn),而不是将其作为的参数传递__init__
。这很简单:
你在这里添加了一个斜杠
/
:directory=f"/{ROOT_PATH}/static_stuff"
,但这会导致路径无效,因为ROOT_PATH
它已经是绝对路径了。将其更改为directory=f"{ROOT_PATH}/static_stuff"
应该就可以了。您可以使用一段简单的代码来检查:
将会回归