FastAPI 14‑Day Series Day 13: Background Tasks and Docker Deployment – From Development to Production
This article shows how to use FastAPI's built‑in BackgroundTasks for asynchronous notifications, creates a Dockerfile to containerize the app, and demonstrates production‑grade deployment with fastapi run, Uvicorn workers, and Gunicorn, while noting when to switch to Celery for heavier tasks.
1. Background Tasks: BackgroundTasks
Some operations do not need to wait for completion, such as sending notification emails, messaging, or logging.
from fastapi import BackgroundTasks
@app.post("/send-notification")
def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(notify_user, email)
return {"message": "Notification queued"}
def notify_user(email: str):
# actual notification logic
... BackgroundTasksis built into FastAPI and requires no extra dependencies; the task runs asynchronously after the response is sent.
Note: This is a lightweight solution. Production‑grade scheduled or long‑running tasks should use Celery + Redis or FastAPI + RQ.
2. Docker Deployment: Standard Practice
Create a Dockerfile:
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["fastapi", "run", "main.py", "--host", "0.0.0.0", "--port", "8000"]Build and run the image:
docker build -t fastapi-14days .
docker run -p 8000:8000 fastapi-14days3. Production Run: Using fastapi run
The fastapi run command uses Uvicorn under the hood. In production you can add workers:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4Multi‑worker mode with Gunicorn and Uvicorn workers:
gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80004. Day 13 Checklist
BackgroundTasksfor asynchronous notifications Dockerfile to containerize the FastAPI app docker build + docker run to verify containerization
Understanding production run options (Uvicorn / Gunicorn workers)
5. Next Steps
Day 14 will create a comprehensive knowledge map of FastAPI core concepts and answer the most common interview questions.
Related Links
Official documentation (Chinese): https://fastapi.tiangolo.com/zh/tutorial/background-tasks/
Official documentation (Chinese): https://fastapi.tiangolo.com/zh/deployment/docker/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tech Ocean
Focused on AI programming, sharing ready-to-use development efficiency solutions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
