Okay, let's create a simple FastAPI and Celery application with Docker and Docker Compose for file uploads and processing, ensuring data persistence across restarts.
Project Structure:
fastapi-celery-upload/
├── app/
│ ├── main.py # FastAPI application
│ ├── requirements.txt
│ └── Dockerfile
├── worker/
│ ├── tasks.py # Celery tasks
│ ├── requirements.txt
│ └── Dockerfile
├── redis/
│ └── Dockerfile # Optional - using official redis image, but can be useful for extension
├── docker-compose.yml
├── data/ # Directory to persist data (mounted as volume)
└── README.md
1. FastAPI Application (app/main.py):
from fastapi import FastAPI, File, UploadFile, HTTPException
from celery import Celery
from celery.result import AsyncResult
from typing import Dict
import os
app = FastAPI()
# Celery Configuration (Using environment variables for flexibility)
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", "redis://redis:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", "redis://redis:6379/0")
celery_app = Celery(
"tasks",
broker=CELERY_BROKER_URL,
backend=CELERY_RESULT_BACKEND
)
celery_app.conf.task_routes = {"worker.tasks.*": "main-queue"}
# Ensure directories for uploaded and processed files exist
UPLOAD_FOLDER = "/app/data/uploaded_files" # Inside container, mapped to ./data/uploaded_files outside
PROCESSED_FOLDER = "/app/data/processed_files" # Inside container, mapped to ./data/processed_files outside
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(PROCESSED_FOLDER, exist_ok=True)
# Celery Task (defined in worker/tasks.py - imported here for usage in FastAPI)
@celery_app.task(name="worker.tasks.process_file")
def process_file_task(filename: str):
from time import sleep
import os
print(f"Processing file: {filename}")
sleep(5) # Simulate some processing time
processed_filename = f"processed_{filename}"
upload_path = os.path.join(UPLOAD_FOLDER, filename)
processed_path = os.path.join(PROCESSED_FOLDER, processed_filename)
try:
with open(upload_path, 'r') as infile, open(processed_path, 'w') as outfile: # Simple copy example
outfile.write(f"Processed content from: {filename}\n")
outfile.write(infile.read()) # Just copying content as example. Replace with actual processing
print(f"File processed and saved as: {processed_filename}")
except Exception as e:
print(f"Error processing file {filename}: {e}")
raise e # Re-raise for Celery to handle retry if configured
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
if not file:
raise HTTPException(status_code=400, detail="No upload file sent")
file_path = os.path.join(UPLOAD_FOLDER, file.filename)
try:
with open(file_path, "wb") as f:
while contents := await file.read(1024 * 1024): # Read in chunks to avoid memory issues
f.write(contents)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error saving file: {e}")
finally:
await file.close()
task = process_file_task.delay(file.filename) # Enqueue Celery task
return {"filename": file.filename, "task_id": task.id, "message": "File uploaded and processing started."}
@app.get("/tasks/{task_id}")
async def get_task_status(task_id):
task_result = AsyncResult(task_id, app=celery_app)
result = {
"task_id": task_id,
"task_status": task_result.status,
"task_result": task_result.result
}
return result
2. FastAPI App Requirements (app/requirements.txt):
fastapi
uvicorn
celery
redis
3. FastAPI App Dockerfile (app/Dockerfile):
FROM python:3.9-slim-buster
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
4. Celery Worker Tasks (worker/tasks.py):
from celery import Celery
import os
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", "redis://redis:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", "redis://redis:6379/0")
celery_app = Celery(
"tasks",
broker=CELERY_BROKER_URL,
backend=CELERY_RESULT_BACKEND
)
celery_app.conf.task_routes = {"worker.tasks.*": "main-queue"} # Ensure tasks go to default queue
UPLOAD_FOLDER = "/app/data/uploaded_files" # Inside container, mapped to ./data/uploaded_files outside
PROCESSED_FOLDER = "/app/data/processed_files" # Inside container, mapped to ./data/processed_files outside
@celery_app.task(name="worker.tasks.process_file")
def process_file(filename: str):
from time import sleep
import os
print(f"Processing file: {filename}")
sleep(5) # Simulate some processing time
processed_filename = f"processed_{filename}"
upload_path = os.path.join(UPLOAD_FOLDER, filename)
processed_path = os.path.join(PROCESSED_FOLDER, processed_filename)
try:
with open(upload_path, 'r') as infile, open(processed_path, 'w') as outfile: # Simple copy example
outfile.write(f"Processed content from: {filename}\n")
outfile.write(infile.read()) # Just copying content as example. Replace with actual processing
print(f"File processed and saved as: {processed_filename}")
except Exception as e:
print(f"Error processing file {filename}: {e}")
raise e # Re-raise for Celery to handle retry if configured
5. Celery Worker Requirements (worker/requirements.txt):
celery
redis
6. Celery Worker Dockerfile (worker/Dockerfile):
FROM python:3.9-slim-buster
WORKDIR /worker
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["celery", "-A", "tasks", "worker", "--loglevel=INFO", "--queues=main-queue"]
7. Redis Dockerfile (redis/Dockerfile - Optional, but good practice for customization):
You can use the official Redis image directly in docker-compose.yml, but if you want to extend or customize redis config later, having a Dockerfile is useful. For now, it can be as simple as:
FROM redis:latest
# You can add custom configurations here if needed
8. Docker Compose File (docker-compose.yml):
version: "3.9"
services:
api:
build: ./app
ports:
- "8000:8000"
environment:
CELERY_BROKER_URL: redis://redis:6379/0
CELERY_RESULT_BACKEND: redis://redis:6379/0
volumes:
- data_volume:/app/data # Mount named volume to /app/data in api container
depends_on:
- redis
- worker
worker:
build: ./worker
environment:
CELERY_BROKER_URL: redis://redis:6379/0
CELERY_RESULT_BACKEND: redis://redis:6379/0
volumes:
- data_volume:/app/data # Mount same named volume to /app/data in worker container
depends_on:
- redis
redis:
image: redis:latest
ports:
- "6379:6379" # Optional: expose redis port for direct access from host if needed (e.g., redis-cli)
volumes:
- redis_data:/data # Persist redis data itself as well (optional but good practice)
volumes:
data_volume: # Named volume for file uploads and processing
redis_data: # Named volume for redis data persistence
9. README.md (Optional - for instructions):
# FastAPI + Celery File Upload and Processing Example
This is a simple example demonstrating file upload and processing using FastAPI and Celery, containerized with Docker and Docker Compose. Data persistence for uploaded and processed files is ensured using Docker volumes.
## Prerequisites
- Docker and Docker Compose installed.
## Running the Application
1. **Build and start the containers:**
```bash
docker-compose up --build
-
Access the FastAPI application:
Open your browser or use a tool like curl or Postman to access the API at http://localhost:8000.
-
Upload a file:
Use a tool like curl or Postman to send a POST request to http://localhost:8000/uploadfile/ with a file in the files field. For example using curl:
curl -X POST -F "file=@./your_file.txt" http://localhost:8000/uploadfile/
Replace ./your_file.txt with the path to your file.
-
Check task status (optional):
The upload endpoint returns a task_id. You can use this task_id to check the task status at http://localhost:8000/tasks/{task_id}.
-
Data Persistence:
Uploaded files and processed files are stored in the data/uploaded_files and data/processed_files directories respectively. This data will persist even if you stop and restart the containers using docker-compose down and docker-compose up.
Stopping the Application
docker-compose down
Notes:
- File Processing: The
process_file_task in worker/tasks.py currently performs a very basic operation (simulating processing and copying content). You should replace this with your actual file processing logic.
- Error Handling: Basic error handling is included, but you should enhance it for production environments.
- Scaling: For scaling, you can easily increase the number of worker instances in your
docker-compose.yml.
- Queues: This example uses a default Celery queue named
main-queue. You can configure and manage multiple queues as needed.
- Environment Variables: Configuration for Redis connection is done using environment variables, making it more flexible.
- Volumes: The
data_volume and redis_data in docker-compose.yml are named volumes. Docker manages these volumes and their lifecycle. Data within these volumes will persist across container restarts.
**How to Run:**
1. **Create the project directory** `fastapi-celery-upload` and all the subdirectories and files as structured above.
2. **Put your code** (copy and paste the code snippets into the respective files).
3. **Build and run the containers:** Open your terminal, navigate to the `fastapi-celery-upload` directory (where `docker-compose.yml` is located), and run:
```bash
docker-compose up --build
-
Test the application:
- Access FastAPI at
http://localhost:8000 in your browser or using a tool like Postman or curl.
- Try uploading a file to the
/uploadfile/ endpoint using a POST request with multipart/form-data and the file in the files field.
- Check the task status at
/tasks/{task_id} (using the task_id returned after uploading).
- Verify that uploaded files are saved in
data/uploaded_files and processed files are in data/processed_files.
-
Stop and restart: Run docker-compose down and then docker-compose up. Check that the files you uploaded previously are still in the data directory.
Explanation of Data Persistence:
- Docker Volumes: We use Docker volumes (
data_volume and redis_data defined in docker-compose.yml).
- Mounting Volumes: These named volumes are mounted to specific directories inside the containers (
/app/data in api and worker, and /data in redis).
- Persistence: When containers are stopped or restarted, Docker volumes persist independently of the container lifecycle. Data written to the mounted directories within the containers is actually stored in the Docker volume, and it will be available when the containers are restarted and the volumes are re-mounted.
data/ directory: The data/ directory at the root of your project (fastapi-celery-upload/data/) is where Docker will store the content of the data_volume. You can check this directory to see your uploaded and processed files after running the application.
This setup provides a basic but functional FastAPI + Celery application with file upload, background processing, Docker containerization, and most importantly, data persistence using Docker volumes, ensuring you don't lose your uploaded and processed data when containers restart. Remember to adapt the file processing logic in worker/tasks.py to your actual requirements.