Centos8 Nginx + uwsgi + Flask 搭建web服务

代码

test.py

from flask import Flask


app = Flask(__name__)
@app.route("/")
def test():
    return "hello world"


if __name__ == "__main__":
    flag = 1
    app.run(host="0.0.0.0", port=5000, debug=True)

Flask

首先安装python 安装教程
安装虚拟环境 自行建立软连接

pip install virtualenv -i https://pypi.tuna.tsinghua.edu.cn/simple

在代码所在目录创建虚拟环境.env

virtualenv -p python .env

安装flask

pip install flask -i https://pypi.tuna.tsinghua.edu.cn/simple

使用python启动test.py

python test.py

运行结果
image

测试是否代码是否正常运行

查看自己的ip

ifconfig

image
我的ip是192.168.1.43 代码里占用的端口是5000 用浏览器去访问
image

uwsgi

安装uwsgi 自行建立软连接

pip install uwsgi -i https://pypi.tuna.tsinghua.edu.cn/simple

在当前目录建立uwsgi.ini

vim uwsgi.ini

填入

[uwsgi]
chdir=/home/czl/uwsgi_test
home=/home/czl/uwsgi_test/.env
module=test
callable=app
master=true
processes=2
chmod-socket=666
logfile-chmod=644
procname-prefix-spaced=mysite
http=0.0.0.0:5000

vacuum=true
socket=%(chdir)/uwsgi.sock
stats=%(chdir)/uwsgi.status
pidfile=%(chdir)/uwsgi.pid
daemonize=%(chdir)/uwsgi.log

这个文件不能写注释,chdir和home换成自己的目录,module填入app所在py文件名,不用加.py,callable必须填application的变量名,如 app = Flask(name),那么callable德填app,其他照写就行

启动 uwsgi

uwsgi --ini uwsgi.ini

image
查看是否启动成功,查看占用5000端口的进程

lsof -i:5000

image
像上面这样就启动成功了,若失败就去当前目录下单uwsgi.log,查看错误原因
使用浏览器访问
image
这个只是测试,记得把该应用关掉,使用下面的命令关掉该web服务

kill -9 `lsof -i:5000`

nginx

启动uwsgi socket服务

将uwsgi.ini的http改成socket

[uwsgi]
chdir=/home/czl/uwsgi_test
home=/home/czl/uwsgi_test/.env
module=test
callable=app
master=true
processes=2
chmod-socket=666
logfile-chmod=644
procname-prefix-spaced=mysite
socket=0.0.0.0:5000

vacuum=true
socket=%(chdir)/uwsgi.sock
stats=%(chdir)/uwsgi.status
pidfile=%(chdir)/uwsgi.pid
daemonize=%(chdir)/uwsgi.log

然后用uwsgi --ini uwsgi.ini启动
这个是socket服务,不是http,不能直接用浏览器访问,必须有Nginx转发

下载安装Nginx
Centos8安装nginx比较简单

sudo yum install nginx

开放nginx

sudo systemctl enable nginx

配置nginx.conf

vim /etc/nginx/nginx.conf

将 location /{} 改成下面所示

location / {

	include uwsgi_params;
	uwsgi_pass 127.0.0.1:5000;
}

启动Nginx

sudo systemctl start nginx

如果有报错查看错误日志 /var/log/nginx/error.log
到这里就完成了
使用浏览器访问 ip地址,不用加端口号

posted @ 2022-09-15 18:15  乘舟凉  阅读(157)  评论(0编辑  收藏  举报