环境部署

概述

服务器的操作系统是Ubuntu14.04(64位),使用Nginx作为反向代理,uWSGI作为HTTP服务器,使用基于Python的Django应用框架,数据库方面使用MySQL。

1.建立文件夹

> cd ~
> mkdir webserver

  1. 安装Python3和pip3
    Ubuntu14.04默认安装的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操作系统本身有很多地方还是依赖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

接下来配置当前使用python版本为python3,

> sudo update-alternatives --config python

一切配置完毕之后,查看当前python版本是否正确,

> python --version
Python 3.4.3

  1. 构造一个干净的Python副本

在开发Python应用程序的时候,系统安装的Python3只有一个版本:3.4。所有第三方的包都会被pip安装到Python3的site-packages目录下。
如果我们要同时开发多个应用程序,那这些应用程序都会共用一个Python,就是安装在系统的Python 3。如果应用A需要Django 1.11,而应用B需要Django2.0怎么办?
这种情况下,每个应用可能需要各自拥有一套“独立”的Python运行环境。virtualenv就是用来为一个应用创建一套“隔离”的Python运行环境。

> sudo pip3 install virtualenv
> cd ~/webserver
> virtualenv venv

新建的Python环境被放到当前目录下的venv目录。有了venv这个Python环境,可以用source进入该环境:

> source venv/bin/activate
(venv) jessen@ubuntu:~/webserver$

注意到命令提示符变了,有个(venv)前缀,表示当前环境是一个名为venv的Python环境,如果想退出,

> 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
    虽然安装了数据库和Django应用框架,但是他们之间是无法通讯的,只有遵循一定的协议才能进行数据库操作,因此还需要安装MySQL数据库驱动及接口,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

安装成功后,可以通过如下命令确认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

接下来我们创建一个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,将会出现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主要用来做反向代理用,关于代理和反向代理的区别,可以用一句话概括:代理服务区客户端,反向代理服务于服务端。如果有时间的话,我想就Nginx在以后的博文中会有更详细的介绍。
> sudo apt-get install nginx

Nginx用于处理静态网页,而动态网页则需要交给uWSGI来处理,因此需要配置Nginx,配置文件路径:/etc/nginx/sites-available/default,增加如下内容:

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的测试页面,就说明环境部署成功了。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,254评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,875评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,682评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,896评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,015评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,152评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,208评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,962评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,388评论 1 304
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,700评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,867评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,551评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,186评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,901评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,142评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,689评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,757评论 2 351

推荐阅读更多精彩内容