又部署了一遍 Django

2016-07-29
  • Ubuntu – 14.04
  • Django – 1.9.8
  • Nginx – 1.4.6
  • uwsgi – 2.0.13.1

ubuntu 上要依赖三个东西 python-dev, libxml2-dev, pcre。

libxml2-dev 是用来解析 uwsgi 的 .xml 脚本的,pcre 是 Perl 的正则表达式解析库,Django 解析 URL 的,python-dev 我也不知道是干什么的

Nginx 开个 80 端口,uwsgi_pass 传给 8001 这个端口,uwsgi 在通过这里把 Django 跑起来。

1. Nginx 配置 /etc/nginx/sites-enabled/my_app.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name IP OR DOMAIN; # substitute your machine's IP address or FQDN
charset utf-8;

# max upload size
client_max_body_size 75M; # adjust to taste

# logs
access_log /home/chen/my_app/logs/access.log;
error_log /home/chen/my_app/logs/error.log;

# Django media
location /media {
alias /home/chen/my_app/media; # your Django project's media files - amend as required
}

location /static {
alias /home/chen/my_app/static; # your Django project's static files - amend as required
}

# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass IP OR DOMAIN:8001;
include /home/chen/my_app/uwsgi_params; # the uwsgi_params file you installed
}
}

2. Django 项目下需要从 Nginx 源码中复制出一份 uwsgi_params

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;

uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REQUEST_SCHEME $scheme;
uwsgi_param HTTPS $https if_not_empty;

uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;

3. Django 项目下需要一个 my_app_wsgi.py

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-

import os
import sys

reload(sys)
sys.setdefaultencoding('utf8')

from django.core.wsgi import get_wsgi_application # Django 1.7 前是 from django.core.handlers.wsgi import WSGIHandler

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings") # “你的项目.settings”
application = get_wsgi_application() # 1.7以前是 application = WSGIHandler()

4. uwsgi 启动脚本 my_app_socket.xml 放在 Django 项目下

1
2
3
4
5
6
7
<uwsgi>
<socket>IP OR DOMAIN:8001</socket>
<chdir>/home/chen/my_app</chdir>
<module>my_app_wsgi</module>
<processes>4</processes>
<daemonize>/home/chen/my_app/uwsgi.log</daemonize>
</uwsgi>

最后重启 Nginx,启动 uwsgi 的脚本 load Django App

1
2
sudo nginx -s reload
uwsgi -x my_app_socket.xml