環(huán)境部署

概述

服務(wù)器的操作系統(tǒng)是Ubuntu14.04(64位)滑臊,使用Nginx作為反向代理喘鸟,uWSGI作為HTTP服務(wù)器堤尾,使用基于Python的Django應(yīng)用框架啰劲,數(shù)據(jù)庫方面使用MySQL。

1.建立文件夾

> cd ~
> mkdir webserver

  1. 安裝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

  1. 構(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 

  1. 安裝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
#

  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

  1. 安裝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/'


  1. 安裝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

  1. 安裝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

  1. 測試
> cd ~/webserver
> source venv/bin/activate
> uwsgi --ini website/website_uwsgi.ini

打開瀏覽器,輸入:127.0.0.1:8005馏予,如果能夠看到Django的測試頁面天梧,就說明環(huán)境部署成功了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末霞丧,一起剝皮案震驚了整個濱河市呢岗,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蛹尝,老刑警劉巖后豫,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異突那,居然都是意外死亡挫酿,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進(jìn)店門愕难,熙熙樓的掌柜王于貴愁眉苦臉地迎上來饭豹,“玉大人,你說我怎么就攤上這事务漩≈羲ィ” “怎么了?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵饵骨,是天一觀的道長翘悉。 經(jīng)常有香客問我,道長居触,這世上最難降的妖魔是什么妖混? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮轮洋,結(jié)果婚禮上制市,老公的妹妹穿的比我還像新娘。我一直安慰自己弊予,他們只是感情好祥楣,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般误褪。 火紅的嫁衣襯著肌膚如雪责鳍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天兽间,我揣著相機(jī)與錄音历葛,去河邊找鬼。 笑死嘀略,一個胖子當(dāng)著我的面吹牛恤溶,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播帜羊,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼宏娄,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了逮壁?” 一聲冷哼從身側(cè)響起孵坚,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎窥淆,沒想到半個月后卖宠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡忧饭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年扛伍,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片词裤。...
    茶點(diǎn)故事閱讀 39,739評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡刺洒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出吼砂,到底是詐尸還是另有隱情逆航,我是刑警寧澤,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布渔肩,位于F島的核電站因俐,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏周偎。R本人自食惡果不足惜抹剩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蓉坎。 院中可真熱鬧澳眷,春花似錦、人聲如沸蛉艾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至箍土,卻和暖如春逢享,著一層夾襖步出監(jiān)牢的瞬間罐监,已是汗流浹背吴藻。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留弓柱,地道東北人沟堡。 一個月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像矢空,于是被迫代替她去往敵國和親航罗。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,647評論 2 354

推薦閱讀更多精彩內(nèi)容