title: Nginx + Django + Gunicorn: 502 Bad Gateway upstream prematurely closed connection while reading response header from upstream
body: <p>I am creating (for the first time) a website.
  More specifically, the user uploads an image and after some computations the website displays some result. </p>
  
  <p>However, <strong>sometimes</strong> (not always, sometimes just retrying or changing image it works) during this process I get "502 Bad Gateway nginx/1.10.3 (Ubuntu)" </p>
  
  <p>Looking at the error I get:</p>
  
  <pre><code>[error] 7836#7836: *16 upstream prematurely closed connection while reading response header from upstream, client: 131.175.147.1, server: _, request: "POST / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "165.227.170.231", referrer: "http://165.227.170.231/"
  </code></pre>
  
  <p>I tried <a href="https://stackoverflow.com/questions/6816215/gunicorn-nginx-timeout-problem">this</a> but it did not help much, while I think <a href="https://stackoverflow.com/questions/30470448/nginx-uwsgi-websockets-502-bad-gateway-upstream-prematurely-closed-connection-wh">this</a> is not my case.</p>
  
  <p>The settings are:</p>
  
  <p>/etc/nginx/sites-available/django :</p>
  
  <pre><code>upstream app_server {
  server unix:/home/django/gunicorn.socket fail_timeout=0;
  }
  
  server {
  listen 80 default_server;
  listen [::]:80 default_server ipv6only=on;
  
  root /usr/share/nginx/html;
  index index.html index.htm;
  
  client_max_body_size 4G;
  server_name _;
  
  keepalive_timeout 5;
  
  # Your Django project's media files - amend as required
  location /media  {
      alias /home/django/django_project/django_project/media;
  }   
  
  # your Django project's static files - amend as required
  location /static {
      alias /home/django/django_project/django_project/static;
  }   
  
  # Proxy the static assests for the Django Admin panel
  location /static/admin {
     alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
  }  
  
  location / {
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $host;
          proxy_redirect off;
          proxy_buffering off;
  
          proxy_connect_timeout 75s;
          proxy_read_timeout 300s;
  
  
  
          proxy_pass http://app_server;
          }
  }
  </code></pre>
  
  <p>The /etc/nginx/nginx.conf:</p>
  
  <pre><code>user www-data;
  worker_processes auto;
  pid /run/nginx.pid;
  
  events {
      worker_connections 768;
      # multi_accept on;
  }
  
  http {
  
      ##
      # Basic Settings
      ##
  
      sendfile on;
      tcp_nopush on;
      tcp_nodelay on;
      keepalive_timeout 65;
      types_hash_max_size 2048;
      # server_tokens off;
  
      # server_names_hash_bucket_size 64;
      # server_name_in_redirect off;
  
      include /etc/nginx/mime.types;
      default_type application/octet-stream;
  
      ##
      # SSL Settings
      ##
  
      ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
      ssl_prefer_server_ciphers on;
  
      ##
      # Logging Settings
      ##
  
      access_log /var/log/nginx/access.log;
      error_log /var/log/nginx/error.log;
     ##
      # Gzip Settings
      ##
  
      gzip on;
      gzip_disable "msie6";
  
      # gzip_vary on;
      # gzip_proxied any;
      # gzip_comp_level 6;
      # gzip_buffers 16 8k;
      # gzip_http_version 1.1;
      # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
  
      ##
      # Virtual Host Configs
      ##
  
      include /etc/nginx/conf.d/*.conf;
      include /etc/nginx/sites-enabled/*;
  
      proxy_connect_timeout 75s;
      proxy_read_timeout 300s;
    }
  
  
    #mail {
    #       # See sample authentication script at:
    #       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
    #
    #       # auth_http localhost/auth.php;
    #       # pop3_capabilities "TOP" "USER";
    #       # imap_capabilities "IMAP4rev1" "UIDPLUS";
    #
    #       server {
    #               listen     localhost:110;
    #               protocol   pop3;
    #               proxy      on;
  
    #       }
    #}
  </code></pre>
  
  <p>The /ect/gunicorn.d/gunicorn.py:</p>
  
  <pre><code>"""gunicorn WSGI server configuration."""
  from multiprocessing import cpu_count
  from os import environ
  
  
  def max_workers():
      return cpu_count() * 2 + 1
  
      max_requests = 1000
      worker_class = 'gevent'
      workers = max_workers()
      TIMEOUT=120
  </code></pre>
  
  <p>And I start gunicorn in this way:</p>
  
  <pre><code>service gunicorn start --timeout 300 
  </code></pre>
  
  <p>Basically, I tried everywhere to avoid timing out, but still encounter the same problem.</p>