這片文章描述瞭如何部署一個基於Django的web服務器,參考了https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html並進行了精簡和補充。css
Nginx和uWSGI是很是流行的web服務器部署組件:html
Nginx ----開源的、高性能的HTTP服務器、反向代理服務器、IMAP/POP3服務器;python
uWSGI ----web服務器,它使用的WSGI協議是一種服務器網關接口,是web服務器和web應用之間的通訊規範;nginx
Django ----開放源代碼的Web應用框架,由Python寫成,採用了MVC的框架模式。git
上述組件之間的通訊流程以下:github
the web client <-> nginx <-> the socket <-> uwsgi <-> Djangoweb
安裝virtualenv ---- pip install virtualenv;django
建立虛擬環境 ---- virtualenv env_django;cd env_django;source bin/activate;cd ../瀏覽器
安裝 Django ---- pip install Django;服務器
安裝git ----yum install git;
下載Django項目 ---- git clone https://github.com/dongguadan/mysite.git;
進入項目目錄 ---- cd mysie
安裝python-dev ---- yum install python-dev.x86_64;
安裝uwsgi ---- pip install uwsgi
安裝nginx ---- yum install nginx;
在mysite目錄下準備uwsgi_params、mysite_nginx.conf兩個文件:
---- cp /etc/nginx/uwsgi_params ./mysite/;
---- 建立mysite_nginx.conf文件並輸入下面的內容
# mysite_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
# server unix:///home/projects/mysite/mysite.sock; # for afile 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 8000;
# 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/projects/mysite/media; # your Django project's media files - amend as required
}
location /static {
alias / home/projects/mysite/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/projects/mysite/uwsgi_params; # the uwsgi_params file you installed
}
}
---- 創建軟鏈接,sudo ln -s ~/ home/projects/mysite/mysite_nginx.conf /etc/nginx/conf.d/
打開8000、8001端口並啓動nginx和uwsgi ---- sudo /sbin/nginx;uwsgi –socket :8001 –module mysite.wsgi;
瀏覽器輸入ip:8000,能夠看到網頁了。
Faq:
1 阿里雲界面能夠配置開放端口
2 uwsgi 須要python-dev的支持
3 django ALLOWED_HOSTS = ['*'] 開放ip地址
4 新版nginx沒有site_enabled這個目錄,改成conf.d
5 django+nginx 不必定支持unix socket的方法,能夠改成127.0.0.1:port的方法
6 nginx默認是以nginx的權限登錄的,因此訪問不到admin權限下的css文件:出現css 403的錯誤;將nginx的worker啓動用戶改成admin就能夠了