Nginx / Flask / Python应用程序,Nginx抛出502 Bad Gateway错误

时间:2016-12-12 21:53:11

标签: python nginx flask

Nginx之前工作正常,然后我向form添加了html,nginx开始抛出此错误:

2016/12/12 16:37:24 [error] 983#0: *3 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xxx.xxx.xxx, server: site.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "site.com"

我的 forms.py 如下所示:

from flask_wtf import FlaskForm
from wtforms import TextField, StringField, SubmitField, validators

class EmailForm(FlaskForm):
  email = TextField("Email")
  submit = SubmitField("Send")

我的 app.py 看起来像:

from flask import Flask, render_template, request
from flask_mail import Mail, Message
from forms import EmailForm

app.config['DEBUG'] = True

app = Flask(__name__)
app.secret_key = 'secrets'

# add mail server config
app.config['MAIL_SERVER'] = 'site.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'contact@site.com'
app.config['MAIL_PASSWORD'] = 'pass'

mail = Mail(app)

@app.route('/', methods=('GET', 'POST'))
def email():
    form = EmailForm()

    if request.method == 'POST':
        if form.validate() == False:
            return 'Please fill in all fields <p><a href="/">Try Again</a></p>'
        else:
            msg = Message("Message from your visitor",
                          sender='contact@site.com',
                          recipients=['contact@site.com'])
           msg.body = """
            From: %s <%s>,
            %s
            """ % (form.email.data)
            mail.send(msg)
            return "Successfully  sent message!"
    elif request.method == 'GET':
        return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run()

index.html (在templates/中):

        <form action="{{ url_for('email') }}" method="post">
            {{ form.hidden_tag() }}
            {{ form.email }}
            {{ form.submit }}
        </form>

sites-enabled/中的nginx配置:

server {
   server_name mysite.com;
   listen 80;
    location / {
        proxy_pass http://localhost:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    location /static {
        alias  /home/www/flask-deploy/mysite/static/;
    }
}

我已经孜孜不倦地看着这个,但似乎无法确定问题所在。有谁看到我在这里做错了什么?

谢谢。

1 个答案:

答案 0 :(得分:3)

&#34;拒绝连接&#34;意味着Nginx没有在localhost,端口8001上找到任何东西。也许你的烧瓶应用程序正在侦听另一个端口。默认情况下,flask会侦听端口5000。

您可以尝试:

  • 修改nginx conf:proxy_pass http://localhost:5000;
  • 让烧瓶应用监听端口8001:app.config['SERVER_NAME'] = "127.0.0.1:8001"