目录
- 实现示例
- 1. 项目结构
- 2. FastAPI 应用 (app/main.py)
- 3. 依赖文件 (app/requirements.txt)
- 4. Dockerfile
- 5. Nginx 配置 (nginx/nginx.conf)
- 6. Docker Compose 配置 (docker-compose.yml)
- 使用方法
- 修改代码后更新
实现示例
接下来创建一个简单的示例项目,展示如何使用 Docker 和 Nginx 部署 FastAPI 应用,并实现代码修改后的快速更新。
1. 项目结构
fastapi_ngnix_docker/
├── app/
│ ├── main.py
│ └── requirements.txt
├── nginx/
│ └── nginx.conf
├── docker-compose.yml
└── Dockerfile
2. FastAPI 应用 (app/main.py)
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
3. 依赖文件 (app/requirements.txt)
fastapi>=0.68.0
uvicorn>=0.15.0
4. Dockerfile
FROM python:3.9
WORKDIR /app
COPY ./app/requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt
# 不复制代码,而是在运行时通过卷挂载
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
5. Nginx 配置 (nginx/nginx.conf)
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
location / {
proxy_pass http://fastapi:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
6. Docker Compose 配置 (docker-compose.yml)
version: '3'
services:
fastapi:
build: .
volumes:
- ./app:/app
ports:
- "8000:8000"
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
depends_on:
- fastapi
使用方法
- 创建上述文件结构
- 启动服务:
docker-compose up -d
- 现在您可以通过 http://localhost 访问您的 FastAPI 应用
修改代码后更新
当您修改 app/main.py
或其他 FastAPI 代码文件时:
- 由于使用了
--reload
选项和卷挂载,FastAPI 会自动检测到文件变化并重新加载 - 无需重新构建或重启容器,修改会立即生效
- 如果添加了新的依赖项,则需要重新构建容器:
docker-compose down
docker-compose up -d --build
修改前
修改后