Docker容器运行FastAPI时无法找到static/templates目录求助
解决Docker中FastAPI找不到static目录的问题
问题原因
本地运行时,你的工作目录是项目根目录(static和templates所在目录),所以相对路径"static"能正确指向目录;但在Docker容器中,WORKDIR被设为/tmp,运行uvicorn时工作目录仍为/tmp,程序会去/tmp/static查找目录,而实际static目录在/opt/apps/app1/static,因此触发"目录不存在"的错误。
两种修复方案
方案1:在代码中使用基于脚本位置的动态路径
修改app1.py,通过__file__获取当前脚本的绝对路径,拼接出static和templates的正确位置,这样无论工作目录在哪都能找到:
from fastapi import FastAPI, Request from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import os # 获取当前脚本所在的目录 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) app = FastAPI() app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "static")), name="static") templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))
方案2:修改Dockerfile的工作目录
在Dockerfile中把工作目录切换到APP_DIR,这样运行uvicorn时相对路径会指向正确的目录:
FROM python:3.13-alpine WORKDIR /tmp COPY ./requirements.txt ./ RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PORT=8080 ENV APP_DIR=/opt/apps/app1 ENV APP_APP=app1:app RUN mkdir -p $APP_DIR COPY *.py $APP_DIR/ COPY *.toml $APP_DIR/ COPY static/ $APP_DIR/static/ COPY templates/ $APP_DIR/templates/ # 添加这行,切换工作目录到APP_DIR WORKDIR $APP_DIR ENTRYPOINT uvicorn $APP_APP --host 0.0.0.0 --port $PORT EXPOSE $PORT
这样修改后,容器内运行程序时,相对路径"static"就会指向/opt/apps/app1/static,问题即可解决。
内容的提问来源于stack exchange,提问作者John Heyer
相关产品推荐
相关产品推荐

