FastAPI在 Nginx 和 Docker 环境中的部署

实现示例

接下来创建一个简单的示例项目,展示如何使用 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

使用方法

  1. 创建上述文件结构
  2. 启动服务:
docker-compose up -d
  1. 现在您可以通过 http://localhost 访问您的 FastAPI 应用

修改代码后更新

当您修改 app/main.py 或其他 FastAPI 代码文件时:

  1. 由于使用了 --reload 选项和卷挂载,FastAPI 会自动检测到文件变化并重新加载
  2. 无需重新构建或重启容器,修改会立即生效
  3. 如果添加了新的依赖项,则需要重新构建容器:
docker-compose down
docker-compose up -d --build

修改前
在这里插入图片描述
修改后
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值