Linux 下部署 Django 環境

安裝 Nginx

在本教程中,我們使用 Nginx 作爲 Web 服務器。

執行如下命令來安裝 nginx

yum install nginx

安裝完成後,執行如下命令來啓動 Nginx

systemctl start nginx.service
systemctl enable nginx.service

安裝 Python 環境

本實驗以 Python 最新版 , Python 3.6 爲基礎開發。

首先,我們來安裝 Python 3.6

yum install https://centos7.iuscommunity.org/ius-release.rpm -y 
yum install python36u  -y
yum install python36u-pip python36u-devel  -y

配置 Python PIP 的清華鏡像

爲了提升依賴的下載速度,這裏我們使用清華提供的鏡像源

首先,我們來創建文件夾,用於存儲我們的配置文件

mkdir ~/.config/pip/

然後在文件內添加如下代碼

示例代碼:/root/.config/pip/pip.conf

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

安裝 MySQL

首先,我們來安裝 MySQL ,這裏我們使用的是 MySQL 的一個發行版 —— MariaDB 。

yum install mariadb mariadb-server -y 
systemctl start mariadb.service
systemctl enable mariadb.service

安裝完成後,執行如下命令來進行 mariadb 的初始化,並根據提示設置 root 的密碼(默認密碼爲空)

mysql_secure_installation

初始化 Python 項目

任務時間:時間未知

初始化虛擬環境

爲了不影響外界環境的清潔,所以我們使用虛擬環境來配置 Django 項目

cd /home/
mkdir django
cd django
python3.6 -m venv venv

創建完成後,執行命令,進入虛擬環境

source venv/bin/activate

然後在虛擬環境中安裝 django 並初始化項目

pip install django
django-admin startproject my
cd my 
python manage.py startapp mine

預覽項目

創建完成 App 後,我們需要修改 my/settings.py 使 Django 能處理來做所有域名中的請求

示例代碼:/home/django/my/my/settings.py

"""
Django settings for my project.

Generated by 'django-admin startproject' using Django 2.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^p3prd2a*$y-#n%jy2#@)setwu(1+yv#2kas4l*4r5_ss&+3zm'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'my.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'my.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

修改完成後,執行如下命令來啓動 Django 的測試服務器。

python /home/django/my/manage.py runserver 0.0.0.0:80

這時,你可以訪問 http://<您的 CVM IP 地址> 查看預覽界面

配置 Uwsgi

任務時間:時間未知

安裝 Uwsgi

執行如下命令,退出虛擬環境。

deactivate

接下來,我們來安裝配置 Uwsgi

yum install gcc -y
python3.6 -m pip install uwsgi

測試 Uwsgi

執行如下命令,測試使用 uwsgi 來啓動 django

uwsgi --http :80 --chdir /home/django/my --home=/home/django/venv --module my.wsgi

此時,你可以訪問 https://<您的 CVM IP 地址> ,確認是否可以查看到 django 的測試頁面。

可以看到後,按下 Ctrl + C ,退出 uwsgi 進程。接下來我們來配置 Uwsgi。

配置 Uwsgi

首先,我們來創建一個目錄用於存放 Django 的配置文件

mkdir -p /home/django_conf

然後在這個目錄下創建一個文件 [uwsgi.ini].

示例代碼:/home/django_conf/uwsgi.ini

[uwsgi]
socket = /home/django_conf/my.sock
chdir = /home/django/my
wsgi-file = my/wsgi.py
plugins = python
virtualenv = /home/django/venv/
processes = 2
threads = 4
chmod-socket = 664
chown-socket = nginx:nginx
vacuum = true

 

這裏的 nginx:nginx 是 nginx 自己的用戶組和用戶名

配置 Nginx

配置完成 Uwsgi 後,我們來創建 Nginx 的配置文件(/etc/nginx/conf.d/my.conf)

示例代碼:/etc/nginx/conf.d/my.conf

server {
    listen      80;
    server_name <您的 CVM IP 地址>;
    charset     utf-8;

    client_max_body_size 75M;

    location /media  {
        alias /home/django/my/media;
    }

    location /static {
        alias /home/django/my/static;
    }

    location / {
        uwsgi_pass  unix:///home/django_conf/my.sock;
        include     /etc/nginx/uwsgi_params;
    }
}

然後,重啓 Nginx

systemctl restart nginx.service

配置 Supervisord

接下來,我們來配置 Supervisord ,確保我們的 django 可以持久運行

首先,我們要安裝 pip ,用來安裝 Supervisord。

yum install python-pip -y

安裝完成後,我們使用 pip 來安裝 supervisord,並輸出配置文件

python -m pip install supervisor
echo_supervisord_conf > /etc/supervisord.conf

並在配置文件(/etc/supervisord.conf)底部添加如下代碼

[program:my]
command=/usr/bin/uwsgi --ini /home/django_conf/uwsgi.ini
directory=/home/django/my
startsecs=0
stopwaitsecs=0
autostart=true
autorestart=true

添加完成後,執行如下命令來啓動 supervisord

supervisord -c /etc/supervisord.conf

這時,你可以訪問 http://<您的 CVM IP 地址> 查看網站

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章