fastapi: 用gunicorn管理进程

一,安装第三方库

用pip从命令行安装

$ pip install gunicorn gevent 

测试安装效果:

(venv) [sysop@blog fast_scaf2]$ gunicorn --version
gunicorn (version 27.0.1)
(venv) [sysop@blog fast_scaf2]$ whereis gunicorn
gunicorn: /opt/project/fast_scaf2/venv/bin/gunicorn
(venv) [sysop@blog fast_scaf2]$ ./venv/bin/gunicorn --version
gunicorn (version 27.0.1)

二,配置gunicorn

创建日志目录:

# mkdir /data/logs/pythonlogs
# chmod 777 /data/logs/pythonlogs  

新建配置文件:

bind = "127.0.0.1:8001"
workers = 4
worker_class = "uvicorn.workers.UvicornWorker"
loglevel = "info"
accesslog = "/data/logs/pythonlogs/gunicorn_access.log"
errorlog = "/data/logs/pythonlogs/gunicorn_error.log"
daemon = False

测试运行命令:不是以daemon方式,会占用终端

$ /opt/project/fast_scaf2/venv/bin/gunicorn -c /opt/project/fast_scaf2/gunicorn.conf.py app.main:app

查看端口是否已守护:

# ss -lntp | grep 8001
LISTEN   0         1024              127.0.0.1:8001             0.0.0.0:*        users:(("gunicorn",pid=16923,fd=5),("gunicorn",pid=16922,fd=5),("gunicorn",pid=16921,fd=5),("gunicorn",pid=16920,fd=5),("gunicorn",pid=16919,fd=5))

三,用systemctl管理服务

创建服务用到的service文件:

[root@blog conf.d]# vi /etc/systemd/system/fast_scaf2.service
[root@blog conf.d]# systemctl daemon-reload 

文件内容:

[Unit]
Description=fast_scaf2 Daemon
After=network.target

[Service]
User=root
WorkingDirectory=/opt/project/fast_scaf2
ExecStart=/opt/project/fast_scaf2/venv/bin/gunicorn -c /opt/project/fast_scaf2/gunicorn.conf.py app.main:app
Restart=always

[Install]
WantedBy=multi-user.target

启动后查看状态:

[root@blog conf.d]# systemctl start fast_scaf2.service
[root@blog conf.d]# systemctl status fast_scaf2.service
● fast_scaf2.service - fast_scaf2 Daemon
   Loaded: loaded (/etc/systemd/system/fast_scaf2.service; disabled; vendor preset: disabled)
   Active: active (running) since Thu 2026-11-19 19:21:26 CST; 1s ago
 Main PID: 17105 (gunicorn)
    Tasks: 1 (limit: 26213)
   Memory: 18.9M
   CGroup: /system.slice/fast_scaf2.service
           └─17105 /opt/project/fast_scaf2/venv/bin/python3 /opt/project/fast_scaf2/venv/bin/gunicorn -c /opt/project/fast_scaf2/gunicorn.conf.py app.main:app

Nov 19 19:21:26 blog systemd[1]: Started fast_scaf2 Daemon.

 

posted @ 2026-11-19 19:30  刘宏缔的架构森林  阅读(4)  评论(0)    收藏  举报