You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker化Django项目:Nginx未监听80端口且无法读取静态文件

Django Docker化部署Nginx相关问题

我正在Windows系统上对Django项目进行Docker化部署,未配置Nginx容器时,静态文件服务正常。但安装Nginx后,尽管静态文件已存在于Nginx容器中,Nginx仍无法找到它们;同时站点仅能通过localhost:8000端口访问。


相关配置文件

docker-compose.yml

version: '3'

services:
  nginx:
    build: ./nginx
    ports:
      - 80:80
    depends_on:
      - "web"
    volumes:
      - ./static_volume/:/home/app/web/staticfiles
  db:
    image: postgres
    restart: always
    volumes:
      - ./pgdb:/var/lib/postgresql/data/
    ports:
      - "5432:5432"
    env_file:
      - .env
  web:
    build: .
    command: gunicorn config.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - .:/app
      - ./static_volume/:/app/staticfiles
    ports:
      - "8000:8000"
    depends_on:
      - db
      - redis
      - celery
    env_file:
      - .env
  redis:
    image: redis
    ports:
      - "6379:6379"
  celery:
    build: .
    command: celery -A config worker -l info
    depends_on:
      - redis
    env_file:
      - .env
volumes:
  static_volume:
  pgdb:
    external: false

nginx.conf

upstream hello_django {
    server web:8000;
}

server {

    listen 80;

    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static/ {
        alias /home/app/web/staticfiles;
    }
}

Nginx Dockerfile

FROM nginx:1.21-alpine

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d

问题解决步骤

1. 修复Nginx静态文件找不到的问题

  • 修正alias路径结尾斜杠:Nginx的alias配置需要和location的斜杠匹配,修改nginx.conf中的静态文件路径配置:
    location /static/ {
        alias /home/app/web/staticfiles/;  # 添加末尾斜杠
    }
    
    若缺少斜杠,访问/static/css/style.css时,Nginx会错误拼接为/home/app/web/staticfilescss/style.css。
  • 确认静态文件已收集:进入web容器执行收集命令,确保文件同步到挂载目录:
    docker-compose exec web python manage.py collectstatic --noinput
    
    再进入Nginx容器验证文件是否存在:
    docker-compose exec nginx ls /home/app/web/staticfiles/
    
  • 解决Windows权限问题:Windows文件系统权限可能导致Nginx无法读取挂载文件,可临时在docker-compose.yml的Nginx服务中添加user: root测试,或调整宿主机static_volume目录权限。

2. 修复仅能访问localhost:8000的问题

  • 检查Nginx容器状态:执行docker-compose ps确认Nginx容器处于Up状态,若启动失败查看日志:
    docker-compose logs nginx
    
  • 检查80端口占用:Windows上执行netstat -ano | findstr ":80",关闭占用80端口的程序(如IIS)后重启Nginx容器。
  • 验证Django允许代理访问:确保.env中ALLOWED_HOSTS包含localhost和web(容器内部域名),比如:
    ALLOWED_HOSTS=localhost,web
    

内容的提问来源于stack exchange,提问作者Ughur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 15:43:17