'How to serve static files saved in a docker volume with FastAPI?
I've created two volumes, t21db for my SQLite DB and t21images for my images, in my FastAPI app im using app.mount to mount the location for the volume to retrieve the images, here's the code -
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/app/images", StaticFiles(directory="."), name="static") # <--- here, is this directory correct?
app.include_router(webapp, prefix='/api/v1/webapp', tags=["WebApp"])
app.include_router(webapptype, prefix='/api/v1/webapptype', tags=["WebAppType"])
I have an endpoint which uses a function to get the image URL's from the volume but this doesn't seem to be working at the moment as I'm getting a status code 404 back
def __get_url(self, image, request: Request):
return request.url_for('static', path=f"app/images/{image}")
this is how I am running my container & mounting volumes to it -
docker run --mount source=t21db,target=/app/db --mount source=t21images,target=/app/images -p 3088:5000 t21
I was previously using /app/images path to retrieve images to encode but later changed that serving the image URL was more efficient
How can I get the correct volume path in my app to serve the static files?
Solution 1:[1]
i hope it'll helpfull,
what i using in mine without mounting directory in docker is
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/media", StaticFiles(directory="media"), name="media")
make sure you set directory correctly
and try
app.mount("/images", StaticFiles(directory="images"), name="images")
i even used traefik or nginx without mounting my statics or ... folder
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashkan Goleh Pour |
