Can Django run on Gunicorn alone (no Apache or nginx)?

Sahat Yalkabov picture Sahat Yalkabov · Jun 2, 2012 · Viewed 14.4k times · Source

I have tried just about every django + nginx tutorial on the web and I cannot get an image file to display on the screen. It's always the old story - 404 PAGE NOT FOUND. The web page loads fine but django.png in my /static/ folder does not. Not sure if it's a problem in settings.py or with nginx.

I am so frustrated with it that I refuse to look at another "How to get nginx/django tutorial". If I deploy a website in the near future will Gunicorn suffice to run a Django site and serve static files simultaneously without using Apache or nginx? Is there a big benefit to having a reverse proxy in the first place?

Answer

Lakshman Prasad picture Lakshman Prasad · Jun 2, 2012

Yes. Gunicorn can serve your static too.

If all else fails, let django do it for you (although, do this as a last resort before frustration.) To do that, you just have to add another url pattern, as follows:

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

While django serving static is better than not serving it at all, it is worth delegating that to the servers optimized for the same like nginx.

I'd recommend running nginx on a different port to start with, and change the django STATIC_URL setting to include the port (After you have confirmed that the port serves the statics). - Doing this is as simple as doing a simlink to the MEDIA_ROOT from the nginx folder.

And if you are using nginx anyway, it is also good to proxy all requests using it and only pass the django request to the gunicorn. All this requires is the addition of a conf file that tells nginx accordingly.

I can see how it can be confusing to those who are starting and trying to do all (proxy requests, serve static, configure nginx) at once. Try it one by one. Get the media from the gunicorn; Then serve it from nginx and then eventually have the nginx proxy too. But do this all before you have your app in production. This approach, I have seen increases understanding and decreases frustration.