概述
服務(wù)器的操作系統(tǒng)是Ubuntu14.04(64位)滑臊,使用Nginx作為反向代理喘鸟,uWSGI作為HTTP服務(wù)器堤尾,使用基于Python的Django應(yīng)用框架啰劲,數(shù)據(jù)庫方面使用MySQL。
1.建立文件夾
> cd ~
> mkdir webserver
- 安裝Python3和pip3
Ubuntu14.04默認(rèn)安裝的python版本是2.7交播,而我們這邊需要使用python3.4重虑,主要還是因為python3接下去是主流,而python3又不兼容python2秦士,Django框架以后也將不支持python2缺厉。
> sudo apt-get install python3.4 // v3.4.3
> sudo apt-get install python3-pip
這里需要兼容python2和python3,因為Ubuntu操作系統(tǒng)本身有很多地方還是依賴python2的,
> sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 100
> sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 150
接下來配置當(dāng)前使用python版本為python3提针,
> sudo update-alternatives --config python
一切配置完畢之后命爬,查看當(dāng)前python版本是否正確,
> python --version
Python 3.4.3
- 構(gòu)造一個干凈的Python副本
在開發(fā)Python應(yīng)用程序的時候辐脖,系統(tǒng)安裝的Python3只有一個版本:3.4遇骑。所有第三方的包都會被pip安裝到Python3的site-packages目錄下。
如果我們要同時開發(fā)多個應(yīng)用程序揖曾,那這些應(yīng)用程序都會共用一個Python落萎,就是安裝在系統(tǒng)的Python 3。如果應(yīng)用A需要Django 1.11炭剪,而應(yīng)用B需要Django2.0怎么辦练链?
這種情況下,每個應(yīng)用可能需要各自擁有一套“獨(dú)立”的Python運(yùn)行環(huán)境奴拦。virtualenv就是用來為一個應(yīng)用創(chuàng)建一套“隔離”的Python運(yùn)行環(huán)境媒鼓。
> sudo pip3 install virtualenv
> cd ~/webserver
> virtualenv venv
新建的Python環(huán)境被放到當(dāng)前目錄下的venv目錄。有了venv這個Python環(huán)境错妖,可以用source進(jìn)入該環(huán)境:
> source venv/bin/activate
(venv) jessen@ubuntu:~/webserver$
注意到命令提示符變了绿鸣,有個(venv)前綴,表示當(dāng)前環(huán)境是一個名為venv的Python環(huán)境暂氯,如果想退出潮模,
> deactivate
- 安裝MySQL
sudo apt-get install mysql-server-5.6 // 5.6.33
修改配置文件使得MySQL使用utf8字符編碼,配置文件路徑:/etc/mysql/my.cnf
痴施。
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
default-character-set = utf8
# Here is entries for some specific programs
# The following values assume you have at least 32M ram
# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
sql_mode = NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
character-set-server = utf8
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 127.0.0.1
#
- 安裝mysqlclient
雖然安裝了數(shù)據(jù)庫和Django應(yīng)用框架擎厢,但是他們之間是無法通訊的,只有遵循一定的協(xié)議才能進(jìn)行數(shù)據(jù)庫操作辣吃,因此還需要安裝MySQL數(shù)據(jù)庫驅(qū)動及接口动遭,mysqlclient版本至少1.3.7及以上。
> sudo apt-get install libmysqlclient-dev
> cd ~/webserver
> source venv/bin/activate
> pip install mysqlclient
> deactivate
- 安裝Django
> cd ~/webserver
> source venv/bin/activate
> pip install Django==1.11 // 1.11
安裝成功后神得,可以通過如下命令確認(rèn)Django是否安裝成功厘惦,
> cd ~/webserver
> source venv/bin/activate
> python
Python 3.4.3 (default, Nov 28 2017, 16:41:13)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
1.11
接下來我們創(chuàng)建一個Django項目,
> cd ~/webserver
> source venv/bin/activate
> mkdir website
> cd website
> django-admin startproject website
> python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s):
admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 18, 2018 - 11:19:28
Django version 1.11, using settings 'magsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
這時候打開瀏覽器哩簿,輸入IP地址: http://127.0.0.1:8000宵蕉,將會出現(xiàn)Django的提示頁面,這樣部署Django就算大功告成了卡骂。接下來我們需要稍微配置一下Django国裳,配置文件路徑~/webserver/website/website/settings.py
,
"""
Django settings for magsite project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pg&m@_e4zs@ktuc4=npe^d6s+aob0s3ne13b2em2m5uo*+10%i'
# 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 = 'magsite.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 = 'magsite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'magdb',
'USER': 'root',
'PASSWORD': 'magnity126912',
'HOST': '127.0.0.1',
'PORT': '3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
- 安裝uWSGI
> cd ~/webserver
> source venv/bin/activate
> pip install uwsgi //版本是2.0.17
編寫uWSGI的啟動腳本website_uwsgi.ini
形入,
# myweb_uwsgi.ini file
[uwsgi]
web_dir = /home/jessen/webserver
project_name = magsite
# Django-related settings
socket = :8000
# virtual enviroment
home = %(web_dir)/venv
# the base directory (full path)
chdir = %(web_dir)/%(project_name)
# Django s wsgi file
module = %(project_name).wsgi
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 2
threads = 2
# ... with appropriate permissions - may be needed
# chmod-socket = 664
# clear environment on exit
vacuum = true
# log
#daemonize = %(project_dir)/uwsgi.log
- 安裝Nginx
Nginx主要用來做反向代理用全跨,關(guān)于代理和反向代理的區(qū)別,可以用一句話概括:代理服務(wù)區(qū)客戶端亿遂,反向代理服務(wù)于服務(wù)端浓若。如果有時間的話渺杉,我想就Nginx在以后的博文中會有更詳細(xì)的介紹。
> sudo apt-get install nginx
Nginx用于處理靜態(tài)網(wǎng)頁挪钓,而動態(tài)網(wǎng)頁則需要交給uWSGI來處理是越,因此需要配置Nginx,配置文件路徑:/etc/nginx/sites-available/default
碌上,增加如下內(nèi)容:
server {
listen 8005;
server_name localhost;
charset utf-8;
client_max_body_size 75M;
location /static {
alias /home/jessen/webserver/website/static;
}
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8000;
}
}
配置完畢后倚评,重啟Nginx,
> sudo service nginx restart
- 測試
> cd ~/webserver
> source venv/bin/activate
> uwsgi --ini website/website_uwsgi.ini
打開瀏覽器,輸入:127.0.0.1:8005馏予,如果能夠看到Django的測試頁面天梧,就說明環(huán)境部署成功了。