Notes to self

Serve Django static assets with Gunicorn

Serving static assets by the application server such as Gunicorn is usually not a good idea. We should prefer a web server with a better performance, but what if you want to serve the assets directly with the Django application?

In case you want to do that, either for testing or for avoiding NGINX process in your application Docker container, you can do so by including the static files URLs returned by staticfiles_urlpatterns() in urlpatterns variable in your urls.py.

Like this:

--- a/mysite/urls.py
+++ b/mysite/urls.py
@@ -15,8 +15,11 @@ Including another URLconf
 """
 from django.contrib import admin
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns
 from django.urls import include, path

 urlpatterns = [
     path('polls/', include('polls.urls')),
     path('admin/', admin.site.urls),
 ]
+
+urlpatterns += staticfiles_urlpatterns()

With this change, your Python application server will serve static assets as well.

Check out my book
Deployment from Scratch is unique Linux book about web application deployment. Learn how deployment works from the first principles rather than YAML files of a specific tool.
by Josef Strzibny
RSS