服务器为cenos
工具安装:
- flask python 的服务器框架
- gunicorn webservice,WSGI 的容器
- supervisor 进程管理工具
- nginx 一个高性能的 web 服务器
- 在/home/xxhong目录下创建一个目录,起名img2txt,代码都会放到这个目录
- 安装python3.6
yum install python36
- 安装 virtualenv
sudo pip3.6 install virtualenv
- 进到img2txt目录,创建虚拟环境
virtualenv venv
- 激活虚拟环境
source venv/bin/activate
- 安装 flask 框架
pip3.6 install flask
- 我们在img2txt目录写个Hello World用来测试,取名hello.py,代码如下
app = Flask(__name__)
@app.route('/')
def hello_world():
# return render_template('index.html')
return "Hello World"
if __name__ == '__main__':
app.run()
- 安装 gunicorn
pip3.6 install gunicorn
9.测试我们刚才的代码,输入以下命令,然后访问自己服务器的外网ip地址
gunicorn -w 4 -b 0.0.0.0:8888 hello:app
可以看到浏览器中显示出Hello World image.png
参数解析
此时我们使用8888端口进行访问,-w 表示开启了多少个 worker, -b 表示访问地址。hello 就是 hello.py 的文件名,hello.py 相当于一个库文件被 gunicorn 调用。app 则是 hello.py 里创建的 app,这样 gunicorn 才可以定位 flask 应用。
想结束 gunicorn 可以通过执行 pkill gunicorn,有时还要找到 pid 才能 kill 掉。这样的操作过于繁琐,所以我们使用另一个神器 supervisor, 用来专门管理系统的进程。 - 安装 supervisor
注意:由于supervisor不支持3.X的python版本,我直接退出虚拟环境使用以下命令安装
yum install supervisor
退出虚拟环境的命令是:
deactivate
- 安装完成后直接打开配置文件
vim /etc/supervisord.conf
- 在配置文件中添加当前项目的配置参数
[program:hello]
command=/home/xxhong/img2txt/venv/bin/gunicorn -w4 -b 0.0.0.0:8888 hello:app ; supervisor启动命令
directory=/home/xxhong/img2txt ; 项目的文件夹路径
startsecs=0 ; 启动时间
stopwaitsecs=0 ; 终止等待时间
autostart=false ; 是否自动启动
autorestart=false ; 是否自动重启
stdout_logfile=/var/www/server/log/gunicorn.log ;log 日志
stderr_logfile=var/www/server/log/gunicorn.err
- 测试supervisor
supervisord -c /etc/supervisord.conf
supervisorctl start hello
// 这里的hello是program的名字
再补几个常用命令:
supervisorctl status
supervisorctl stop hello
supervisorctl start hello
supervisorctl restart hello
supervisorctl reread
supervisorctl update
如果出现以下错误
Starting supervisor: Error: Another program is already listening on a port that one of our HTTP servers is configured to use. Shut this program down first before starting supervisord.
For help, use /usr/bin/supervisord -h
解决方法:
先ps -ef | grep supervisord
然后使用kill -s SIGTERM 3999
杀掉进程中有/usr/bin/python /usr/bin/supervisord的一个
- 安装 nginx
nginx 是一个高性能的 HTTP 和 反向代理服务器,在高并发方面表现非常不错。
安装命令:
yum install nginx
nginx相关命令
service nginx start #启动 nginx 服务
service nginx stop #停止 nginx 服务
service nginx restart #重启 nginx 服务
nginx配置文件
vim /etc/nginx/ nginx.conf
直接在location 下添加如下代码就可以了
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
教程完毕, 有问题留言
网友评论