django 部署,gunicorn、virtualenv、nginx
1. Update Your System
- apt-get update
- apt-get upgrade
- apt-get install aptitude
2. Install and create application database 这个我没有测试我使用的是 mysql
- apt-get install postgresql postgresql-contrib
- su – postgres
- postgres@django:~$createuser –interactive -P
- Enter name of role to add: hello_django
- Enter password for new role:
- Enter it again:
- Shall the new role be a superuser? (y/n) n
- Shall the new role be allowed to create databases? (y/n) n
- Shall the new role be allowed to create more new roles? (y/n) n
- postgres@django:~$createdb –owner hello_django hello
- postgres@django:~$logout
3. Create Application User
- groupadd webapps
- useradd -g webapps -s /bin/bash -d /webapps/hello_django hello
- useradd -g webapps -s /bin/bash -d /webapps/goodbye_django goodbye
4. Install Virtualenv and create environment for your application
- apt-get install python-virtualenv libmysqlclient-dev
- apt-get install python-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev g++ libpq-dev
- mkdir -p /webapps/hello_django/
- mkdir -p /webapps/goodbye_django/
- chown hello:webapps /webapps/hello_django/
- chown goodbye:webapps /webapps/goodbye_django/
- As the application user create a virtual Python environment in the application directory:
- su – hello
- hello@django:~$ cd /webapps/hello_django/
- hello@django:~$ virtualenv .
- New python executable in hello_django/bin/python
- Installing distribute…………..done.
- Installing pip…………………done.
- hello@django:~$ source bin/activate
- (hello_django)hello@django:~$
- Your environment is now activated and you can proceed to install Django inside it.
- (hello_django)hello@django:~$ pip install django
- Downloading/unpacking django
- (…)
- Installing collected packages: django
- (…)
- Successfully installed django
- Cleaning up…
- Your environment with Django should be ready to use. Go ahead and create an empty Django project.
- (hello_django)hello@django:~$ django-admin.py startproject hello
- You can test it by running the development server:
- (hello_django)hello@django:~$ cd hello
- (hello_django)hello@django:~$ python manage.py runserver 0.0.0.0:8000 (或者使用IP)
- Validating models…
- 0 errors found
- June 09, 2013 – 06:12:00
- Django version 1.5.1, using settings 'hello.settings'
- Development server is running at http://0.0.0.0:8000/
- Quit the server with CONTROL-C.
- You should now be able to access your development server from http://IP:8000
5. Allowing other users write access to the application directory
Your application will run as the user hello, who owns the entire application directory. If you want regular user to be able to change application files, you can set the group owner of the directory to users and give the group write permissions.
- chown -R hello:users /webapps/hello_django
- chmod -R g+w /webapps/hello_django
- If you're not a member of users, you can add yourself to the group with this command:
- usermod -a -G users `whoami`
6. Configure PostgreSQL to work with Django
- apt-get install libpq-dev python-dev
- Install psycopg2 database adapter:
- (hello_django)hello@django:~$ pip install psycopg2
- You can now configure the databases section in your settings.py. Change it to:
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.postgresql_psycopg2′,
- 'NAME': 'hello',
- 'USER': 'hello_django',
- 'PASSWORD': 'password',
- 'HOST': 'localhost',
- 'PORT':
- ”, # Set to empty string for default.
- }
- }
- And finally build the initial database for Django:
- (hello_django)hello@django:~$ python manage.py syncdb
- mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
7. Install and configure Gunicorn
- (hello_django)hello@django:~$ pip install gunicorn
- Now that you have gunicorn, you can test whether it can serve your Django application by running the following command:
- (hello_django)hello@django:~$ gunicorn hello.wsgi:application -–bind 0.0.0.0:8001
- You should now be able to access the Gunicorn server from http://0.0.0.0:8001 . I intentionally changed port 8000 to 8001 to force your browser to establish a new connection.
- Gunicorn is installed and ready to serve your app. Let's set some configuration options to make it more useful. I like to set a number of parameters, so let's put them all into a small BASH script, which I save as bin/gunicorn_start
cat bin/gunicorn_start
- #!/bin/bash
- NAME="hello_app" # Name of the application
- DJANGODIR=/webapps/hello_django/hello # Django project directory
- SOCKFILE=/webapps/hello_django/run/gunicorn.sock # we will communicte using this unix socket
- USER=hello # the user to run as
- GROUP=webapps # the group to run as
- NUM_WORKERS=3 # how many worker processes should Gunicorn spawn
- TIMEOUT=600
- DJANGO_SETTINGS_MODULE=hello.settings # which settings file should Django use
- DJANGO_WSGI_MODULE=hello.wsgi # WSGI module name
- PORT=8000
- SERVER_NAME=0.0.0.0
- echo "Starting $NAME as `whoami`"
- # Activate the virtual environment
- cd $DJANGODIR
- source ../bin/activate
- export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
- export PYTHONPATH=$DJANGODIR:$PYTHONPATH
- # Create the run directory if it doesn't exist
- RUNDIR=$(dirname $SOCKFILE)
- test -d $RUNDIR || mkdir -p $RUNDIR
- # Start your Django Unicorn
- # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
- exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
- --name $NAME \
- --workers $NUM_WORKERS \
- --timeout $TIMEOUT \
- --user=$USER --group=$GROUP \
- --log-level=debug \
- --bind=unix:$SOCKFILE
#如果你需要直接用 IP:port 这样的方式访问查看 那么就这么写 ,主要是测试是否可以访问 用上面的,不可以直接在浏览器中查看需要借助 nginx 等 反向代理的方法看。 配置 在 9 , 安装nginx 中。 在没有安装Nginx前注释 --bind=unix:$SOCKFILE 有了Nginx后注释 #--bind=$SERVER_NAME:$PORT
当前也可以就用--bind=$SERVER_NAME:$PORT 的方式;
Set the executable bit on the gunicorn_start script:chmod u+x bin/gunicorn_start
You can test your gunicorn_start script by running it as the user hello.
su – hello
hello@django:~$ bin/gunicorn_start
In order for the –name argument to have an effect you need to install a Python module called setproctitle. To build this native extension pip needs to have access to C header files for Python. You can add them to your system with the python-dev package and then install setproctitle.
(hello_django)hello@django:~$ pip install setproctitle
Now when you list processes, you should see which gunicorn belongs to which application.
ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
.....
hello 12977 12643 0 04:26 pts/1 00:00:00 /webapps/hello_django/bin/python /webapps/hello_django/hello/../bin/gunicorn hello.wsgi:application --name hello_app --workers 3 --timeout 600 --user=hello --group=webapps --log-level=debug --bind=0.0.0.0:8000
hello 12988 12977 0 04:26 pts/1 00:00:00 /webapps/hello_django/bin/python /webapps/hello_django/hello/../bin/gunicorn hello.wsgi:application --name hello_app --workers 3 --timeout 600 --user=hello --group=webapps --log-level=debug --bind=0.0.0.0:8000
hello 12989 12977 0 04:26 pts/1 00:00:00 /webapps/hello_django/bin/python /webapps/hello_django/hello/../bin/gunicorn hello.wsgi:application --name hello_app --workers 3 --timeout 600 --user=hello --group=webapps --log-level=debug --bind=0.0.0.0:8000
hello 12990 12977 0 04:26 pts/1 00:00:00 /webapps/hello_django/bin/python /webapps/hello_django/hello/../bin/gunicorn hello.wsgi:application --name hello_app --workers 3 --timeout 600 --user=hello --group=webapps --log-level=debug --bind=0.0.0.0:8000
root 13019 9050 0 04:27 pts/2 00:00:00 grep --color=auto gunicorn
8. Configure Monitoring using Supervisor
apt-get install supervisor
When Supervisor is installed you can give it programs to start and watch by creating configuration files in the /etc/supervisor/conf.d directory. For our hello application we’ll create a file named /etc/supervisor/conf.d/hello.conf with this content:
vim /etc/supervisor/conf.d/hello.conf
- [program:hello]
- command = /webapps/hello_django/bin/gunicorn_start ; Command to start app
- user = hello ; User to run as
- stdout_logfile = /webapps/hello_django/logs/gunicorn_supervisor.log ; Where to write log
- messages
- redirect_stderr = true ; Save stderr in the same log
- environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8
Create the file to store your application’s log messages:hello@django:~$ mkdir -p /webapps/hello_django/logs/
hello@django:~$ touch /webapps/hello_django/logs/gunicorn_supervisor.log
After you save the configuration file for your program you can ask supervisor to reread configuration files and update (which will start your the newly registered app).
supervisorctl command [all]|[appname] 启动/关闭/重启 .. 指定/所有 supervisor 管理的程序进程
supervisorctl reread
hello: available
supervisorctl update
hello: added process group
You can also check the status of your app or start, stop or restart it using supervisor.
supervisorctl status hello
hello RUNNING pid 18020, uptime 0:00:50
supervisorctl stop hello
hello: stopped
supervisorctl start hello
hello: started
supervisorctl restart hello
hello: stopped
hello: started
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
多个 gunicorn 需注意一点 supervisorctl 需要重新加载以及更新
Reread the configuration files and update Supervisor to start the apps:
supervisorctl update例如: 上面建立的 goodbye_django 过程一致
su – goodbye
cd /webapps/goodbye_django/
goodbye@django:~$ virtualenv .
New python executable in goodbye_django/bin/python
Installing distribute…………..done.
Installing pip…………………done.goodbye@django:~$ source bin/activate
(goodbye_django)goodbye@django:~$
Your environment is now activated and you can proceed to install Django inside it.
(goodbye_django)goodbye@django:~$ pip install django
...
...
过程省略
(goodbye_django)goodbye@django:~$ django-admin.py startproject goodbye
(goodbye_django)goodbye@django:~$ cd goodbye
(goodbye_django)goodbye@django:~$ python manage.py runserver 0.0.0.0:8001
... 省略
You should now be able to access your development server from http://IP:8001
出现django 的It worked! 就成功了
安装 gunicorn (我采用的是单独的虚拟环境 virtualenv是Python中常用的虚拟环境。可以理解为属于Python的虚拟机 )
(goodbye_django)goodbye@django:~$ pip install gunicorn
....
....
vim bin/gunicorn_start
- #!/bin/bash
- NAME="goodbye_app" # Name of the application
- DJANGODIR=/webapps/goodbye_django/goodbye # Django project directory
- SOCKFILE=/webapps/goodbye_django/run/gunicorn.sock # we will communicte using this unix socket
- USER=goodbye # the user to run as
- GROUP=webapps # the group to run as
- NUM_WORKERS=3 # how many worker processes should Gunicorn spawn
- TIMEOUT=600
- DJANGO_SETTINGS_MODULE=goodbye.settings # which settings file should Django use
- DJANGO_WSGI_MODULE=goodbye.wsgi # WSGI module name
- PORT=8001
- SERVER_NAME=0.0.0.0
- echo "Starting $NAME as `whoami`"
- # Activate the virtual environment
- cd $DJANGODIR
- source ../bin/activate
- export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
- export PYTHONPATH=$DJANGODIR:$PYTHONPATH
- # Create the run directory if it doesn't exist
- RUNDIR=$(dirname $SOCKFILE)
- test -d $RUNDIR || mkdir -p $RUNDIR
- # Start your Django Unicorn
- # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
- exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
- --name $NAME \
- --workers $NUM_WORKERS \
- --timeout $TIMEOUT \
- --user=$USER --group=$GROUP \
- --log-level=debug \
- --bind=unix:$SOCKFILE
- ###--bind=0.0.0.0:8001
先杀掉之前启动的进程
(goodbye_django)goodbye@django:~$ bin/gunicorn_startcat /etc/supervisor/conf.d/goodbye.conf[program:goodbye]
command = /webapps/goodbye_django/bin/gunicorn_start ; Command to start app
user = goodbye ; User to run as
autostart = true ; 在 supervisord 启动的时候也自动启动
startsecs = 5 ; 启动 5 秒后没有异常退出,就当作已经正常启动了
autorestart = true ; 程序异常退出后自动重启
redirect_stderr = true ; 把 stderr 重定向到 stdout,默认 false
stdout_logfile_maxbytes = 100MB ; stdout 日志文件大小,默认 50MB
stdout_logfile_backups = 20 ; stdout 日志文件备份数
stdout_logfile = /webapps/goodbye_django/logs/gunicorn_supervisor.log ; Where to write log messages
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8
logfile 自定义如果不存在先创建 注意所属用户和组
mkdir -p mkdir -p /webapps/hello_django/logs/
将任务添加到 supervisord
supervisorctl reread
goodbye: available
supervisorctl update
goodbye: added process group
9. Install and configure Nginx for web hosting
- aptitude install libpcre3 libpcre3-dev
- aptitude install libssl-dev openssl
- aptitude install libxslt-dev
- aptitude install libgd2-xpm libgd2-xpm-dev
- aptitude install libgeoip-dev
- aptitude install pcre
- pcre-config --version
- cd /usr/local/src
- wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
- tar zxf ngx_cache_purge-2.3.tar.gz
- wget http://nginx.org/download/nginx-1.9.0.tar.gz
- tar zxf nginx-1.9.0.tar.gz
- cd nginx-1.9.0
- ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module --with-http_realip_module --add-module=/usr/local/src/ngx_cache_purge-2.3 --with-http_image_filter_module --with-http_dav_module --with-http_flv_module --with-http_random_index_module --with-http_secure_link_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 --with-http_spdy_module --with-http_gunzip_module --with-http_auth_request_module --with-http_geoip_module
- make
- make install
- /usr/local/nginx/sbin/nginx -t
- nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
- nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
- 具体细节参照之前的debain nginx 安装 note.php?serial_number=203 nginx自启动 note.php?serial_number=236
-
upstream hello_app_server {
# fail_timeout=0 means we always retry an upstream even if it failed - # to return a good HTTP response (in case the Unicorn master nukes a
- # single worker for timing out).
- server unix:/webapps/hello_django/run/gunicorn.sock fail_timeout=0;
- #server 127.0.0.1:8000;
- }
- server {
- listen 80;
- server_name world_alive.com;
- client_max_body_size 100M;
- access_log /webapps/hello_django/logs/nginx-access.log;
- error_log /webapps/hello_django/logs/nginx-error.log;
- location /static/ {
- alias
- /webapps/hello_django/static/;
- }
- location /media/ {
- alias
- /webapps/hello_django/media/;
- }
- location / {
- proxy_set_header
- X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header Host $http_host;
- proxy_redirect off;
- if (!-f
- $request_filename) {
- proxy_pass http://hello_app_server;
- break;
- }
- }
- # Error pages
- error_page 500 502 503 504 /500.html;
- location = /500.html {
- root /webapps/hello_django/static/;
- }
- }
没有评论