h3blog linux+python虚拟环境下flask使用gunicorn+nginx高并发部署

背景

总有人问我h3blog博客怎么部署,这里简单写下过程

1、下载源码

$ git clone https://gitee.com/pojoin/h3blog.git
$ cd h3blog
$ python -m venv venv  #创建python虚拟环境
$ source venv/bin/activate
$ 
$ pip install -r requirements.txt # 安装项目依赖,可能不全,根据提示自行安装即可

2、修改配置文件

$ vim .env

FLASK_CONFIG=production
DATABASE_URL=mysql+pymysql://root:123456@127.0.0.1/h3blog?charset=utf8

H3BLOG_UPLOAD_TYPE=qiniu
QINIU_CDN_URL=http://cdn.h3blog.com/
QINIU_BUCKET_NAME=h3blog
QINIU_ACCESS_KEY=Kio7HR9o7mUpSFdLjLwJvKxAaeTAgnXpJ4hT-h_J
QINIU_SECRET_KEY=eEHXUpudwApbuTRWQl0k1mbJZwO1Pv-iWx77Mltd

H3BLOG_DOMAIN=https://www.h3blog.com
BAIDU_PUSH_TOKEN=TagL7I7By8xm4Nm5

SITEMAP_URL_SCHEME=https

3、安装gunicorn

pip install gunicorn
pip install gevent

4、配置gunicoren开机自启

# vim /etc/systemd/system/gunicorn_h3blog.service
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/data/h3blog
ExecStart=/data/h3blog/venv/bin/gunicorn -c /data/h3blog/gunicorn.py  wsgi:app

[Install]
WantedBy=multi-user.target

gunicorn.py内容如下:

import logging
import logging.handlers
from logging.handlers import WatchedFileHandler
import os
import multiprocessing

project_path = os.path.dirname(__file__)
print(project_path)

bind = f'unix:{project_path}/h3blog.sock' #绑定ip和端口号
# daemon = True  # 是否开启守护进程模式
backlog = 512   #监听队列
chdir = f'{project_path}'  #gunicorn要切换到的目的工作目录
timeout = 30  #超时
worker_class = 'gevent' #使用gevent模式,还可以使用sync 模式,默认的是sync模式
workers = multiprocessing.cpu_count() * 2 + 1    #进程数
threads = 2 #指定每个进程开启的线程数
loglevel = 'info' #日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'    #设置gunicorn访问日志格式,错误日志无法设置

"""
其每个选项的含义如下:
h          remote address
l          '-'
u          currently '-', may be user name in future releases
t          date of the request
r          status line (e.g. ``GET / HTTP/1.1``)
s          status
b          response length or '-'
f          referer
a          user agent
T          request time in seconds
D          request time in microseconds
L          request time in decimal seconds
p          process ID
"""
capture_output = True # 是否捕获输出
accesslog = f"{project_path}/logs/gunicorn_access.log"      #访问日志文件
errorlog = f"{project_path}/logs/gunicorn_error.log"        #错误日志文件

开机自启

# systemctl enable gunicorn_h3blog.service

启动gunicorn

# systemctl start gunicorn_h3blog.service

5、安装nginx

apt install nginx

6、配置nginx

# vim /etc/nginx/sites-available/h3blog.com
server {
    listen 80;
    server_name www.h3blog.com h3blog.com;

    gzip on;
    gzip_buffers 32 4K;
    gzip_comp_level 6;
    gzip_min_length 100;
    gzip_types application/javascript text/css text/xml;
    gzip_disable "MSIE [1-6]\."; #配置禁用gzip条件,支持正则。此处表示ie6及以下不启用gzip(因为ie低版本不支持)
    gzip_vary on;

    client_max_body_size 10M;

    location /root.txt {
                alias /data/taobaoke/root.txt;
        }
    location /js/ {
                alias /data/h3blog-flask/app/main/themes/tend/static/js/;
                autoindex on;
    }
    location /css/ {
                alias /data/h3blog-flask/app/main/themes/tend/static/css/;
                autoindex on;
        }
     location /img/ {
                alias /data/h3blog-flask/app/main/themes/tend/static/img/;
                autoindex on;
        }

    location / {
        include proxy_params;
        proxy_pass http://unix:/data/h3blog/h3blog.sock;
    }

    #return 301 https://$server_name$request_uri;
}

server {
    listen 443;
    server_name www.h3blog.com h3blog.com;
    ssl on;
    ssl_certificate   cert/h3blog.com/3852674_h3blog.com.pem;
    ssl_certificate_key  cert/h3blog.com/3852674_h3blog.com.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    gzip on;
    gzip_buffers 32 4K;
    gzip_comp_level 6;
    gzip_min_length 100;
    gzip_types application/javascript text/css text/xml;
    gzip_disable "MSIE [1-6]\."; #配置禁用gzip条件,支持正则。此处表示ie6及以下不启用gzip(因为ie低版本不支持)
    gzip_vary on;

    client_max_body_size 10M;

    location /js/ {
                alias /data/h3blog-flask/app/main/themes/tend/static/js/;
                autoindex on;
    }
        location /css/ {
                alias /data/h3blog-flask/app/main/themes/tend/static/css/;
                autoindex on;
        }
        location /img/ {
                alias /data/h3blog-flask/app/main/themes/tend/static/img/;
                autoindex on;
        }

    location / {
        include proxy_params;
        proxy_pass http://unix:/data/h3blog/h3blog.sock;
    }

}