Jshee
Jshee

Reputation: 2686

Nginx/Flask/Python App, Nginx throwing 502 Bad Gateway Error

Nginx was working fine before, then I added a form to my html and nginx started throwing this error:

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"

My forms.py looks like:

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

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

my app.py looks like:

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'] = '[email protected]'
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='[email protected]',
                          recipients=['[email protected]'])
           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 (in templates/):

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

nginx config in sites-enabled/:

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/;
    }
}

I've looked tirelessly at this, but cant seem to pinpoint the problem. Does anyone see what I'm doing wrong here?

Thank you.

Upvotes: 2

Views: 3804

Answers (1)

Stephane Martin
Stephane Martin

Reputation: 1642

"Connection refused" means that Nginx does not find anything listening on localhost, port 8001. Maybe your flask app is listening on another port. By default flask listens on port 5000.

You could either try:

  • to modify nginx conf: proxy_pass http://localhost:5000;
  • OR to make flask app listen on port 8001: app.config['SERVER_NAME'] = "127.0.0.1:8001"

Upvotes: 4

Related Questions