fastapi+https

lightsong發表於2024-06-18

docker-fastapi-celery

https://github.com/fanqingsong/docker-fastapi-celery

設定了https證書,可以執行檢視效果。

Run on local machine

Install docker and docker-compose

Run entire app with one command
sh local_env_up.sh
content of local_env_up.sh
sudo docker-compose -f docker-compose.yml up --scale worker=2 --build

docker-compose.yaml

version: "3.7"

services:
fastapi:
build:
context: .
dockerfile: DockerfileWebApi
environment:
REDISSERVER: redis://redis_server:6379
C_FORCE_ROOT: "true"
ports:
- "5000:80"
secrets:
- certificate_cert
- certificate_key
command: ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80", "--ssl-keyfile", "/run/secrets/certificate_key", "--ssl-keyfile-password", "123456", "--ssl-certfile", "/run/secrets/certificate_cert"]
depends_on:
- redis_server
worker:
build:
dockerfile: DockerfileCelery
context: .
environment:
REDISSERVER: redis://redis_server:6379
C_FORCE_ROOT: "true"
depends_on:
- redis_server
redis_server:
image: redis

flower:
image: mher/flower
command: ["celery", "--broker=redis://redis_server:6379", "flower", "--port=5555"]
ports:
- "5555:5555"
depends_on:
- redis_server

secrets:
certificate_cert:
file: ./certificate/cert.pem
certificate_key:
file: ./certificate/key.pem

use-secrets - docker-compose

https://docs.docker.com/compose/use-secrets/

A secret is any piece of data, such as a password, certificate, or API key, that shouldn’t be transmitted over a network or stored unencrypted in a Dockerfile or in your application’s source code.

Docker Compose provides a way for you to use secrets without having to use environment variables to store information. If you’re injecting passwords and API keys as environment variables, you risk unintentional information exposure. Services can only access secrets when explicitly granted by a secrets attribute within the services top-level element.

Environment variables are often available to all processes, and it can be difficult to track access. They can also be printed in logs when debugging errors without your knowledge. Using secrets mitigates these risks.

base image

https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker/tree/master

Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python with performance auto-tuning.

uvicorn + https

https://www.uvicorn.org/deployment/#running-with-https

Running with HTTPS

To run uvicorn with https, a certificate and a private key are required. The recommended way to get them is using Let's Encrypt.

For local development with https, it's possible to use mkcert to generate a valid certificate and private key.

$ uvicorn main:app --port 5000 --ssl-keyfile=./key.pem --ssl-certfile=./cert.pem

https://www.uvicorn.org/deployment/

  --ssl-keyfile TEXT              SSL key file
  --ssl-certfile TEXT             SSL certificate file
  --ssl-keyfile-password TEXT     SSL keyfile password