配置python3 项目环境

安装python3

安装仓库软件

sudo apt-get install software-properties-common python-software-properties

添加仓库

sudo add-apt-repository ppa:jonathonf/python-3.6

更新

sudo apt-get update

安装python3.6

sudo apt-get install python3.6

修改python3版本

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2
sudo update-alternatives --config python3

安装pip3

sudo apt install python3-pip

安装虚拟模块

apt install python3.6-venv

cd进入项目目录,建立虚拟环境目录

python3 -m venv env

激活虚拟环境

source env/bin/activate

配置项目

安装依赖

pip3 install -r requirements.txt
ubuntu 安装依赖报错, 可能是需要先安装
sudo apt-get install python3.6-dev

上传代码,并运行起来

sanic 运行方式: python3 -m sanic server.app --host=0.0.0.0 --port=1337 --workers=4 #后面参数如果文件里有app.run().参数可以不写
gunicorn方式: gunicorn server:app --bind 0.0.0.0:3000 --worker-class sanic.worker.GunicornWorker

Supervisor + gunicron 监控端口,重启服务

文档:https://www.cnblogs.com/weidiao/p/6505346.html

[program:btc]
directory = /www/wwwroot/python_project/btc.local
command=/www/wwwroot/python_project/btc.local/env/bin/gunicorn server:app --bind 0.0.0.0:3000 --worker-class sanic.worker.GunicornWorker
autostart=true
autorestart=true
stdout_logfile=/www/wwwroot/python_project/btc.local/logs/gunicorn.log
stderr_logfile=/www/wwwroot/python_project/btc.local/logs/gunicorn.err

supervisorctl reload

配置nginx

上面可以用Ip地址访问程序了,但要域名访问需配置nginx

server {
    listen 80;
    server_name example.org; # 这是HOST机器的外部域名,用地址也行

    location / {
        proxy_pass http://127.0.0.1:8080; # 这里是指向 gunicorn host 的服务地址
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

或者

server {
    listen 80;
    # 这是服务器的外部域名(不建议用IP地址)
    server_name example.com www.example.com;

    location / {
        # 这里是指向gunicorn服务器的端口
        proxy_pass http://localhost:8080; 
    }
    
    location /static {
        # 配置静态文件的相对地址
        alias /mnt/www/app/static
    }
  }

启动nginx: sudo service nginx restart

原文地址:https://www.cnblogs.com/xielisen/p/8433047.html