2014-10-06 155 views
2

我還是很新的Flask/Nginx/Gunicorn,因爲這只是我第二個使用這個組合的站點。我創建了一個基於Miguel Grinberg的tutorial的網站,因此我的文件結構與本教程完全相同。Nginx,Flask,Gunicorn 502錯誤

在我以前的瓶的應用程序,我的應用程序是在一個名爲app.py這樣一個文件,當我用Gunicorn我只是叫
gunicorn app:app

現在,我的新的應用程序分爲我用一個文件中的多個文件run.py開始應用程序,但我不知道我現在應該怎麼打電話給Gunicorn。我已閱讀其他問題和教程,但他們沒有奏效。當我運行gunicorn run:app並嘗試訪問站點時,出現502錯誤網關錯誤。

我覺得我的問題比Nginx或Flask更加Gunicorn,因爲如果我只鍵入./run.py,網站就可以工作。無論如何,我已經在下面包含了我的Nginx配置和一些其他文件。非常感謝你的幫助!

文件:run.py

#!flask/bin/python 
from app import app 
from werkzeug.contrib.fixers import ProxyFix 

app.wsgi_app = ProxyFix(app.wsgi_app) 
app.run(debug = True, port=8001) 

文件:app/views.py

from app import app 

@app.route('/') 
@app.route('/index') 
def index(): 
    posts = Post.query.order_by(Post.id.desc()).all() 
    return render_template('index.html', posts=posts) 

文件:nginx.conf

server { 
    listen 80; 
    server_name example.com; 

    root /var/www/example.com/public_html/app; 

    access_log /var/www/example.com/logs/access.log; 
    error_log /var/www/example.com/logs/error.log; 

    client_max_body_size 2M; 

    location/{ 
     try_files $uri @gunicorn_proxy; 
    } 

    location @gunicorn_proxy { 
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
     proxy_set_header Host $http_host; 
     proxy_redirect off; 
     proxy_pass http://127.0.0.1:8001; 
    } 
} 
+0

您是否檢查過您可以訪問http://127.0.0.1:8001?然後 - 我將「location @ gunicorn_proxy」更改爲「location /」(並註釋掉以前的位置部分) – soerium 2014-10-06 07:40:36

+0

@soerium我可以訪問127.0.0.1:8001,因爲當我從命令行運行我的應用程序時,Flask會打印'* Running在http://127.0.0.1:8001'上。 – Connie 2014-10-06 17:17:20

回答

2

正在發生的事情是gunicorn進口app.py當開發服務器正在運行。您只希望在文件直接執行時發生這種情況(例如,python app.py)。

#!flask/bin/python 
from app import app 
from werkzeug.contrib.fixers import ProxyFix 

app.wsgi_app = ProxyFix(app.wsgi_app) 

if __name__ == '__main__': 
    # You don't need to set the port here unless you don't want to use 5000 for development. 
    app.run(debug=True) 

一旦你做出這種改變,你應該能夠與gunicorn run:app運行應用程序。請注意,gunicorn默認使用端口8000。如果您希望在備用端口上運行(例如8001),則需要使用gunicorn -b :8001 run:app來指定。

+0

謝謝你回到我身邊。我嘗試改變'run.py'來包含你所建議的'if'語句,並且如果我直接從'$。/ run.py'這個命令執行它,它會起作用,但是如果我嘗試gunicorn'$ gunicorn rup: app'。 – Connie 2014-10-06 17:07:45

+0

'rup'是一個錯字嗎? – dirn 2014-10-06 17:08:50

+0

哎呦,這是一個錯字。當我輸入'$ gunicorn run:app'時,Gunicorn似乎不工作。 – Connie 2014-10-06 17:50:10