项目部署二:服务器和环境配置

2.服务和环境配置

下面的配置和操作均在腾讯云服务器+CentOS 7.5的系统下进行。

2.1 MySQL

  • 安装服务端

    yum install mariadb-server -y
    mariadb-server.x86_64 1:5.5.68-1.el7
    
  • 安装客户端

    yum install mariadb -y
    软件包 1:mariadb-5.5.68-1.el7.x86_64 已安装并且是最新版本
    
  • 服务配置

    • 启动
      systemctl start mariadb
      
    • 设置开机自启动
      systemctl enable mariadb
      
  • 账号初始化

    • 登录

      mysql -u root -p
      
    • root设置密码

      UPDATE user SET password=password('qwe123..') WHERE user='root'; 
      flush privileges;
      
    • 创建用户

      insert into mysql.user(user,host,password) values('xxx','%',password('qwe123..'));
      
      # 或更新密码
      UPDATE user SET password=password('qwe123..') WHERE user='xxx'; 
      flush privileges;
      
    • 创建数据库

      CREATE DATABASE 数据库名 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
      
    • 授权

      grant all privileges on 数据库.* to settle@'%';
      flush privileges;
      
      grant all privileges on 数据库.* to tasker@'127.0.0.1';
      flush privileges;
      

    img

    img

服务器安全组可以进行端口配置

2.2 redis

  • 安装
    yum install redis -y
    
  • 配置
    打开文件
      	vim /etc/redis.conf
    
      	寻找
      		?requirepass
    
      	进入编辑状态
      		requirepass qwe123456
    
      	点击ESC退出编辑状态
    
      	保存并退出
      		:wq
    
    
  • 启动
    • 启动
      systemctl start redis
      systemctl restart redis
      
    • 开机启动
      systemctl enable redis
      

2.3 Python3

  • 安装gcc,用于后续安装Python时编译源码。

    yum install gcc -y
    
  • 安装Python3相关依赖

    yum install zlib zlib-devel -y
    yum install bzip2 bzip2-devel  -y
    yum install ncurses ncurses-devel  -y
    yum install readline readline-devel  -y
    yum install openssl openssl-devel  -y
    yum install xz lzma xz-devel  -y
    yum install sqlite sqlite-devel  -y
    yum install gdbm gdbm-devel  -y
    yum install tk tk-devel  -y
    yum install mysql-devel -y
    yum install python-devel -y
    yum install libffi-devel -y
    
  • 下载Python源码,https://www.python.org/ftp/python/

    cd /data/
    wget https://www.python.org/ftp/python/3.9.5/Python-3.9.5.tgz
    

    注意:如果没有wget,则先安装 yum install wget

  • 编译安装

    • 解压

      tar -xvf Python-3.9.5.tgz
      
    • 进入目录并编译安装

      cd Python-3.9.5
      ./configure
      make all
      make install
      
    • 测试

      python3 --version
      
      /usr/local/bin/python3
      /usr/local/bin/pip3
      /usr/local/bin/pip3.9
      
    • 配置豆瓣源(腾讯云服务器,默认腾讯源)

      pip3.9 config set global.index-url https://pypi.douban.com/simple/
      

2.4 虚拟环境

  • 安装虚拟环境

    pip3.9 install virtualenv
    
  • 创建虚拟环境目录并创建虚拟环境

    mkdir /envs
    virtualenv /envs/nb --python=python3.9
    
  • 安装项目依赖的pip包

    source /envs/nb/bin/activate
    cd /data/www/nb/
    pip install -r requirements.txt
    

2.5 拉取代码和配置

当上述环境准备好之后,接下来需要在线上服务器上做以下步骤:

  • 获取最新代码

  • 安装第三方包

    source /envs/nb/bin/activate # 激活虚拟环境
    pip install -r requirements.txt # 下载gitee上面down下来的代码
    
  • local_settings.py设置线上配置(在虚拟环境中创建本py文件,然后进行项目配置)

    import os
    from pathlib import Path
    
    BASE_DIR = Path(__file__).resolve().parent.parent.parent
    
    DEBUG = False
    
    ALLOWED_HOSTS = ['*']
    
    STATIC_ROOT = os.path.join(BASE_DIR,"allstatic")
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
    		'NAME': 'day06db',  # 数据库名字
            'USER': 'wangchuan',
            'PASSWORD': 'qwe123..',
            'HOST': '127.0.0.1',  # ip
            'PORT': 3306,
        }
    }
    
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "CONNECTION_POOL_KWARGS": {"max_connections": 100},
                "PASSWORD": "qwe123456",
            }
        }
    }
    
  • 收集静态文件

    python manage.py  collectstatic
    

2.5 uwsgi

激活虚拟环境并安装uwsgi

source /envs/nb/bin/activate
pip install uwsgi

命令运行:
	cd /data/www/day06
	uwsgi --http :80 --chdir /data/www/day06/ --wsgi-file day06/wsgi.py --master --processes 1 - static-map static=/data/www/allstatic/

基于uwsgi运行项目

  • 命令参数

    uwsgi --http :80 --chdir /data/www/xxxxx/ --wsgi-file day06/wsgi.py --master --processes 4 --static-map /static=/data/www/allstatic
    
  • 文件参数

    • 创建 day06_uwsgi.ini

      [uwsgi]
      http = 0.0.0.0:80
      chdir = /data/www/xxxxx/
      wsgi-file = day06/wsgi.py
      processes = 4
      static-map = /static=/data/www/allstatic
      
      virtualenv = /envs/nb/
      
      
    • 执行命令

      uwsgi --ini  day06_uwsgi.ini
      

2.6 nginx

利用nginx做反向代理和处理静态文件。

yum install nginx -y

修改nginx.conf配置文件:

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

# Load dynamic modules. See /usr/share/doc/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 4096;

    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;

    upstream django {
        server 127.0.0.1:8001;
    }

    server {
        listen       80;
        listen       [::]:80;
        server_name  day06.pythonav.com;

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

		location /static {
            alias  /data/www/allstatic/;
        }

        location / {
            uwsgi_pass  django;
            include     uwsgi_params;
        }

    }
}

修改uwsgi配置(day06_uwsgi):

[uwsgi]
socket = 127.0.0.1:9000
chdir = /data/www/xxxxx/
wsgi-file = day06/wsgi.py
processes = 4
virtualenv = /envs/video_killer/

接下来就需要启动uwsgi和nginx:

  • nginx

    # 启动
    systemctl start nginx
    
    # 开机启动
    systemctl enable nginx
    
  • uwsgi

    uwsgi --ini  day06_uwsgi.ini
    

每次启动都比较麻烦,怎么办?

2.7 shell脚本

  • shell脚本,自动实现重启等功能(shell命令)

    • reboot.sh
    • stop.sh

2.7.1 reboot.sh

#!/usr/bin/env bash

echo -e "\033[34m--------------------wsgi process--------------------\033[0m"

ps -ef|grep uwsgi_day06.ini | grep -v grep

sleep 0.5

echo -e '\n--------------------going to close--------------------'

ps -ef |grep uwsgi_day06.ini | grep -v grep | awk '{print $2}' | xargs kill -9

sleep 0.5

echo -e '\n----------check if the kill action is correct----------'

/envs/day06/bin/uwsgi  --ini uwsgi_day06.ini &  >/dev/null

echo -e '\n\033[42;1m----------------------started...----------------------\033[0m'
sleep 1

ps -ef |grep uwsgi_day06.ini | grep -v grep
chmod 755 reboot.sh
./reboot.sh

2.7.2 stop.sh

#!/usr/bin/env bash

echo -e "\033[34m--------------------wsgi process--------------------\033[0m"

ps -ef |grep uwsgi_day06.ini | grep -v grep

sleep 0.5

echo -e '\n--------------------going to close--------------------'

ps -ef |grep uwsgi_day06.ini | grep -v grep | awk '{print $2}' | xargs kill -9

sleep 0.5

2.7.3 uwsgi

uwsgi_day06.ini

[uwsgi]
socket = 127.0.0.1:8001
chdir = /data/www/day06/
wsgi-file = day06/wsgi.py
processes = 1
virtualenv = /envs/day06/

数据库处理

	 登录线上服务器
	 	python manage.py makemigrations
	 	python manage.py migrate

	 在.gitignore中
	 	# database migrations
		*/migrations/*.py
		!*/migrations/__init__.py

	原因:redis配置没有重启。
	问题:关于应该尽可能的去避免。

2.8 域名和解析

2.8.1 购买域名

img

2.8.2 解析

就是让域名和我们刚才买的服务器绑定,以后通过域名就可以找到那台服务器,不需要再使用IP了。
img

img

img

img

2.9 https

2.9.1 申请证书

2.9.2 下载证书

2.9.3 证书上传

将证书文件上传至服务器,例如:上传至项目目录的ssl文件夹下。

2.9.4 修改nginx配置

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

events {
    worker_connections  65536;
    use epoll;
}

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;
    gzip on;
    gzip_http_version 1.1;
    gzip_buffers  4 32k;
     gzip_comp_level 9;
    include             mime.types;
    default_type        application/octet-stream;

    upstream django {
        server 127.0.0.1:8001; # for a web port socket (we'll use this first)
    }

    server {
        listen      80;
        server_name day06.pythonav.com;
        rewrite ^(.*) https://$server_name$1 redirect;
    }

    server {
        listen       443 ssl;
        server_name  day06.pythonav.com;

        #证书文件
        ssl_certificate      /data/www/ssl/8372403_day06.pythonav.com.pem;
        #私钥文件
        ssl_certificate_key  /data/www/ssl/8372403_day06.pythonav.com.key;

        ssl_session_cache    shared:SSL:1m;
        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;

        location / {
            uwsgi_pass  django;
            include     uwsgi_params;
           }
        location /static {
            alias  /data/www/allstatic;
        }
    }

}
  • nginx重启(就合适了)
    systemctl restart nginx
posted @ 2024-10-05 20:33  tmars  阅读(16)  评论(0编辑  收藏  举报