Getting "502 Bad Gateway" with nginx, uwsgi python-flask on ubuntu 16.04

16,173

Solution 1

I had the same problem using the guide. As far as I've read; 502 bad gateway is a symptom of Nginx not being able to properly connect to the uwsgi. Changing the permissions on the socket solved the issue for me.

sudo chmod 777 /home/sajjan/project/project.sock
sudo systemctl restart nginx

777 is offcourse a bit excessive, but its a quick and dirty way to verify if it is in fact a problem with permissions

Solution 2

Nginx has no permission to write to socket. Granting appropriate mode with below command, helped me.

chmod 0755 /to/project

Solution 3

For me this problem was due to the users configuration. Basically, I set up all of my project using the root user. But then I redid everything from scratch using a non-root user with sudo privileges. It worked.

Solution 4

Try running myapp/bin/uwsgi --ini myapp.ini to see the actual error thats preventing uwsgi to run.

In my case 5 processes in the .ini configuration file were to much to handle for my cpu this was my error output.

your processes number limit is 3900 your memory page size is 4096 bytes detected max file descriptor number: 1024

If this is your case lowering the number of processes to 2 in your .ini file might work.

Share:
16,173
Sajjan Kumar
Author by

Sajjan Kumar

Updated on July 05, 2022

Comments

  • Sajjan Kumar
    Sajjan Kumar almost 2 years

    I am following the this to deploy a flask app(simple hello world) on the Ubuntu 16-04. digital Ocean tutorial

    Everything works fine till Testing uWSGI Serving. After that I followed the step as described and when I finally reach the bottom and check server IP address then I got:

    502 Bad Gateway
    

    Ok fine. I searched and checked my error log, I got this :-

    2017/01/16 05:29:27 [crit] 20714#20714: *2 connect() to unix:/home/sajjan/project/project.sock failed (2: No such file or directory) while connecting to upstream, client: xx.9.xxx.xxx, server: 138.xxx.xx.xxx, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/home/sajjan/project/project.sock:", host: "xx.xx.xx.xx"
    

    So After taking a error log , I created the file project.sock manually. again Go to server ip address and then same error "502 Bad Gateway"

    Again checked the error log and found this

    2017/01/16 06:07:11 [crit] 20874#20874: *1 connect() to unix:/home/sajjan/project/project.sock failed (13: Permission denied) while connecting to upstream, client: 47.9.237.113, server: XX.XX.XX.XX, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/home/sajjan/project/project.sock:", host: " XX.XX.XX.XX "
    

    I figured out about the permission issue and change the permission using below command

    sudo chmod 666 project.sock
    

    Now I checked the permision( using ls -l filename)

    -rw-rw-rw- 1 root root 0 Jan 16 05:31 project.sock
    

    Now I go back to check the server's IP but found the same "502 Bad Gateway". Again I checked the error log and found this :

    017/01/16 06:13:31 [error] 20897#20897: *6 connect() to unix:/home/sajjan/project/project.sock failed (111: Connection refused) while connecting to upstream, client: 47.9.237.113, server: XX.XX.XX.XX, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://unix:/home/sajjan/project/project.sock:", host: " XX.XX.XX.XX ", referrer: "http:// XX.XX.XX.XX /"
    

    I googled for above error read a lot in last two days but nothing to seem working for me . I have check these answers but no help stackanswer-1 stackanswer-2 and along with these I checked all the digital-ocean community thread but nothing seems to work.

    I am total begineer to servers and don't know much about ubuntu. If you can help me to find out what wrong am I doing or suggest some better tutorial/ways to deploy my flask application, then I would be greatful.

    These are my files

    1. hello.py

      from flask import Flask
      app = Flask(__name__)
      
      @app.route("/")
      def hello():
          return "<h1 style='color:blue'>Hello There!</h1>"
      
      if __name__ == "__main__":
          app.run(host='0.0.0.0')
      
    2. project.ini

      [uwsgi]
      
      module = wsgi:app
      
      master = true
      
      processes = 5
      
      socket = /home/sajjan/project/project.sock
      
      chmod-socket = 660
      
      vacuum = true
      
      die-on-term = true
      
    3. wsgi.py

      from hello import app
      
      if __name__ == "__main__":
            app.run()
      
    4. Below is file : /etc/nginx/sites-available/project

      server {
          listen 80;
          server_name 138.197.28.107;
      
          location / {
              include uwsgi_params;
              uwsgi_pass unix:/home/sajjan/project/project.sock;
          }
      }
      

    When I run the command :

        sudo service uwsgi restart
    

    output:

       Failed to restart wsgi.service: Unit wsgi.service not found. 
    

    while output of

       sudo service nginx status/restart
    

    then this show that nginx is running .

    Help me, If anything else that you want to know then let me know. Thanks

    EDIT :

    I have created a project.service file and its conetent is :

        [Unit]
        Description=uWSGI instance to serve project
        After=network.target
    
        [Service]
        User=sajjan
        Group=www-data
        WorkingDirectory=/home/sajjan/project
        Environment="PATH=/home/sajjan/project/venv/bin"
        ExecStart=/home/sajjan/project/venv/bin/uwsgi --ini project.ini
    
        [Install]
        WantedBy=multi-user.target
    

    I figured out I have to run below command :

        sudo systemctl start project
    

    Output is :

        Warning: project.service changed on disk. Run 'systemctl daemon-reload' to reload units.
    

    and when I run

         sudo systemcl reload project 
    

    then output :

        Failed to reload project.service: Job type reload is not applicable for unit project.service.
        See system logs and 'systemctl status project.service' for details.
    

    and when I check the "systemctl status project.service"

         ● project.service - uWSGI instance to serve project
          Loaded: loaded (/etc/systemd/system/project.service; enabled; vendor preset: enabled)
         Active: failed (Result: exit-code) since Mon 2017-01-16 17:49:29 UTC; 6min ago
          Main PID: 27157 (code=exited, status=203/EXEC)
    
         Jan 16 17:49:29 learningwithpython systemd[1]: Started uWSGI instance to serve project.
         Jan 16 17:49:29 learningwithpython systemd[1]: project.service: Main process exited, code=exited, status=203/EXEC
         Jan 16 17:49:29 learningwithpython systemd[1]: project.service: Unit entered failed state.
         Jan 16 17:49:29 learningwithpython systemd[1]: project.service: Failed with result 'exit-code'.
    
  • Sajjan Kumar
    Sajjan Kumar almost 7 years
    Good, But I dropped the idea of server setup, maybe in near future, it would be some help.
  • Arthur Khazbs
    Arthur Khazbs over 2 years
    Thank you, this helped me identify a permissions problem. My uwsgi processes were owned by a user called dev, my nginx processes were owned by the www-data user, both of the users being part of the www-data group. The uwsgi Unix socket was owned by dev:www-data (that is, user dev and group www-data), and its access mode was 660. It didn't work, so I ended up changing my uwsgi systemd service unit config and my uwsgi site config so that the uwsgi processes and the socket were also owned by the www-data user (the uid setting). Now it works.
  • chichilatte
    chichilatte over 2 years
    Thank you, mine turned out to be a memory problem too. My app was on Google App Engine, but i couldn't find that particular error output in their daunting logging console!