概述
服务器的操作系统是Ubuntu14.04(64位),使用Nginx作为反向代理,uWSGI作为HTTP服务器,使用基于Python的Django应用框架,数据库方面使用MySQL。
1.建立文件夹
> cd ~
> mkdir webserver
- 安装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
- 构造一个干净的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
- 安装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
虽然安装了数据库和Django应用框架,但是他们之间是无法通讯的,只有遵循一定的协议才能进行数据库操作,因此还需要安装MySQL数据库驱动及接口,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
安装成功后,可以通过如下命令确认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/'
- 安装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主要用来做反向代理用,关于代理和反向代理的区别,可以用一句话概括:代理服务区客户端,反向代理服务于服务端。如果有时间的话,我想就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
- 测试
> cd ~/webserver
> source venv/bin/activate
> uwsgi --ini website/website_uwsgi.ini
打开浏览器,输入:127.0.0.1:8005,如果能够看到Django的测试页面,就说明环境部署成功了。