FastAPI环境部署

2021-11-09  本文已影响0人  还是那个没头脑

测试环境

pip install uvicorn
uvicorn main:app --host 0.0.0.0 --port 80 --reload
if __name__ == '__main__':
    uvicorn.run(
        app='main:app',
        host="0.0.0.0",
        port=8899,
        workers=4,
        reload=True,
        debug=True)
uvicorn --help
Usage: uvicorn [OPTIONS] APP

Options:
  --host TEXT                     Bind socket to this host.  [default:
                                  127.0.0.1]
  --port INTEGER                  Bind socket to this port.  [default: 8000]
  --uds TEXT                      Bind to a UNIX domain socket.
  --fd INTEGER                    Bind to socket from this file descriptor.
  --reload                        Enable auto-reload.
  --reload-dir TEXT               Set reload directories explicitly, instead
                                  of using the current working directory.
  --reload-delay FLOAT            Delay between previous and next check if
                                  application needs to be. Defaults to 0.25s.
                                  [default: 0.25]
  --workers INTEGER               Number of worker processes. Defaults to the
                                  $WEB_CONCURRENCY environment variable if
                                  available, or 1. Not valid with --reload.
  --loop [auto|asyncio|uvloop]    Event loop implementation.  [default: auto]
  --http [auto|h11|httptools]     HTTP protocol implementation.  [default:
                                  auto]
  --ws [auto|none|websockets|wsproto]
                                  WebSocket protocol implementation.
                                  [default: auto]
  --ws-max-size INTEGER           WebSocket max size message in bytes
                                  [default: 16777216]
  --lifespan [auto|on|off]        Lifespan implementation.  [default: auto]
  --interface [auto|asgi3|asgi2|wsgi]
                                  Select ASGI3, ASGI2, or WSGI as the
                                  application interface.  [default: auto]
  --env-file PATH                 Environment configuration file.
  --log-config PATH               Logging configuration file. Supported
                                  formats: .ini, .json, .yaml.
  --log-level [critical|error|warning|info|debug|trace]
                                  Log level. [default: info]
  --access-log / --no-access-log  Enable/Disable access log.
  --use-colors / --no-use-colors  Enable/Disable colorized logging.
  --proxy-headers / --no-proxy-headers
                                  Enable/Disable X-Forwarded-Proto,
                                  X-Forwarded-For, X-Forwarded-Port to
                                  populate remote address info.
  --forwarded-allow-ips TEXT      Comma seperated list of IPs to trust with
                                  proxy headers. Defaults to the
                                  $FORWARDED_ALLOW_IPS environment variable if
                                  available, or '127.0.0.1'.
  --root-path TEXT                Set the ASGI 'root_path' for applications
                                  submounted below a given URL path.
  --limit-concurrency INTEGER     Maximum number of concurrent connections or
                                  tasks to allow, before issuing HTTP 503
                                  responses.
  --backlog INTEGER               Maximum number of connections to hold in
                                  backlog
  --limit-max-requests INTEGER    Maximum number of requests to service before
                                  terminating the process.
  --timeout-keep-alive INTEGER    Close Keep-Alive connections if no new data
                                  is received within this timeout.  [default:
                                  5]
  --ssl-keyfile TEXT              SSL key file
  --ssl-certfile TEXT             SSL certificate file
  --ssl-keyfile-password TEXT     SSL keyfile password
  --ssl-version INTEGER           SSL version to use (see stdlib ssl module's)
                                  [default: 2]
  --ssl-cert-reqs INTEGER         Whether client certificate is required (see
                                  stdlib ssl module's)  [default: 0]
  --ssl-ca-certs TEXT             CA certificates file
  --ssl-ciphers TEXT              Ciphers to use (see stdlib ssl module's)
                                  [default: TLSv1]
  --header TEXT                   Specify custom default HTTP response headers
                                  as a Name:Value pair
  --version                       Display the uvicorn version and exit.
  --app-dir TEXT                  Look for APP in the specified directory, by
                                  adding this to the PYTHONPATH. Defaults to
                                  the current working directory.  [default: .]
  --factory                       Treat APP as an application factory, i.e. a
                                  () -> <ASGI app> callable.  [default: False]
  --help                          Show this message and exit.

生产环境

pip install gunicorn
pip install uvloop
pip install httptools

查看使用的命令

gunicorn -h 

Gunicorn 是成熟的,功能齐全的服务器,Uvicorn 内部包含有 Guicorn 的 workers 类,允许你运行 ASGI 应用程序,这些 workers 继承了所有 Uvicorn 高性能的特点。

使用 Guicorn 来进行进程管理,我们可以动态增加或减少进程数量,平滑地重启工作进程,或者升级服务器而无需停机。

在生产环境中,Guicorn 大概是最简单的方式来管理 Uvicorn 了,生产环境部署我们推荐使用 Guicorn 和 Uvicorn 的 worker 类

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

获取Gunicorn进程树

pstree -ap|grep gunicorn

重启Gunicorn任务

kill -HUP 30080

gunicorn的参数详解

-c CONFIG    : CONFIG,配置文件的路径,通过配置文件启动;生产环境使用;

-b ADDRESS   : ADDRESS,ip加端口,绑定运行的主机;

-w INT, --workers INT:用于处理工作进程的数量,为正整数,默认为1;

-k STRTING, --worker-class STRTING:要使用的工作模式,默认为sync异步,可以下载eventlet和gevent并指定

--threads INT:处理请求的工作线程数,使用指定数量的线程运行每个worker。为正整数,默认为1。

--worker-connections INT:最大客户端并发数量,默认情况下这个值为1000。

--backlog int:未连接的最大数量,即等待服务的客户的数量。默认2048个,一般不修改;

-p FILE, --pid FILE:设置pid文件的文件名,如果不设置将不会创建pid文件


--access-logfile FILE   :  要写入的访问日志目录

--access-logformat STRING:要写入的访问日志格式

--error-logfile FILE, --log-file FILE  :  要写入错误日志的文件目录。

--log-level LEVEL   :   错误日志输出等级。


--limit-request-line INT   :  HTTP请求头的行数的最大大小,此参数用于限制HTTP请求行的允许大小,默认情况下,这个值为4094。值是0~8190的数字。

--limit-request-fields INT   :  限制HTTP请求中请求头字段的数量。此字段用于限制请求头字段的数量以防止DDOS攻击,默认情况下,这个值为100,这个值不能超过32768

--limit-request-field-size INT  :  限制HTTP请求中请求头的大小,默认情况下这个值为8190字节。值是一个整数或者0,当该值为0时,表示将对请求头大小不做限制


-t INT, --timeout INT:超过这么多秒后工作将被杀掉,并重新启动。一般设定为30秒;

--daemon,-D: 是否以守护进程启动,默认false;

--chdir: 在加载应用程序之前切换目录;

--graceful-timeout INT:默认情况下,这个值为30,在超时(从接收到重启信号开始)之后仍然活着的工作将被强行杀死;一般使用默认;

--keep-alive INT:在keep-alive连接上等待请求的秒数,默认情况下值为2。一般设定在1~5秒之间。

--reload:默认为False。此设置用于开发,每当应用程序发生更改时,都会导致工作重新启动。

--spew:打印服务器执行过的每一条语句,默认False。此选择为原子性的,即要么全部打印,要么全部不打印;

--check-config   :显示现在的配置,默认值为False,即显示。

-e ENV, --env ENV: 设置环境变量;
import multiprocessing

# 并行工作进程数(multiprocessing.cpu_count()线程数,官方说可以有:核心数*2+1个)
workers = multiprocessing.cpu_count() * 2 + 1 
# 指定每个工作者的线程数
threads = 2
# 监听内网端口5000
bind = '127.0.0.1:5000'
# 设置守护进程,推荐将进程交给supervisor管理(以守护进程形式来运行Gunicorn进程,true其实就是将这个服务放到后台去运行,故此处设置false,交给supervisor开守护进程,因为supervisor不支持后台进程)
daemon = 'false'
# 工作模式协程
worker_class = 'gevent'
# 设置最大并发量
worker_connections = 2000
# 设置进程文件目录
pidfile = '/var/run/gunicorn.pid'
# 设置访问日志和错误信息日志路径
accesslog = '/var/log/gunicorn_acess.log'
errorlog = '/var/log/gunicorn_error.log'
# 日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
loglevel = 'warning'

启动unicorn

gunicorn -c gunicorn.conf main:app

用于管理gunicorn,将其当作自己的子进程启动;当gunicorn由于异常等停止运行后,supervisor可以自动重启gunicorn

supervisor为c/s架构,supervisord 是服务端,supervisorctl 是客户端

supervisord启动成功后,可以通过supervisorctl客户端控制进程,启动、停止、重启

supervisor_gunicorn.ini

[program:supervisor-gunicorn]  
user = root
directory = /root/gunicorn_demo/
command = /usr/local/python3/bin/gunicorn main:app -b 0.0.0.0:8899 -w 4 -k uvicorn.workers.UvicornWorker
autostart = true
startsecs = 10
redirect_stderr = true
stdout_logfile = /var/log/supervisor_gunicorn.log

更详细参数部署可参考 Supervisord安装和配置

参考文档:
https://www.uvicorn.org/deployment/#gunicorn
https://www.cnblogs.com/mazhiyong/p/13384785.html
https://www.cnblogs.com/shijingjing07/p/9110619.html

上一篇 下一篇

猜你喜欢

热点阅读