django+gunicorn+nginx, WebSocket无法正常连接

问题: django+gunicorn+nginx, WebSocket无法正常连接

关键词: nginx, WebSocket

时间: 2017/06/12

描述:

  1.  单独使用django, websocket正常连接, 尝试加上gunicorn+nginx后, 连接失败报错码500.
  2. websocket:
    var socket = new WebSocket("ws://" + window.location.host + "/chatrooms/online_user/" + userid + "/");
  3. /etc/nginx/sites-avaliabal/default 配置如下:
    server {
    	listen 80; 	
    
    	server_name 192.168.31.137;
            access_log /var/log/nginx/bbank.log;
    
    	location / {
                    proxy_pass http://127.0.0.1:8000;
                    proxy_http_version 1.1;
                    proxy_set_header Host $host;
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    
    	}

解决: 

  1. 参考: 文章
  2. 修改default:
    server {
    	listen 80; 	
    
    	server_name 192.168.31.137;
            access_log /var/log/nginx/bbank.log;
    
    	location / {
                    proxy_pass http://127.0.0.1:8000;
                    proxy_http_version 1.1;
                    proxy_set_header Host $host;
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection "upgrade";
    	}
    至此, websocket正常连接.
  3. 衍生问题:
    (1)websocket连接30秒后自动断开.
        2017/06/12: 暂且通过配置default文件在server中加入proxy_read_timeout = 3600s; 即,保持连接1小时.
    (2)websocket断开后, 才可以正常获取页面信息.
        2017/06/12: 1.意外发现django+nginx, websocket正常使用, 问题出在gunicorn. 待更新
                            2.解决: gunicorn yourapp.wsgi:application(这样启动gunicorn好像只能单线程工作, 这样就会出现上面的情况),
            而采用 gunicorn --worker-class=gevent yourapp.wsgi:application 的形式, 好像就变成多线程工作了.


你可能感兴趣的:(python,django)