简体   繁体   中英

not able to serve static files with nginx on ec2 with django and gunicorn running inside docker container

I am using the below docker compose 'local.yml' to run django on ec2 server

services:
  django: &django
    build:
      context: .
      dockerfile: ./compose/local/django/Dockerfile
    image: name_docker
    container_name: django
    depends_on:
      - mariadb
      - mailhog
    volumes:
      - .:/app:z
    env_file:
      - ./.envs/.local/.django
      - ./.envs/.local/.mariadb
    oom_kill_disable: True
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: '3G'
    ports:
      - "8000:8000"
    command: /start

it starts with start.sh script which is written as

#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset


# python /app/manage.py collectstatic --noinput


/usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:8000 --timeout 10000 --workers 5 --threads 5 --chdir=/app

On ec2 after deployment, server is running fine with gunicorn.

Now I added nginx configuration as

server {
    listen 3000;
    server_name domain_name.in;
    access_log /var/log/nginx/django_project-access.log;
    error_log /var/log/nginx/django_project-error.log info;
    add_header 'Access-Control-Allow-Origin' '*';

    keepalive_timeout 5;

    # path for staticfiles
    location /static {
            autoindex on;
            alias /static;
    }

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://0.0.0.0:8000;
    }


}

This configuration is also running fine and I can access it locally on example.in:3000.

But when I try to open admin page then I am not able to see static files there.

Also I tried to collectstatic with the below command

docker-compose -f local.yml run --rm django python manange.py collectstatic --no-input

The files are collected successfully.

What should i do to serve the static files?

Map your /app/static/ folder from the container into a folder on the host, lets say: /home/ec2/static/ and make sure your nginx has access there.

volumes:
  - /home/ec2/static/:/app/static

nginx.conf

...
location /home/ec2/static/ {
        autoindex on;
        alias /static/;
    }
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM