CentOS 7下通过uWSGI + Nginx部署Django

Coding Alan 8年前 (2017-01-11) 9346次浏览 0个评论 扫描二维码

安装Python 3

wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
tar -xzvf Python-3.6.0.tgz -C  /tmp
cd  /tmp/Python-3.6.0/
./configure --prefix=/usr/local
make && make altinstall

安装Nginx

#add the CentOS 7 EPEL repository(/etc/yum.repos.d/)
sudo yum -y install epel-release
#安装Nginx
sudo yum -y install nginx
#启动Nginx
sudo systemctl start nginx
#如果运行了防火墙执行如下命令允许http和https的web访问
sudo firewall-cmd --permanent --zone=public --add-service=http 
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
#开机启动Nginx服务
sudo systemctl enable nginx

在浏览器中访问http://server_domain_name_or_IP/如果出现如下页面表明Nginx安装正常
CentOS 7下通过uWSGI + Nginx部署Django
Nginx主配置文件:/etc/nginx/nginx.conf,可以看网站默认根目录在/usr/share/nginx/html,可通过在/etc/nginx/conf.d下添加.conf文件进行配置

安装MySQL

#安装MySQL,由于直接通过yum安装将会安装的是MariaDB
#需访问https://dev.mysql.com/downloads/repo/yum/查找对应的版本
wget https://dev.mysql.com/get/mysql57-community-release-el7-9.noarch.rpm
rpm -ivh mysql57-community-release-el7-9.noarch.rpm
yum install -y mysql-server mysql-devel
#启动MySQL服务
systemctl start mysqld
#查找安装初始密码
grep 'temporary password' /var/log/mysqld.log
#修改密码删除多余的测试表
mysql_secure_installation

安装virtualenvwrapper

yum -y install python-setuptools python-devel
yum -y install python-pip
pip install virtualenvwrapper
#如果出现因安装过慢所导致的失败,进行如下配置
cd ~
mkdir .pip
cd .pip
vi pip.conf 
#放入如下内容保存退出
[global]  
index-url = https://pypi.doubanio.com/simple/  
[install]  
trusted-host=pypi.doubanio.com  
disable-pip-version-check = true  
timeout = 6000  

#也可在安装时直接使用pip install -i https://pypi.douban.com/simple package_name

编辑家目录下的.bashrc文件设置如下环境变量

export WORKON_HOME=$HOME/.virtualenvs
#可不设置export PROJECT_HOME=$HOME/project_directory
source /usr/bin/virtualenvwrapper.sh 
#重载.bashrc
source  ~/.bashrc
#新建虚拟环境
mkvirtualenv test

#过入本机,导出本地环境安装包
workon xxx
pip freeze > requirements.txt
#上传requirements.txt需部署机器
workon test
pip install -r requirements.txt


#安装uwsgi
pip install uwsgi

测试uwsgi(Web Server Gateway Interface)是否安装正常

方法一: 创建test.py文件,添加如下代码

def application(env, start_response):
        start_response('200 OK', [('Content-Type','text/html')])
        return "Hello World"
#执行如下代码
uwsgi --http :8001 --wsgi-file test.py

浏览器访问http://your-ip:8001输出Hello World表示安装正常
方法二:

django-admin startproject testProject
cd testProject
uwsgi --http :8000 --module testProject.wsgi

浏览器访问http://your-ip:8000输出It worked页面表示安装正常

以上方法如无法访问,可能需要关闭防火墙:systemctl stop firewalld
如果从本地打包上传,在testProject/settings.py

#将DEBUG值修改为False
#注释以下部分
#STATICFILES_DIRS = [
#    os.path.join(BASE_DIR, 'static')
#]
#添加如下代码
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

执行 python manage.py collectstatic

Nginx配置

在testProject主目录下创建uc_nginx.conf然后创建软链接
sudo ln -s 你的目录/testProject/uc_nginx.conf /etc/nginx/conf.d/
或者直接在/etc/nginx/conf.d/下创建uc_nginx.conf:

# the upstream component nginx needs to connect to
upstream django {
# server unix:///path/to/your/mysite/mysite.sock; # for a file socket
server 127.0.0.1:8000; # for a web port socket (we'll use this first)
}
# configuration of the server

server {
# the port your site will be served on
listen      80;
# the domain name it will serve for
server_name 192.168.0.16 www.yourdomain.com; # substitute your machine's IP address or FQDN
charset     utf-8;

# max upload size
client_max_body_size 75M;   # adjust to taste

# Django media
location /media  {
    alias /root/testProject/media;  # 指向django的media目录
}

location /static {
    alias /root/testProject/static; # 指向django的static目录
}

# Finally, send all non-media requests to the Django server.
location / {
    uwsgi_pass  django;
    include     uwsgi_params; # the uwsgi_params file you installed
}
}

#ssl配置
server {
# the port your site will be served on
listen   443;
ssl on;
ssl_certificate   /home/cert/yourcert.pem;
ssl_certificate_key  /home/cert/yourkey.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
# the domain name it will serve for
server_name www.yourdomain.com; # substitute your machine's IP address or FQDN
charset     utf-8;

# max upload size
client_max_body_size 75M;   # adjust to taste

# Django media
location /media  {
    alias /root/testProject/media;  # 指向django的media目录
}

location /static {
    alias /root/testProject/static; # 指向django的static目录
}

# Finally, send all non-media requests to the Django server.
location / {
    uwsgi_pass  django;
    include     /root/testProject/conf/uwsgi_params; # the uwsgi_params file you installed
}
}

重启Nginx
注:使用systemctl restart nginx.service有可能会出现权限问题

些时使用pkill -f nginx,执行如下命令启动nginx

sudo /usr/sbin/nginx

在根目录下/root/testProject添加conf/uwsgi.ini

# mysite_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /root/testProject
# Django's wsgi file
module          = testProject.wsgi
# the virtualenv (full path)

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10
# the socket (use the full path to be safe
socket          = 127.0.0.1:8000
# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum          = true
virtualenv = /root/.virtualenvs/test
~                                     

启动

uwsgi -i /root/testProject/conf/uwsgi.ini &

Django的配置



接下来配置站点下的settings.py中数据库部分,创建app

[php]
python manage.py startapp blog
python manage.py makemigrations
python manage.py migrate

系统就会创建一些django默认表格,同样地可以测试启动站点

python manage.py runserver 0.0.0.0:9000

uwsgi

uwsgi --http :8000 --home /root/.virtualenvs/test --chdir /root/testsite/ -w testsite.wsgi
#停止所有uwsgi服务
ps -ef |grep uwsgi |awk '{print $2}'|xargs kill -9
#或使用如下命令自动关闭并重启
pkill -f uwsgi

设置定时任务

 

常见问题

1.Exception: you need a C compiler to build uWSGI
或Failed building wheel for mysql-python

yum install gcc  
//或执行
yum groupinstall "Development tools"

http://11hcw.me/setting-up-django-and-cloud-server-with-uwsgi-and-nginx/

2.environmenterror mysql_config not found

yum install -y mysql-devel

3.‘WSGIRequest’ object has no attribute ‘user’

访问http://your_ip:8000/admin时出现如上报错,将settings中的MIDDLEWARE改为MIDDLEWARE_CLASSES可以修复这一问题
4.出现以下报错需先安装MySQL

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-vMcjZK/MySQL-python/
# 注:Python 3尚不能直接支持MySQL-python,请使用pip install mysqlclient

5.出现以下错误yum install gcc -y

error: command 'gcc' failed with exit status 1
  
  ----------------------------------------
  Failed building wheel for MySQL-python

6.ImportError: cannot import name patterns
根据提示找到对应文件,如Alan这里是由一个Ueditor插件所致,找到DjangoUeditor/urls.py删除掉patterns的import并修改掉urlpattern的写法

from django.conf.urls import patterns, url
修改为
from django.conf.urls import url
urlpatterns = patterns('',
    url(r'^controller/$',get_ueditor_controller)
)
修改为
urlpatterns = [
    url(r'^controller/$',get_ueditor_controller)
]

7.TemplateDoesNotExist
将本地项目移到线上,UEditor会报错,关闭调试在后台中查看详情或添加时均会报Server Error (500)
Exception Type: TemplateDoesNotExist
Exception Value: ueditor.html
相信会有更好的解决方法,Alan的处理方式是将相关的模板文件以及静态文件拷贝到对应目录

/root/.virtualenvs/yourproject/DjangoUeditor/templates/* extra_apps/xadmin/templates/
cp -R /root/.virtualenvs/yourproject/DjangoUeditor/static/* static/

参考文章:

初识Nginx

如何将django项目用Nginx部署到服务器

喜欢 (5)
[]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址