Serve Static Files by Nginx from Django using Docker

This is more of a followup post of my previous blog.

Before I start, I am assuming you have successfully deployed django using docker & nginx, but having some problems serving static files.

No worries, its easy. Just follow these steps:

1. In your django file, add static file directory i.e. STATIC_ROOT=/static. So what it will do is, when you run collectstatic command(python collectstatic), it will store the static files in your /static directory of OS.

2. Now in docker-compose.yml folder, lets add a configuration like this:

version: '2'  
    image: nginx:latest
    container_name: NGINXDOCKERNAME
      - "8000:8000"
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
      - /static:/static  <--- HERE
      - web
    build: .
    container_name: DJANGOXDOCKERNAME
    command: bash -c "python makemigrations && python migrate && gunicorn mydjango.wsgi -b"
      - db
      - ./src:/src
      - /static:/static    <---- HERE
      - "8000"

    image: postgres:latest
    container_name: PSQLDOCKERNAME

What it will do is that, two containers web and nginx will share a directory named /static.

3. Now lets add few lines in nginx's config file, i.e mydjango.conf:

upstream web {  
  server web:8000;

server {

    location /static/ {    
        autoindex on;    
        alias /static/; 

    location / {
        proxy_pass http://web/;
    listen 8001;
    server_name localhost;

So what it will do is, any request to url like yourhost:yourport/static/* this comes to nginx, it will serve data from /static directory.

4. Now lets run the following command:

docker exec DOCKERNAME /bin/sh -c "python collectstatic --noinput"  

It will put static files in /static directory and thats should do the trick. Whenever you hit url with /static will serve static files from that folder. Similarly you can serve media files too.
Codes have been updated here at:

comments powered by Disqus