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。

  這下就行了。

相關文章
相關標籤/搜索