sslhttpsgunicornfastapi

How can we run a FastAPI application on two ports one HTTP and one HTTPS without redirecting?


I want to host my FastAPI application using gunicorn and host it on a Kubernetes Service. My Kubernetes service runs a liveness probe (health check) using HTTP call on a specified endpoint.

I also want the application to be served on HTTPS because my Kubernetes service exposes it to be used by external components.

Now my HTTP endpoint can't rely on redirection as the liveness probe expects a 200 Response and redirection will hamper that.

I want to host my HTTPS endpoint on a pre-specified port as the organization has the best practices in place and the endpoint and port are specified.

Some similar problems on StackOverflow:

  1. Running Gunicorn on both http and https
  2. uvicorn [fastapi] python run both HTTP and HTTPS

But both of these are okay with redirection, and we are not. And we cannot use the NGINX server too, because that support is deprecated in my organization.


Solution

  • If we are trying this out in a Docker environment. The following will get it done:

    Dockerfile:

    ENTRYPOINT ./start.sh
    

    Shell Script start.sh:

    gunicorn -k uvicorn.workers.UvicornWorker -w 3 -b 0.0.0.0:30000 -t 360 --reload app:app & gunicorn -k uvicorn.workers.UvicornWorker -w 3 --ssl-certfile certfile.txt --ssl-keyfile keyfile.txt --ca-certs ca_certs.txt -b 0.0.0.0:8443 -t 360 --reload app:app 
    

    The & runs one in the background and then runs the other one. You can configure one to use HTTP and one to use HTTPS.

    We are using gunicorn for fastAPI application so we are using uvicorn workers and you need to change it accordingly for your use case.