How to make Django serve static files with Gunicorn?

前端 未结 6 1230
小鲜肉
小鲜肉 2020-11-30 20:27

I want to run my django project under gunicorn on localhost. I installed and integrated gunicorn. When I run:

python manage.py run_gunicorn

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 21:06

    The gunicorn should be used to serve the python "application" itself, while the static files are served by a static file server ( such as Nginx ).

    There is a good guide here: http://honza.ca/2011/05/deploying-django-with-nginx-and-gunicorn

    This is an excerpt from one of my configurations:

    upstream app_server_djangoapp {
        server localhost:8000 fail_timeout=0;
    }
    
    server {
        listen < server port goes here >;
        server_name < server name goes here >;
    
        access_log  /var/log/nginx/guni-access.log;
        error_log  /var/log/nginx/guni-error.log info;
    
        keepalive_timeout 5;
    
        root < application root directory goes here >;
    
        location /static {    
            autoindex on;    
            alias < static folder directory goes here >;    
        }
    
        location /media {
           autoindex on;
           alias < user uploaded media file directory goes here >;
        }
    
        location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
    
            if (!-f $request_filename) {
                proxy_pass http://app_server_djangoapp;
                break;
            }
        }
    }
    

    Some notes:

    • The static root, media root, static files path prefix and media file path prefix are set up in your settings.py
    • Once you have nginx set up to serve from the static content directory, you need to run "python manage.py collectstatic" in your project root so that the static files in the various apps can be copied to the static folder

    In closing: while it is possible to serve static files from gunicorn ( by enabling a debug-only static file serving view ), that is considered bad practice in production.

提交回复
热议问题