Django Nginx+uWSGI 安装配置指南
在Django开发中,python manage.py runserver
命令仅适用于开发和测试环境。对于生产环境,我们需要一个更为稳定和高效的服务器解决方案。Nginx和uWSGI的组合是发布Django应用的常见选择。以下是如何在Linux系统上安装和配置Nginx与uWSGI的详细步骤。
安装基础开发包
首先,需要安装Linux系统的基础开发包和Python环境。
对于CentOS系统,可以通过以下命令安装开发工具和依赖库:
yum groupinstall "Development tools"
yum install zlib-devel bzip2-devel pcre-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel
接着,安装Python 2.7.5(如果系统未自带所需版本):
cd ~
wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tar.bz2
tar xvf Python-2.7.5.tar.bz2
cd Python-2.7.5
./configure --prefix=/usr/local
make && make altinstall
安装Python包管理工具
使用以下命令安装easy_install
和pip
:
wget https://pypi.python.org/packages/source/d/distribute/distribute-0.6.49.tar.gz
tar xf distribute-0.6.49.tar.gz
cd distribute-0.6.49
python2.7 setup.py install
easy_install --version
pip install pip
安装uWSGI
uWSGI是一个用于部署Python应用的服务器。安装uWSGI:
pip install uwsgi
uwsgi --version
创建一个简单的test.py
文件来测试uWSGI是否安装成功:
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return "Hello World"
运行uWSGI并访问http://127.0.0.1:8001
来检查输出。
安装Django
使用pip安装Django:
pip install django
创建一个测试Django项目并运行服务器:
django-admin.py startproject demosite
cd demosite
python2.7 manage.py runserver 0.0.0.0:8002
安装Nginx
Nginx是一个高性能的HTTP服务器和反向代理服务器。安装Nginx:
wget http://nginx.org/download/nginx-1.5.6.tar.gz
tar xf nginx-1.5.6.tar.gz
cd nginx-1.5.6
./configure --prefix=/usr/local/nginx-1.5.6 \
--with-http_stub_status_module \
--with-http_gzip_static_module
make && make install
uWSGI配置
创建uWSGI配置文件/etc/uwsgi9090.ini
:
[uwsgi]
socket = 127.0.0.1:9090
master = true
vhost = true
no-site = true
workers = 2
reload-mercy = 10
vacuum = true
max-requests = 1000
limit-as = 512
buffer-size = 30000
pidfile = /var/run/uwsgi9090.pid
daemonize = /website/uwsgi9090.log
Nginx配置
配置Nginx以代理uWSGI服务器。编辑/usr/local/nginx/conf/nginx.conf
文件:
server {
listen 80;
server_name localhost;
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:9090;
uwsgi_param UWSGI_SCRIPT demosite.wsgi;
uwsgi_param UWSGI_CHDIR /demosite;
index index.html index.htm;
client_max_body_size 35m;
}
}
启动服务
启动uWSGI和Nginx服务:
uwsgi --ini /etc/uwsgi9090.ini &
/usr/local/nginx/sbin/nginx