Docker化你的 FastAPI 和 Celery 应用
PDF version is available!
PDF 版本已提供!
Download the PDF version of this post for free:
免费下载本帖的 PDF 版本:
A while ago I wrote a tutorial about how to use Celery with FastAPI to run asynchronous tasks. In this post, I will explain how to dockerize the application and simplify the deployment with Docker Compose.
不久前我写了一篇教程,介绍如何使用 Celery 与 FastAPI 运行异步任务。在本文中,我将说明如何将该应用容器化,并通过 Docker Compose 简化部署。
Make sure you already have Docker installed on your system.
请确保你的系统已安装 Docker。
The source code to deploy
要部署的源代码
To recap, here is the source code from my previous FastAPI and Celery tutorial. We have three files:
回顾一下,这是我之前 FastAPI 和 Celery 教程 中的源代码。我们有三个文件:
-
requirements.txt
- The file that specify the required dependencies. -
requirements.txt
- 指定所需依赖的文件。 -
main.py
- Contains the FastAPI application -
main.py
- 包含 FastAPI 应用程序 -
tasks.py
- Contains the Celery tasks -
tasks.py
- 包含 Celery 任务
The contents of requirements.txt
:
requirements.txt
的内容如下:
Text
文本
fastapi==0.111.0
celery==5.4.0
redis==5.0.4
The contents of main.py
:
main.py
的内容:
Python
Python
from fastapi import FastAPI
from .tasks import celery, square_root app = FastAPI() @app.post('/square_root')
def process(num: float): task = square_root.delay(num) return {'taskId': task.id} @app.get('/status/{task_id}')
def status(task_id: str): task = celery.AsyncResult(task_id) if task.ready(): return {'status': 'DONE', 'result': task.get()} else: return {'status': 'IN_PROGRESS'}
The contents of tasks.py
:
tasks.py
的内容:
Python
Python
import math
import time
import os from celery import Celery REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')
REDIS_PORT = os.getenv('REDIS_PORT', 6379) celery = Celery( 'tasks', broker=f'redis://{REDIS_HOST}:{REDIS_PORT}/0', backend=f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
) @celery.task
def square_root(num: float): time.sleep(10) return math.sqrt(num)
In short, this simple application provides two endpoints:
简而言之,这个简单的应用提供了两个端点:
-
/square_root
: start the task -
/square_root
: 启动任务 -
/status/<task_id>
: check the status of the task. -
/status/<task_id>
:检查任务状态。
When yo...