`

用nginx和uwsgi部署 Django

阅读更多

This post attempts to be a complete guide to setting up a production-ready Django deployment. I’m publishing it because I hope it will help someone. It is subject to revision, as I get feedback from experience and other developers. I’m not going to populate this post with my usual literary cruft, either.

I’m using nginx and uWSGI because, so far, it’s been the best-performing combination I’ve tried. At low concurrency, it’s comparable in performance to Apache with mod_wsgi; as concurrency increases, it becomes screamingly fast in comparison. Speed is certainly a factor in making the choice, but nginx’s super-simple configuration doesn’t hurt its chances (zen[2]).

Let’s jump in.

Installation

  1. Create a virtualenv. This will house a complete Python environment, and all the compiled nginx and uwsgi binaries:

    $ virtualenv examplesite
    $ cd examplesite/
    $ . bin/activate
    

    I like to create mine in /sites/ — for example, /sites/example.com/.

  2. Download the nginx and uWSGI tarballs into a pkg/ directory:

    $ mkdir pkg && cd pkg/
    $ wget 'http://projects.unbit.it/downloads/uwsgi-0.9.4.2.tar.gz'
    $ wget 'http://nginx.org/download/nginx-0.7.65.tar.gz'
    
  3. Start by compiling uWSGI. I prefer to use the ROCK_SOLID mode, as this is for a production site:

    $ tar -xzvf uwsgi-0.9.4.2.tar.gz
    $ cd uwsgi-0.9.4.2/
    $ make -f Makefile.ROCK_SOLID
    

    Note that you may need to edit Makefile.ROCK_SOLID for your particular version of Python. The last command will have created a binary called uwsgi_rs; move this into your virtualenv’s bin/ directory and rename it to uwsgi:

        $ mv uwsgi_rs $VIRTUAL_ENV/bin/uwsgi
    
  4. Next, you’ll compile nginx with the uWSGI extension module. Extract the nginx tarball and enter the directory:

    $ cd $VIRTUAL_ENV/pkg
    $ tar -xzvf nginx-0.7.65.tar.gz
    $ cd nginx-0.7.65/
    

    You may have your own preferred setup for nginx; you just need to add a single option:

    $ ./configure --add-module=../uwsgi-0.9.4.2/nginx/
    

    Now compile the web server:

    $ make
    

    This will create an nginx binary in objs/; install this into the virtualenv:

    $ mv objs/nginx $VIRTUAL_ENV/bin/nginx
    

You now have all the required (non-Python) software to deploy a Django project under nginx/uWSGI. Keep the pkg/ directory and its contents for now; you’ll need them during configuration.

Configuration

There are a few parts to configure before you can run the web server. nginx is configured using a standalone plain-text configuration file (nginx.conf), whereas uWSGI, in ROCK_SOLID mode, uses only command-line options. Before considering any of this, however, it’s best to take a look at the structure of the deployment. I like to put my Django project directly under the virtualenv, like so:

uwsgitest/
|-- PROJECT_ROOT/
|   |-- apps/
|   |-- etc/ -> etcs/DEPLOYMENT_NAME
|   |-- etcs/
|   |-- libs/
|   |-- media/
|   |-- settings/
|   |-- templates/
|   |-- .hgignore
|   |-- README
|   |-- REQUIREMENTS
|   |-- __init__.py
|   `-- urls.py
|-- bin/
|-- include/
|-- lib/
`-- pkg/

This follows the layout discussed in my previous blog post on Django project conventions. You should do the usual set-up as described in that post; symlink the project root onto the site path, add DJANGO_SETTINGS_MODULE to the bin/activate script, et cetera.

And now for the main event.

  1. Create an etcs/production directory to keep plain-text configs in:

    $ cd $VIRTUAL_ENV/PROJECT_ROOT
    $ mkdir -p etcs/production
    

    Symlink PROJECT_ROOT/etc/ to PROJECT_ROOT/etcs/production/, to represent the currently-activated config directory:

    $ ln -s $PROJECT_ROOT/etcs/production $PROJECT_ROOT/etc
    

    This whole architecture is so that you can create different sets of plain-text configs for different deployments. Again, read my blog post for more information.

  2. Now to configure nginx. There are a couple of required files which are imported into the config; you’ll need to add these to the config directory. Copy the file mime.types from the nginx tarball into etcs/production:

    $ cp $VIRTUAL_ENV/pkg/nginx-0.7.65/conf/mime.types etcs/production/
    

    Then, add uwsgi_params from the uWSGI tarball:

    $ cp $VIRTUAL_ENV/pkg/uwsgi-0.9.4.2/nginx/uwsgi_params etcs/production/
    
  3. What follows is the meat of the nginx configuration. Make sure you read and understand it thoroughly; there’s nothing particularly difficult about it:

    worker_processes  1;
    pid               pid/nginx.pid;
        
    error_log         log/nginx-error.log;
        
    events {
      worker_connections  1024;
    }
        
    http {
      # Some sensible defaults.
      include               mime.types;
      default_type          application/octet-stream;
      keepalive_timeout     10;
      client_max_body_size  20m;
      sendfile              on;
      gzip                  on;
          
      # Directories
      client_body_temp_path tmp/client_body/  2 2;
      fastcgi_temp_path     tmp/fastcgi/;
      proxy_temp_path       tmp/proxy/;
      uwsgi_temp_path       tmp/uwsgi/;
          
      # Logging
      access_log            log/nginx-access.log  combined;
          
      # uWSGI serving Django.
      upstream django {
        # Distribute requests to servers based on client IP. This keeps load
        # balancing fair but consistent per-client. In this instance we're
        # only using one uWGSI worker anyway.
        ip_hash;
        server unix:sock/uwsgi.sock;
      }
          
      server {
        listen      80;
        server_name example.com;
        charset     utf-8;
            
        # Django admin media.
        location /media/admin/ {
          alias lib/python2.6/site-packages/django/contrib/admin/media/;
        }
            
        # Your project's static media.
        location /media/ {
          alias PROJECT_ROOT/media/;
        }
            
        # Finally, send all non-media requests to the Django server.
        location / {
          uwsgi_pass  django;
          include     uwsgi_params;
        }
      }
    }
    

    You should put this in etcs/production/nginx.conf; also, make sure you replacePROJECT_ROOTexample.com and python2.6 with the appropriate values.

  4. You now need to create the necessary directories. From the root of your virtualenv:

    $ mkdir tmp/ sock/ pid/ log/
    
  5. Finally, you’ll need a module containing a WSGI callable called application. This is used by uWSGI. You can just put the following in a file called wsgi.py in your PROJECT_ROOT:

    import django.core.handlers.wsgi
        
    application = django.core.handlers.wsgi.WSGIHandler()
    

And that’s it for configuration!

Execution

Of course, another key step in the whole process is running nginx and uWSGI. Most people have preferred ways of running daemons; I like to use Supervisor, but others prefer init or daemontools. I don’t really want to put a whole config here; instead I’ll tell you what you need to run.

nginx

The command for nginx is very simple. From the root of your virtualenv:

$ bin/nginx -p `pwd`/ -c PROJECT_ROOT/etc/nginx.conf

You may need to run nginx as root (e.g. via sudo) to listen on port 80; I tend to just try running it on port 8080 while I’m setting it up, so I can avoid permissions problems in the beginning. I won’t try and dictate how you should organize your users, groups and permissions — nginx is pretty flexible, anyway.

uWSGI

As I mentioned before, uWSGI’s ‘configuration’ is made up of the command-line arguments you choose to pass to it. See the output of uwsgi -h for detailed information. Here’s a very simple example (but one which works fine):

$ bin/uwsgi -p 4 -s sock/uwsgi.sock -H `pwd`/ PROJECT_NAME.wsgi

The breakdown:

  • -p 4 tells uWSGI to run four worker processes.
  • -s sock/uwsgi.sock specifies the UNIX socket file to use.
  • -H `pwd/` tells uWSGI to use the current virtualenv.
  • PROJECT_NAME.wsgi is the name of a module with an application callable (i.e. your WSGI app).

Just run nginx and uWSGI as detailed above and try visiting your site. It should all work perfectly. You might want to try running a HTTP benchmark or load tester on it, to see how it stacks up.

Also, refer to: http://www.westphahl.net/blog/2010/4/8/running-django-nginx-and-uwsgi/

 

 

分享到:
评论

相关推荐

    Nginx+Uwsgi+Django+Vue部署

    Nginx+Uwsgi+Django(python3)+Vue部署,一步步实现。网上找了N多篇文章都没成功,特意记录,以免其他同学踩坑

    解决nginx+uwsgi部署Django的所有问题(小结)

    本篇文章将详述如何解决使用Nginx和uWSGI部署Django应用过程中遇到的问题。 首先,Nginx是一个轻量级的HTTP服务器和反向代理服务器,它的特点是性能高效、稳定,并且配置简单。在Django应用部署中,Nginx主要负责...

    五步教你实现使用Nginx+uWSGI+Django方法部署Django程序1

    五步教你实现使用Nginx+uWSGI+Django方法部署...本文主要介绍了使用Nginx+uWSGI+Django方法部署Django程序的五个步骤,包括环境介绍、安装uwsgi、测试uwsgi、配置Django和连接Django和uwsgi,实现简单的WEB服务器。

    用Django全栈开发——29. 部署之阿里云CentOS+Nginx+uWsgi+Django.html

    阿里云CentOS+Nginx+uWsgi+Django部署Django,《用Django全栈开发》系列文章最后一篇,感兴趣的同学可以查看。

    Ubuntu16.04下Nginx+uwsgi部署Django项目

    对于Python初学者,部署会踩很多,这里是自己初学时的经验,所以粘出来和大家分享

    nginx+uwsgi启动Django项目的详细步骤

    在部署Django项目时,使用Nginx和uWSGI作为前端和应用服务器是一种常见且高效的做法。本文将详细介绍使用Nginx作为Web服务器,uWSGI作为应用服务器,以及Django框架本身,来启动和运行Django项目的详细步骤。 首先...

    nginx_uwsgi部署1

    本文主要介绍如何使用Nginx和uWSGI部署Django应用,以下是详细的步骤和相关知识点: 1. **Django设置** - `DEBUG`:在`settings.py`中,`DEBUG=False`意味着关闭调试模式。当`DEBUG=True`时,Django会自动处理静态...

    nginx+uWSGI部署Django项目.zip

    3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿...

    Ubuntu12.04 nginx python uwsgi Django安装步骤

    Ubuntu 12.04 下安装 Nginx、Python、uWSGI 和 Django 的步骤 在本文中,我们将介绍如何在 Ubuntu 12.04 环境下安装 Nginx、Python、uWSGI 和 Django。这些技术栈组合是非常流行的 Web 应用程序开发环境。 一、...

    用uwsgi+daphne+Nginx+supervisor部署Django项目.docx

    ### 使用uwsgi+daphne+Nginx+supervisor部署Django项目的详细步骤 #### 一、概述 在本文档中,我们将详细介绍如何在Linux环境下利用uwsgi、daphne、Nginx以及supervisor来部署Django项目。这种方式能够有效地提高...

    openshift-diy-nginx-uwsgi-django:使用 Python 2.7.4、Nginx、uWSGI 和 Django 框架的 Openshift diy 应用程序

    使用 DIY 和 Postgresql 8.4 墨盒创建 Openshift 应用程序(也适用于 MySQL 和 SQLite 开箱即用): $ rhc app create <exampleapp> diy-0.1 postgresql-8.4 $ cd $ git remote add upstream -m master git://...

    Centos+Nginx+UWSGI+Django搭建高性能WEB服务器

    本文将详细介绍如何在CentOS系统上搭建使用Nginx作为Web服务器、UWSGI作为应用服务器、Django作为后端框架的高性能Web应用。 ### 关键技术点概述 1. **CentOS**: CentOS是基于Red Hat Enterprise Linux构建的一个...

    uwsgi+daphne+Nginx+supervisor部署Django

    在本文中,我们将详细介绍如何使用 uwsgi、daphne、Nginx 和 supervisor 部署 Django 项目。这些技术栈组合可以提供高性能、可扩展的 Web 服务。 uwsgi 介绍 uwsgi 是一个基于 Unix 的高性能 Web 服务器,它可以...

    nginx+uwsgi部署步骤.md

    nginx+uwsgi部署步骤.md

    Nginx+Uwsgi+Django 项目部署到服务器的思路详解

    在部署基于Nginx、Uwsgi和Django的Web应用程序时,首先需要理解这个架构的核心组件及其作用。Nginx是一个高性能的反向代理服务器,用于处理HTTP和HTTPS请求,提供静态文件服务,以及负载均衡等功能。Uwsgi则是一个...

    腾讯云部署Django+Nginx+uWSGI+SimpleUI.解决 .svg文件不能显示问题

    我们将使用Django、Nginx、uWSGI和SimpleUI这些技术,并且会详细解释每个组件的作用以及配置过程。 首先,Django是一个Python开发的高级Web框架,用于构建高效、可扩展的Web应用。而uWSGI是一个高性能的应用服务器...

    nginx+uwsgi+django环境搭建的方法步骤

    在本文中,我们将探讨如何搭建一个基于Nginx、uWSGI和Django的Web服务环境。这个组合是部署高性能Python Web应用的常见选择,因为它提供了高效的负载均衡、静态文件处理以及与后端应用的稳定连接。 首先,我们需要...

    Django+Nginx+UWSGI+virtualenv项目部署

    通过上述步骤,我们成功地在服务器上部署了一个基于Django的Web应用,并配置了Nginx和uWSGI作为前端和后端服务器。这种部署方式不仅可以提高应用的性能和稳定性,还能增强系统的安全性。此外,通过使用virtualenv来...

Global site tag (gtag.js) - Google Analytics