27.FastAPI应用生产环境部署

当基于FastAPI的应用程序或者微服务代码编写完成后,可以部署到生产环境下运行。我们在开发、调试过程中采用命令行启动用的是 uvicorn ,在生产环境下,应该使用进程管理器 gunicorn。 Gunicorn 是一个unix上被广泛使用的高性能的Python WSGI UNIX HTTP Server,和大多数的web框架兼容,并具有实现简单,轻量级,高性能等特点。

1.安装Gunicorn

pip install gunicorn

查看帮助

gunicorn -h 

2.以命令行方式启动应用

gunicorn main:app -b 0.0.0.0:8899 -w 4 -k uvicorn.workers.UvicornWorker --daemon 

获取Gunicorn进程树

pstree -ap | grep gunicorn

终止Gunicorn任务

kill -HUP 1090

3.以配置文件方式启动应用

编辑gunicorn.conf 文件,其内容如下:

import multiprocessing
​
# 并行工作进程数 核心数*2+1个
workers = multiprocessing.cpu_count() * 2 + 1 
# 指定每个工作者的线程数
threads = 2
# 监听内网端口5000
bind = '127.0.0.1:5000'
# 设置守护进程
daemon = 'true'
# 工作模式协程
worker_class = 'gevent'
# 设置最大并发量
worker_connections = 2000
# 设置进程文件目录
pidfile = '/var/run/gunicorn.pid'
# 设置访问日志和错误信息日志路径
accesslog = '/var/log/gunicorn_access.log'
errorlog = '/var/log/gunicorn_error.log'
# 日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
loglevel = 'warning'

启动应用:

gunicorn -c gunicorn.conf main:app

4.nginx

如果需要使用nginx代理对应的api,对应的配置内容类似于:

    location /fastapi/ {
        proxy_pass http://fastapi_host/fastapi/;
    }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐