先開一貼,有空來總結下前段時間的網站部署情況。此次部署采用Gunicorn + Nginx + supervisor的組合在VPS環境中部署flask網站應用。
Ubuntu環境准備##
准備python環境
$ sudo apt-get update
$ sudo apt-get install python-dev python-pip python-virtualenv
然后安裝nginx
$ sudo apt-get install nginx
本網站在/home/jack/目錄下建立一個me的文件夾(我是直接git clone,此處說明下,克隆到哪,直接切換到相應的目錄Clone即可)
Gunicorn##
Gunicorn 綠色獨角獸 是一個Python WSGI UNIX的HTTP服務器。這是一個pre-fork worker的模型,從Ruby的獨角獸(Unicorn )項目移植。該Gunicorn服務器大致與各種Web框架兼容,只需非常簡單的執行,輕量級的資源消耗,以及相當迅速。
安裝Gunicorn
Gunicorn需要安裝在相應的virtualenv環境下,安裝前需要激活venv(在me文件夾下,執行 source venv/bin/actiavte)。
(venv) $ pip install gunicorn
運行Gunicorn
cd到你的項目根目錄下,此處為/me文件夾下:
(venv) $ gunicorn -w 4 -b 0.0.0.0:8000 wsgi:application
這使得服務器可以被公網IP訪問
注意:此處wsgi是一個flask實例引導的py文件,appliancation即創建的flask實例。此處和 Flask 項目中常用的 manage.py 引導腳本是沒有半點毛關系,需要做的是引入manage.py的flask實例。
拿本網站舉個例子吧, 很簡單的說:
#wsgi.py
from index import application
if __name__ == '__main__':
application.run()
Nginx 的配置##
關於Nginx后續再補充,直接編輯Nginx的默認配置文件。(/etc/nginx/site-avalidable/default)
建議先備份default文件
sudo cp /etc/nginx/site-avalidable/default /etc/nginx/sites-available/default.bak
server {
listen 80;
server_name example.org; # 這是HOST機器的外部域名,用地址也行(我直接填的IP地址)
location / {
proxy_pass http://127.0.0.1:8000; # 這里是指向 gunicorn host 的服務地址
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
完成配置Ngnix后需要重啟ngnix服務!
sudo service nginx restart
Gunicorn作為服務運行##
這里有兩種方法實現
- 配置成linux服務隨機啟動
- 使用supervisor管理gunicorn
目前使用supervisor配置成功,后面有時間繼續更新
這已經是我第一次補充了......................
首先安裝supervisor
pip install supervisor
配置supervisor
在/etc/supervisor/
下有兩個文件:文件夾,conf.d
;文件supervisord.conf
supersord.conf文件保持不動,尤其include內的內容,這引導接下來的配置的內容。
在conf.d
內創建項目的配置文件:me.conf
重新載入配置文件,並啟動me
$ sudo supervisorctl reload
$ sudo supervisorctl start me
查看運行狀態
$ sudo supervisorctl status
參考####
- http://edward.io/blog/flask-gunicorn-nginx.html
- http://www.cnblogs.com/Ray-liang/p/4837850.html
- http://www.jianshu.com/p/be9dd421fb8d
- http://www.lxway.com/49621091.htm
- https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-14-04
- http://beiyuu.com/vps-config-python-vitrualenv-flask-gunicorn-supervisor-nginx/
- http://defshine.github.io/deploy-flask-app-on-do.html
- http://www.onurguzel.com/how-to-run-flask-applications-with-nginx-using-gunicorn/
- https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-14-04