Docker+Nginx部署Django静态文件问题:Admin面板资源加载失败
问题:Django Admin面板静态文件加载失败(REST Framework面板正常)
以下是配置中存在的关键错误:
1. Nginx静态文件路径映射不匹配
你的nginx配置里location /static/的alias指向/usr/share/nginx/html/static,但docker-compose的nginx服务中静态卷挂载的是static_volume:/app/staticfiles,两者路径完全不一致,导致Nginx无法找到Django收集的静态文件。
2. Web服务静态卷配置错误,本地目录挂载覆盖容器内文件
- Dockerfile中执行了
collectstatic生成静态文件,但web服务配置了volumes: - .:/app,本地目录会直接覆盖容器内的/app目录,构建时生成的staticfiles文件夹被本地无该文件夹的目录覆盖。 - web服务未将
static_volume挂载到Django的STATIC_ROOT(即/app/staticfiles),无法把收集到的静态文件同步到共享卷供Nginx调用。
修正后的关键配置调整
调整docker-compose.yml
version: '3.8' services: web: build: . command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app - static_volume:/app/staticfiles # 挂载静态卷到STATIC_ROOT路径 ports: - "8000:8000" nginx: image: nginx:1.19-alpine ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/conf.d:/etc/nginx/conf.d - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot - static_volume:/usr/share/nginx/html/static # 匹配nginx配置中的alias路径 volumes: static_volume:
调整nginx/conf.d/default.conf
server { listen 80; server_name localhost; location /static/ { alias /usr/share/nginx/html/static/; # 末尾加斜杠避免路径匹配异常 autoindex on; } location / { proxy_pass http://web:8000; proxy_set_header Host $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; } }
额外补充
如果保留web服务的本地目录挂载(.:/app)以实现代码热加载,建议在启动命令中重新执行collectstatic,避免本地目录覆盖容器静态文件:
command: sh -c "python manage.py collectstatic --noinput && gunicorn config.wsgi:application --bind 0.0.0.0:8000"
内容的提问来源于stack exchange,提问作者Advenn
相关产品推荐
相关产品推荐

