This comprehensive guide will help you expose static files from your FastAPI app behind a Traefik proxy. Our example setup includes Traefik and the API set up as services, with Traefik acting as a reverse proxy.
├── back
│ ├── Dockerfile
│ ├── main.py
│ ├── requirements.txt
│ └── static
│ └── test.html
└── docker-compose.yml
1. Configure Traefik
In the docker-compose.yml
file, Traefik is configured with the following labels:
traefik.enable=true
: Enables Traefik for this service.traefik.http.routers.fhback.rule=Host(`example.com`) && PathPrefix(`/`)
: Specifies the rule for matching incoming requests to this service. In this case, it matches requests to theexample.com
hostname and the/
path prefix.traefik.http.services.fhback.loadbalancer.server.port=8000
: Specifies the port on which the FastAPI app is listening inside the container.traefik.http.middlewares.firehouse-compress.compress=true
: Enables GZIP compression for responses from this service.traefik.http.routers.fhback.middlewares=firehouse-compress,fhback-stripprefix
: Specifies the middleware to be applied to requests to this service. In this case, we're using thefirehouse-compress
middleware to enable GZIP compression and thefhback-stripprefix
middleware to remove the/
prefix from the request path before passing it to the FastAPI app.traefik.http.middlewares.testheader.headers.customresponseheaders.X-Test-Header=TraefikProxy
: Adds a custom response header calledX-Test-Header
with the valueTraefikProxy
to responses from this service.traefik.http.routers.fhback.middlewares=testheader
: Specifies that thetestheader
middleware should be applied to requests to this service.
2. Configure FastAPI
In the main.py
file, we mount the static
directory as a static file endpoint at /static
using app.mount('/static', StaticFiles(directory='static'), name='static')
.
3. Build and Run the Application
Run docker-compose up
to build and run the application. Make sure you have Docker installed and running.
4. Test the Application
Use curl
to send a request to the FastAPI app and verify that the static file is served correctly:
curl -v --resolve example.com:80:127.0.0.1 http://example.com/static/test.html
You should see the content of the test.html
file in the response. Additionally, you can check the Traefik logs to confirm that the request was proxied through Traefik.
This guide provides a solid foundation for exposing static files from your FastAPI app behind a Traefik proxy. Feel free to adapt it to your specific requirements.