使用 Nginx gunicorn virtualenv mys

2018-12-17  本文已影响0人  MiracleHui

使用 Nginx gunicorn virtualenv 部署django项目上线笔记

注意:本文我是root用户登陆的

第一部分 环境部署

首先我们开放我们需要用到的端口
#开放80,8000,8080端口
#返回success即成功
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=8000/tcp --permanent
firewall-cmd --zone=public --add-port=8080/tcp --permanent

#最后我们需要刷新防火墙规则
firewall-cmd --reload
安装python3,pip3,virtualenv
#更新yum库和安装wget vim
yum update -y
yum install wget -y
yum install vim -y

#安装依赖包
yum -y groupinstall "Development tools"
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel

#然后获取python3.7的安装包
cd  /usr/local/src
wget https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tar.xz

#配置python3的安装目录并安装
tar -xvJf  Python-3.7.1.tar.xz
cd Python-3.7.1
./configure --prefix=/usr/local/bin/python3
sudo make
sudo make install

#安装成功后发现python3提示找不到命令,以下是解决方法
#安装成功后在/usr/bin目录下创建python3和pip3符号链接
ln -s /usr/local/bin/python3/bin/python3 /usr/bin/python3
ln -s /usr/local/bin/python3/bin/pip3 /usr/bin/pip3

#更新pip3
pip3 install --upgrade pip

#安装virtualenv
pip3 install virtualenv
ln -s /usr/local/bin/python3/bin/virtualenv /usr/bin/virtualenv
安装mysql并配置mysql
#获取mysql5.7官方yum源
cd /usr/local/src/
wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm

#安装mysql官方yum源
rpm -ivh mysql-community-release-el7-5.noarch.rpm

#安装mysql5.7
yum -y install mysql-devel
yum -y install mysql-community-server

#安装完成后重启mysql服务
service mysqld restart

#输入mysql命令直接进入mysql控制台,并更改密码
#如果修改过密码后需要用mysql -u root -p命令进入
mysql
set password for 'root'@'localhost' =password('password');

#创建项目数据库呢
create database djangoproject;
exit
首先添加需要用到的源库
#添加Nginx官方yum源
rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

#安装nginx
yum install nginx -y

第二部分 Djano项目创建及部署

创建项目目录以及虚拟环境
#创建目录
mkdir /srv/www/myproject -p
cd /srv/www/myproject

#创建名为venv的虚拟环境
#--no-site-packages表示创建干净的虚拟环境
virtualenv --no-site-packages venv

#进入虚拟环境--命令前面有(venv)--即成功进入
source venv/bin/activate

#安装django gunicorn mysqlclient
pip3 install django gunicorn mysqlclient

创建Django项目
#使用django-manage.py创建  注意命令后面有一个 . 千万不要忽略了
django-manage.py startproject djangoproject .

#manage.py所在目录就是项目根目录

配置django项目
#修改项目的settings
vim djangoproject/settings.py

#在settings.py 修改ip权限,允许所有ip访问
ALLOWED_HOSTS = ['*']
TIME_ZONE='Asia/Shanghai'

#修改settings.py中的数据库参数
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoproject',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        }
    }
}

#settings.py 添加静态文件路径参数
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

#数据库中生成数据表
python manage.py makemigrations
python manage.py migrate

#创建一个超级用户
python manage.py createsuperuser

#收集静态文件
python manage.py collectstatic

#开启Django项目
python manage.py runserver 0.0.0.0:8000
测试gunicorn是否能启动你的项目服务
#在项目跟目录运行以下命令
gunicorn --bind 0.0.0.0:8000 djangoproject.wsgi:application

#访问ip地址看浏览器是否能正常查看内容(此时没有退出虚拟环境) 
#完成测试后,按CTRL-C 停止 Gunicorn 运行


#退出虚拟环境
deactivate

创建gunicorn服务文件

#创建一个 Gunicorn Systemd Service 文件
vim /etc/systemd/system/gunicorn.service

#输入以下内容
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=root
Group=nginx
WorkingDirectory=/srv/www/myproject
ExecStart=/srv/www/myproject/venv/bin/gunicorn --workers 2 --bind unix:/srv/www/myproject/djanao_socket.sock djangoproject.wsgi:application

[Install]
WantedBy=multi-user.target

#启动gunicorn服务以及开机自启
systemctl start gunicorn
systemctl enable gunicorn

#查看gunicorn是否成功激活
systemctl list-units --type=service --state=failed

配置nginx代理通过Gunicorn

现在Gunicorn已经建立,我们需要配置Nginx以将流量传递给进程。

#修改Nginx配置文件
vim /etc/nginx/nginx.conf

#备份原配置文件
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
nginx.conf配置,直接复制
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user  nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

    server {
        listen 80;
        server_name  server_IP;
        access_log /srv/www/myproject/nginx.access.log;
        error_log /srv/www/myproject/nginx.error.log;

        location / {
            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;
            proxy_pass http://unix:/srv/www/myproject/django.sock;
        }

        location /robots.txt {
            alias /srv/www/myproject/static/robots.txt;
        }

        location /favicon.ico {
            alias /srv/www/myproject/static/img/favicon.ico;
        }

        location ~ ^/(media|static)/  {
            root    /srv/www/myproject;
            expires 30d;
        }


        # this prevents hidden files (beginning with a period) from being served
        location ~ /\. { 
            access_log off; log_not_found off; deny all;
        }

    }

}

修改nginx权限
#修改nginx的权限
usermod -a -G root nginx
chmod 710 /srv/www/myproject
nginx -t

#开启nginx服务并开机自启
systemctl start nginx
systemctl enable nginx
解决502 Bad Gateway
yum -y install policycoreutils-python
semanage permissive -a httpd_t 

#重启服务器
上一篇下一篇

猜你喜欢

热点阅读