美文网首页
flask 项目部署

flask 项目部署

作者: 全村滴希望 | 来源:发表于2019-02-23 10:49 被阅读0次

部署flask项目

centos

1.卸载mysql

yum方式安装的mysql

yum remove mysql mysql-server mysql-libs compat-mysql51
rm -rf /var/lib/mysql
rm /etc/my.cnf

查看是否还有mysql软件:

rpm -qa|grep mysql

如果存在的话,继续删除即可。

2.安装mysql

下载mysql的repo源,安装mysql5.7.20,用yum安装

cd /usr/local/src/
wget http://repo.mysql.com/mysql57-community-release-el7-8.noarch.rpm 
rpm -ivh mysql57-community-release-el7-8.noarch.rpm 
yum -y install mysql-server 

默认配置文件路径:
配置文件:/etc/my.cnf
日志文件:/var/log/mysqld.log
服务启动脚本:/usr/lib/systemd/system/mysqld.service

配置 my.cnf

vim /etc/my.cnf

加入

server_id = 1

expire_logs_days = 3

3. 启动mysql服务

service mysqld restart

重置密码

mysql -u root -p

此时提示要输入默认的密码,查看默认的密码命令如下:

grep "password" /var/log/mysqld.log

A temporary password is generated for root@localhost: voTmakYSE6&L
Access denied for user '-root'@'localhost' (using password: NO)

可以看到密码为:voTmakYSE6&L

修改密码

mysql> set password = password('your new password');
mysql> alter user 'root'@'localhost' password expire never;
mysql> flush privileges;
如果出现如下错误
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
表示密码太过简单,更改密码强度即可。
mysql5.7更改如下:
set global validate_password_policy=0;
set global validate_password_length=1;
mysql8.0更改如下:
set global validate_password.policy=0;
set global validate_password.length=1;
如果出现如下错误
# mysql -h172.16.4.5 -uroot -p
Enter password: 
ERROR 2059 (HY000): Authentication plugin 'caching_sha2_password' cannot be loaded: /usr/lib64/mysql/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory

出现这个原因是mysql8 之前的版本中加密规则是mysql_native_password,而在mysql8之后,加密规则是caching_sha2_password, 解决问题方法有两种,一种是升级navicat驱动,一种是把mysql用户登录密码加密规则还原成mysql_native_password. 
这里用第二种方式

1.进入mysql容器

docker exec -it mysql2 /bin/bash

2.进入mysql

mysql -uroot -pmima

3.修改密码

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
grant all on *.* to 'root'@'%';

修改编码 vim /etc/my.cnf 加入

[client]

default-character-set = utf8

[mysqld]

default-storage-engine = INNODB

character-set-server = utf8

collation-server = utf8_general_ci #不区分大小写

collation-server = utf8_bin #区分大小写

collation-server = utf8_unicode_ci #比 utf8_general_ci 更准确

创建数据库

mysql> CREATE DATABASE datebasename CHARACTER SET utf8;

开启数据库远程访问权限(否则会报程序错误)

use mysql;
select t.host from user t where t.user='root'

看到如下所示则说明数据库没有开启用户远程访问

+--------------+
| host |
+--------------+
| localhost |
+--------------+

将localhost替换为%即可

update user set host='%' where host='localhost';

python3,pip

CentOS 7 默认安装了 Python 2,当需要使用 Python 3 的时候,可以手动下载 Python 源码后编译安装。

安装python 3

yum install -y openssl-devel
yum install -y libffi-devel
sudo mkdir /usr/local/python3 # 创建安装目录
wget --no-check-certificate https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz # 下载 Python 源文件 
# 注意:wget获取https的时候要加上:--no-check-certifica
tar -xzvf Python-3.6.2.tgz # 解压缩包
cd Python-3.6.2 # 进入解压目录
sudo ./configure --prefix=/usr/local/python3  --with-ssl # 指定创建的目录
sudo make
sudo make install # 编译安装

执行./configure时可能会报错,configure: error: no acceptable C compiler found in $PATH,这是因为未安装合适的编译器,安装下就好了,

sudo yum install gcc-c++
(使用sudo yum install gcc-c++时会自动安装/升级gcc及其他依赖的包。)

配置两个版本共存

创建python3的软链接:

sudo ln -s /usr/local/python3/bin/python3 /usr/bin/python3

这样就可以通过 python 命令使用Python2, python3 来使用Python3

安装pip

sudo yum -y install epel-release # 首先安装 epel 扩展源
sudo yum -y install python-pip # 安装 python-pip
sudo yum clean all # 清除 cache

安装虚拟环境

virtualenv

pip install virtualenv

建立python虚拟环境

virtualenv venv
source venv/bin/activate
# 推出虚拟环境使用 deactivate

根据requirements.txt文件安装依赖包

pip3 install -r requirements.txt

requirements.txt文件如下

Flask==1.0.2
Flask-Script==2.0.6
Flask-SQLAlchemy==2.3.2
PyMySQL==0.9.3
gunicorn==19.7.1

如果在安装requirements.txt出现以下错误

Collecting Flask-Script==2.0.6 (from -r requirements.txt (line 3))
  Using cached https://files.pythonhosted.org/packages/00/a4/cd587b2b19f043b65bf33ceda2f6e4e6cdbd0ce18d01a52b9559781b1da6/Flask-Script-2.0.6.tar.gz
    ERROR: Command errored out with exit status 1:
     command: /usr/local/python3Dir/bin/python3.8 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-kkgr2xye/Flask-Script/setup.py'"'"'; __file__='"'"'/tmp/pip-install-kkgr2xye/Flask-Script/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info
         cwd: /tmp/pip-install-kkgr2xye/Flask-Script/
    Complete output (11 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/usr/local/python3Dir/lib/python3.8/site-packages/setuptools/__init__.py", line 20, in <module>
        from setuptools.dist import Distribution, Feature
      File "/usr/local/python3Dir/lib/python3.8/site-packages/setuptools/dist.py", line 35, in <module>
        from setuptools import windows_support
      File "/usr/local/python3Dir/lib/python3.8/site-packages/setuptools/windows_support.py", line 2, in <module>
        import ctypes
      File "/usr/local/python3Dir/lib/python3.8/ctypes/__init__.py", line 7, in <module>
        from _ctypes import Union, Structure, Array
    ModuleNotFoundError: No module named '_ctypes'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Python3中有个内置模块叫ctypes,它是Python3的外部函数库模块,它提供兼容C语言的数据类型,并通过它调用Linux系统下的共享库(Shared library),此模块需要使用CentOS7系统中外部函数库(Foreign function library)的开发链接库(头文件和链接库)。
由于在CentOS7系统中没有安装外部函数库(libffi)的开发链接库软件包,所以在安装pip的时候就报了"ModuleNotFoundError: No module named '_ctypes'"的错误。

解决办法:
使用yum install命令安装libffi-devel,然后使用make&make install 命令重新编译并安装python

在虚拟环境中安装gunicorn

pip install gunicorn

在项目目录中启动程序

gunicorn -w 5 -b 127.0.0.1:5000 manage:app -D

在服务器上安装nginx

yum install -y epel-release
yum install -y nginx

找到nginx配置文件并作修改

find / -name nginx.conf
vim nginx.conf

修改内容如下

server {                                                                        
    listen       80 default_server;                                             
    #listen       [::]:80 default_server;                                       
    server_name  202.201.1.20;                                                  
    index index.html index.htm index.php;                                       
    access_log /var/log/nginx/cccc_access.log;                                  
    error_log /var/log/nginx/cccc_error.log;                                    
    #root         /usr/share/nginx/html;                                        
                                                                               
    # Load configuration files for the default server block.                    
    include /etc/nginx/default.d/*.conf;                                        
                                                                               
    location / {                                                                
            proxy_pass http://127.0.0.1:5000;                                   
            proxy_redirect     off;                                             
            proxy_set_header   Host                 $http_host;                 
            proxy_set_header   X-Real-IP            $remote_addr;               
            proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for; 
            proxy_set_header   X-Forwarded-Proto    $scheme;                    
    }                                                                           
                                                                                
     #需要不然项目中的图片无法正常加载                                                          
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {                            
             proxy_pass  http://0.0.0.0:5000;                                   
             expires 30d;                                                       
    }                                                                           
    #需要不然项目中的js|css无法正常加载                                                       
    location ~ .*\.(js|css)?$ {                                                 
            proxy_pass http://0.0.0.0:5000;                                     
            expires 15d;                                                        
    }                                                                           
                                                                                
    error_page 404 /404.html;                                                   
        location = /40x.html {                                                  
    }
}

启动nginx

nginx
service nginx start

停止nginx

service nginx stop

重启nginx

service nginx restart

nginx配置文件检查

nginx -t

重新加载nginx配置

nginx -s reload

如果重载不了执行下面的命令后再重载

nginx -c /etc/nginx/nginx.conf

此时即可在浏览器访问ip地址

如果访问出现

The server encountered an internal error or misconfiguration and was unable to complete your request.

查看nginx日志(/var/log/nginx/cccc_error.log)显示

connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to upstream,

需要执行如下代码

setsebool -P httpd_can_network_connect 1

项目更改后的重新部署

需要重启gunicorn:首先找到gunicorn的进程号

pstree -ap|grep gunicorn

根据找到的主进程号,重启gunicorn:

kill -HUP *****

也可以kill主进程后,用下面的命令重新部署

gunicorn -w 5 -b 127.0.0.1:5000 manage:app -D

使用定时任务重启服务

crontab -e
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

50 7    * * * kill -HUP $(ps axu |grep -v 'grep' |egrep "gunicorn"|awk '{system("echo "$2)}') && echo $(date +\%Y\%m\%d) -- "SUCCESS">> /root/crontab.log

相关文章

网友评论

      本文标题:flask 项目部署

      本文链接:https://www.haomeiwen.com/subject/exwuyqtx.html