uWsgi中文版官网
1.搭建环境
- 创建python虚拟号环境
python -m venv venv
- 激活虚拟环境
source venv/bin/activate
(如果需要退出虚拟环境,执行:deactivate
)
- 安装flask、uwsgi
pip install uwsgi flask
2. 通过原生方式启动flask
- 创建一个应用
vim ~/myporject/app.py
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/hello')
def hello():
return jsonify({'message': 'Hello, World!'})
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000)
- 运行测试
python app.py
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://192.168.0.129:5000
Press CTRL+C to quit
127.0.0.1 - - [25/May/2023 19:24:43] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [25/May/2023 19:24:47] "GET /hello HTTP/1.1" 200 -
正常情况下会在http://127.0.0.1:5000/hello中看到{"message":"Hello, World!"}
如果是要在外网访问则需要修改服务商的安全组,在入向规则中添加5000端口
3.通过uWSGI启动flask
- 创建一个文件夹
mkdir uwsgi
- 创建uWsgi配置文件
vim uwsgi.ini
,并填充以下内容:
[uwsgi]
chdir=~/myporject
http=0.0.0.0:5000
stats=%(chdir)/uwsgi/uwsgi.status
pidfile=%(chdir)/uwsgi/uwsgi.pid
wsgi-file=%(chdir)/app.py
callable=app
processes=2
threads=2
buffer-size=65536
- 通过uWSGI启动
uwsgi --ini uwsgi.ini
服务启动后会在uwsgi文件夹中生成.pid和.status文件,其中.pid里记录了uWSGI服务的进程id,所以停止服务的指令为:
uwsgi --stop uwsgi/uwsgi.pid
- 查看uWSGI运行状态
uwsgi --connect-and-read uwsgi/uwsgi.status
4.为uWSGI添加开机自启动
- 创建启动、停止脚本
vim start.sh
#!/bin/sh
~/myproject/venv/bin/uwsgi --ini ~/myproject/uwsgi.ini
vim stop.sh
#!/bin/sh
~/myproject/venv/bin/uwsgi --stop ~/myproject/uwsgi/uwsgi.pid
chmod a+x start.sh stop.sh
(增加执行权限)
- 配置启动服务(文件名uwsgi对应的就是后续操作开启、结束服务的名字,可以自定义)
vim /etc/systemd/system/uwsgi.service
[Unit]
Description=uWSGI instance
After=network.target remote-fs.target nss-lookup.target
[Service]
ExecStart=~/myproject/run.sh
ExecStop=~/myproject/stop.sh
[Install]
WantedBy=multi-user.target
如果发现有环境变量取不到,可以添加一个环境变量文件
[Service]
EnvironmentFile=path to your env file
...
env文件格式:
key1=value1
key2=value2
- 启动服务,并开启自启动
sudo systemctl start uwsgi
sudo systemctl enable uwsgi
另一种启动服务方式
service uwsig start
每次修改启动服务的配置文件后需要执行systemctl daemon-reload
让其生效
- 其他常用指令:
停止开机自启动 : systemctl disable uwsgi
启动 uwsgi 服务 : systemctl start uwsgi
停止 uwsgi 服务 : systemctl stop uwsgi
重启 uwsgi 服务 : systemctl restart nginx
查看服务当前状态 : systemctl status uwsgi
查看所有已启动的服务 : systemctl list-units --type=service
5.其他
服务端如何配置Clash