Debian环境 Python2.7.9 + Django1.8 + Nginx1.6 + uWSGI + MySQL 最新配置指南


Debian6.0系统自带的nginx python版本过低,所以首先是自定义安装nginx1.6.x 和 python2.7.9
一、
apt-get update
apt-get upgrade
 
#解决“E: Release file expired, ignoring”问题,用下面命令代替apt-get update
apt-get -o Acquire::Check-Valid-Until=false update

二、安装nginx 参考:http://nginx.org/en/linux_packages.html#stable

For Debian/Ubuntu, in order to authenticate the nginx repository signature and to eliminate warnings about missing PGP key during installation of the nginx package, it is necessary to add the key used to sign the nginx packages and repository to the apt program keyring. Please download this key from our web site, and add it to the apt program keyring with the following command:html

sudo apt-key add nginx_signing.key
更新sources.list
在底部添加两行:
deb http://nginx.org/packages/debian/ squeeze nginx
deb-src http://nginx.org/packages/debian/ squeeze nginx
 

执行命令,安装nginx:python

 
apt-get update
apt-get install nginx
 
安装成功后提示:
Thanks for using nginx!

Please find the official documentation for nginx here:
* http://nginx.org/en/docs/

Commercial subscriptions for nginx are available on:
* http://nginx.com/products/

----------------------------------------------------------------------
Setting up nginx (1.6.2-1~squeeze) ...
PS:nginx默认安装在/etc/nginx中,其相关的配置文件也在此处
如今就能够用/etc/init.d/nginxstart来启动nginx服务了
访问localhost就会显示nginx欢迎界面。

四、安装Mysql:
 
apt-get install mysql-server
 
安装成功后: 

在/etc/mysql/my.cnf里面能够修改一些属性。

  原来有这么一行:bind-address = 127.0.0.1mysql

 

  意思是限定只有本机才能访问,愿意是为了保证数据安全。如今想要使得远程的机器可以访问MySQL数据库服务,就能够经过改bind-address来实现, 两种方式:linux

 

  a. bind-address = 0.0.0.0nginx

 

  b. 直接把bind-address这一行注释掉web

 

  这样作完以后,执行如下命令:sql

 
/etc/init.d/mysql stop
/etc/init.d/mysql start

 

 

 这样几步作完以后,再赋予远程机器访问权限:数据库

mysql -u root -p
Enter password:root
  mysql > GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY 'root_password' WITH GRANT OPTION;

上面这条命令的意思是容许任何IP地址(%是通配符)的电脑用root账户和密码(root_password)来访问这个MySQL Server。django

 

三、升级Python 到2.7.9 并配置好基础运行环境,主要是pip工具环境, 这一步至关关键,花费了我不少精力,所以单独开博来介绍!
浏览器

见另外一篇文章http://www.cnblogs.com/jaxthon/p/4393016.html

  python2.7.9及其基础环境配置好后,就能够用pip为所欲为的安装相关软件了

 

四、使用pip安装virtualenv     [ 此步可选 ]

pip install virtualenv
#virtualenv uwsgi-tutorial
#cd uwsgi-tutorial
#source bin/activate

 

五、使用pip安装Django
# pip install Django
Collecting Django
  Downloading Django-1.8-py2.py3-none-any.whl (6.2MB)
    100% |################################| 6.2MB 20kB/s
Installing collected packages: Django

Successfully installed Django-1.8

六、使用pip安装uwsgi

#pip install uwsgi

#ln -s /usr/local/python2.7.9/bin/uwsgi /usr/bin/uwsgi

 

七、进入Django代码目录(/home/john/www/htweb ),运行  python manage.py runserver, 结果报错:

    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

缘由是没有安装MySqldb-python,从官网https://pypi.python.org/pypi/MySQL-python/1.2.5上下载

解压后, python setup.py install 安装,安装成功后,运行python manage.py runserver, 又报一样的错误:django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

 

主要缘由是:没有安装libmysqlclient-dev

接下来,安装libmysqlclient-dev

sudo apt-get install libmysqlclient-dev

找到mysql_config文件的路径

sudo updatedb locate mysql_config

mysql_config的位置为:/usr/bin/mysql_config

在mysql-python源码包下找到:setup_posix.py 文件,而后找到文件中的 mysql_config.path 将其值改成:/usr/bin/mysql_config,而后 sudo python setup.py install ,就ok了

再次运行  python manage.py runserver, 结果又报错,缘由是我使用了Image包没有安装:

ImportError: No module named Image
(uwsgi-tutorial)root@iZ25xo8uaamZ:/home/john/www/htweb# pip install Image
Collecting Image
  Downloading image-1.3.4.tar.gz
Collecting pillow (from Image)
  Downloading Pillow-2.8.1.tar.gz (9.0MB)
    18% |#####                           | 1.6MB 71kB/s eta 0:01:43
。。。。。。
  Running setup.py install for Image
Successfully installed Image-1.3.4 pillow-2.8.1
再次运行  python manage.py runserver, 结果仍是不行,只好将models.py中的Image包去掉!

这下终于运行成功!!

解决Image没法导入及相关图片decode出错的问题:

a、models.py中使用“from PIL import Image” 代替 import Image

b、从新安装libjpeg or libjpeg-dev 

apt-get install libjpeg-dev

c、从新安装Pillow

pip uninstall Pillow

pip install Pillow

解决!

 

 

八、运行uwsgi --http :8000 --module 'your project packagename'.wsgi,详见https://uwsgi.readthedocs.org/en/latest/tutorials/Django_and_nginx.html#install-uwsgi-system-wide

浏览器中输入:domainname:8000/admin,至此能够运行django程序了!但静态文件还没法加载!

八、终于等到nginx上场了,用它来Hold 静态文件。

 在/etc/nginx/conf.d/中新建一个配置文件xxxx.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:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      9000;
    # the domain name it will serve for
    server_name  .example.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 /home/john/www/htweb/media;  # your Django project's media files - amend as required
    }
     location /static {
        alias  /home/john/www/htweb/static; # your Django project's static files - amend as required
    }

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

}

重启ngnix:

#/etc/init.d/nginx restart

OK,如今使用nginx和uwsgi运行Django应用

#  uwsgi --socket 8001 --module mysite.wsgi --chmod-socket=664

 至此,Django动态内容和静态内容均可以正常访问了!

 

请阅读 如下内容,进一步优化应用:

 

九、Using Unix sockets instead of ports

修改/etc/nginx/conf.d/xxxx.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:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      9000;
    # the domain name it will serve for
    server_name  .example.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 /home/john/www/htweb/media;  # your Django project's media files - amend as required
    }
     location /static {
        alias  /home/john/www/htweb/static; # your Django project's static files - amend as required
    }

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

}

重启ngnix:

#/etc/init.d/nginx restart

 开启uwsgi

uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=666

至此,Django动态内容和静态内容也能够正常访问了

ps:mysite.sock文件会在运行uwsgi命令后自动建立!

十、Configuring uWSGI to run with a .ini file

# mysite_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /home/john/www/mysite
# Django's wsgi file
module          = mysite.wsgi
# the virtualenv (full path)
#home            = /path/to/virtualenv  不用virtualenv ,所以将此行其注释掉

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10
# the socket (use the full path to be safe
socket          = /path/to/your/project/mysite.sock
# ... with appropriate permissions - may be needed
chmod-socket    = 664
# clear environment on exit
vacuum          = true

运行

uwsgi --ini mysite_uwsgi.ini

至此,Django动态内容和静态内容也能够正常访问了

 

PS:若是在virtualenv中运行以上步骤,那么退出virtualenv环境后,从新安装uwsgi,以下:

Install uWSGI system-wide

So far, uWSGI is only installed in our virtualenv; we’ll need it installed system-wide for deployment purposes.

Deactivate your virtualenv:

#deactivate

and install uWSGI system-wide:

sudo pip install uwsgi

# Or install LTS (long term support).
pip install http://projects.unbit.it/downloads/uwsgi-lts.tar.gz
uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file

十二、Make uWSGI startup when the system boots

 

先设置Emperor mode

小窍门:将ini文件放在/etc/uwsgi/vassals目录下,uwsgi会自动加载该目录下的全部ini文件,从而实现多个站点同时管理

uWSGI can run in ‘emperor’ mode. In this mode it keeps an eye on a directory of uWSGI config files, and will spawn instances (‘vassals’) for each one it finds.

Whenever a config file is amended, the emperor will automatically restart the vassal.

# create a directory for the vassals
sudo mkdir /etc/uwsgi
sudo mkdir /etc/uwsgi/vassals
# symlink from the default config directory to your config file
sudo ln -s /path/to/your/mysite/mysite_uwsgi.ini /etc/uwsgi/vassals/
# run the emperor
uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

 

 

The last step is to make it all happen automatically at system startup time.

Edit /etc/rc.local and add:

/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

before the line “exit 0”.

And that should be it!

The options mean:

  • emperor: where to look for vassals (config files)
  • uid: the user id of the process once it’s started
  • gid: the group id of the process once it’s started

Check the site; it should be running.

Further configuration

It is important to understand that this has been a tutorial, to get you started. You do need to read the nginx and uWSGI documentation, and study the options available before deployment in a production environment.

Both nginx and uWSGI benefit from friendly communities, who are able to offer invaluable advice about configuration and usage.

nginx

General configuration of nginx is not within the scope of this tutorial though you’ll probably want it to listen on port 80, not 8000, for a production website.

You also ought to consider at having a separate server for non-Django serving, of static files for example.

uWSGI

uWSGI supports multiple ways to configure it. See uWSGI’s documentation and examples.

Some uWSGI options have been mentioned in this tutorial; others you ought to look at for a deployment in production include (listed here with example settings):

env = DJANGO_SETTINGS_MODULE=mysite.settings # set an environment variable pidfile = /tmp/project-master.pid # create a pidfile harakiri = 20 # respawn processes taking more than 20 seconds limit-as = 128 # limit the project to 128 MB max-requests = 5000 # respawn processes after serving 5000 requests daemonize = /var/log/uwsgi/yourproject.log # background the process & log 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

PS:

如何肯定当前的Python默认版本呢?很容易,直接经过下面的命令就能够了:

python --version

你们知道django是安装到python目录下的site-packages下的,可是这几个python目录下都没有site-packages这个文件夹,其实咱们能够先经过下面的命令定位一下:

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

上面的命令会在控制台上打印Python包路径,好比这里咱们可能得到dist-packages这个目录,切换到这个目录你就会发现django在那儿 啦。给django-admin.py加上权限,再作个符号链接,便于咱们之后操做(我这里Django在Python2.7下):

chmod 777 /usr/local/python2.7/lib/python2.7/site-packages/django/bin/django-admin.py
ln -s /usr/local/python2.7/lib/python2.7/site-packages/django/bin/django-admin.py /usr/local/bin



PS:Mysql http://www.linuxidc.com/Linux/2008-10/16513.htm

在Debian下安装MySQL,步骤以下:

  Debian: /# apt-get install mysql-server

  装好以后要缺省root是没有密码的,能够更改.

  Debian: /# mysqladmin -u root password $(yourpass)

  在/etc/mysql/my.conf里面能够修改一些属性。

  原来有这么一行:bind-address = 127.0.0.1

  意思是限定只有本机才能访问,愿意是为了保证数据安全。如今想要使得远程的机器可以访问MySQL数据库服务,就能够经过改bind-address来实现, 两种方式:

  1. bind-address = 0.0.0.0

  2. 直接把bind-address这一行注释掉

  这样作完以后,执行如下命令:

  /etc/init.d/mysql stop
  /etc/init.d/mysql start

  也有的说/etc/init/d/mysql reload, 可是有时候好像会出奇怪的问题,用上面两步比较好。Ossim官方网站上说改为 bind-address = *, 我试了,行不通,浪费我好多时间。

  这样几步作完以后,还赋予远程机器访问权限:

  mysql > GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY 'root_password' WITH GRANT OPTION;

  上面这条命令的意思是容许任何IP地址(%是通配符)的电脑用root账户和密码(root_password)来访问这个MySQL Server。

  这下就行了。

相关文章
相关标签/搜索