Home > Back-end >  How to serve static files saved in a docker volume with FastAPI?
How to serve static files saved in a docker volume with FastAPI?

Time:05-25

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?

CodePudding user response:

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

CodePudding user response:

Ok, so the solution is to add the path to the directory as the initial path param in app.mount

So this worked -

app.mount("/app/images", StaticFiles(directory="/apps/images"), name="static")
  • Related