uvicorn 框架软件编写后发布至ubuntu服务器
Published in:2023-06-20 |
Words: 763 | Reading time: 3min | reading:

uvicorn 框架软件编写后发布至ubuntu服务器

uvicorn安装使用

  • 1.安装
    1
    pip install uvicorn
  • 2.main.py编写
    1
    2
    3
    4
    5
    6
    7
    8
    from fastapi import FastApi

    app = FastApi()


    @app.get('/hello')
    async def hello():
    return {'message': 'hello World'}
  • 3.开发环境运行
    1
    2
    if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8000, log_level="info")

发布环境部署

  • 1.gunicorn安装
    1
    2
    pip install uvicorn
    pip install gunicorn
  • 2.gunicorn.py配置文件编写
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    import os

    # 设置守护进程
    daemon=True
    # 监听内网端口8000
    bind='0.0.0.0:8000'
    # 设置进程文件目录
    pidfile='./gunicorn.pid'
    chdir='./' # 工作目录
    # 工作模式
    worker_class='uvicorn.workers.UvicornWorker'
    # 并行工作进程数 核心数*2+1个
    workers=3 #multiprocessing.cpu_count()+1
    # 指定每个工作者的线程数
    threads=2
    # 设置最大并发量
    worker_connections = 2000
    loglevel='debug' # 错误日志的日志级别
    access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
    # 设置访问日志和错误信息日志路径
    log_dir = "./log"
    if not os.path.exists(log_dir):
    os.makedirs(log_dir)
    accesslog = "./log/gunicorn_access.log"
    errorlog = "./log/gunicorn_error.log"
  • 3.py文件特殊处理
    1
    2
    3
    4
    5
    6
    # 导入OS模块
    import os
    import sys

    # 把当前文件所在文件夹的父文件夹路径加入到PYTHONPATH
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  • 4.服务器运行
    1
    gunicorn main:app -c gunicorn.py

    抑或

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

项目停止运行

  • 1.获取gunicorn进程树
    1
    pstree -ap | grep gunicorn
  • 2.终止gunicorn任务

kill -HUP 进程pid

  • 3.如果使用了多进程,那么执行了上述命令后还会有子进程在运行,可以使用如下命令杀死
    1
    kill -9 进程pid

进程脚本杀死

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash

# 查找 gunicorn 主进程 PID
gunicorn_pid=$(ps aux | grep 'gunicorn' | grep -v 'grep' | awk '{print $2}')

# 如果找到了主进程 PID
if [ -n "$gunicorn_pid" ]; then
echo "Found gunicorn process: $gunicorn_pid"

# 给主进程发 SIGINT 信号,请求正常停止进程
kill -INT $gunicorn_pid

# 睡眠 5 秒等待主进程结束
sleep 5

# 查找所有 gunicorn 子进程 PID
gunicorn_child_pids=$(pstree -p $gunicorn_pid | grep -oP '([0-9]+)(?=\))')

# 如果找到了子进程 PID
if [ -n "$gunicorn_child_pids" ]; then
echo "Found gunicorn child processes: $gunicorn_child_pids"

# 杀死所有子进程
for pid in $gunicorn_child_pids; do
kill -9 $pid
done
fi

echo "Stopped gunicorn process and child processes"

else
echo "No running gunicorn process found"
fi
  • 脚本执行
    1
    2
    chmod 777 stop_gunicorn.sh
    bash stop_gunicorn.sh

配置开机自启动服务

配置 gunicorn.service服务开机自启动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
cat >/usr/lib/systemd/system/gunicorn.service << EOF
[Unit]
Description=Gunicorn fast
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/var/run/gunicorn.pid
ExecStart=/root/.local/share/virtualenvs/fastapi-Xq8atoqR/bin/gunicorn -c
/opt/web/fastapi/gunicorn.py main:app
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

EOF

依次执行下面命令

1
2
3
systemctl daemon-reload
systemctl enable gunicorn
systemctl start gunicorn

查看服务状态

1
systemctl status gunicorn

Nginx代理配置

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
# listen 443 ssl;
server_name api.hmily.vip;
access_log /var/log/nginx/access.log;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
}
}

nginx配置生效

1
nginx -s reload

See

Prev:
使用python 链接 ADCS FTP 服务批量下载和上传文件
Next:
Zuul + Oauth 2 实现鉴权功能