无法在 docker 容器内使用 django 和 gunicorn 运行 在 ec2 上使用 nginx 提供静态文件

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

我在 ec2 服务器上使用 docker 将 'local.yml' 组合成 运行 django

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

它以 start.sh 脚本开始,写成

#!/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

部署后在 ec2 上,服务器 运行gunicorn 正常。

现在我添加nginx配置为

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;
    }


}

这个配置也 运行 没问题,我可以在 example.in:3000 本地访问它。

但是当我尝试打开管理页面时,我在那里看不到静态文件。

我还尝试使用以下命令收集静态信息

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

文件收集成功。

我应该怎么做才能提供静态文件?

将您的 /app/static/ 文件夹从容器映射到主机上的一个文件夹中,假设:/home/ec2/static/ 并确保您的 nginx 可以访问那里。

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

nginx.conf

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