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

Docker部署Django模板变更仅生效一次问题求助

问题分析与解决方案

你遇到的问题核心是多进程内存缓存+代理/浏览器缓存的组合问题:Gunicorn启动的多个worker进程会在启动时把模板加载到内存,修改模板后未触发所有worker重载,导致请求分配到不同worker时显示新旧内容;同时Nginx或浏览器的缓存也会阻碍修改内容的及时展示。

以下是具体解决步骤:

一、调整Django模板缓存设置(开发环境)

打开项目的settings.py,找到TEMPLATES配置块,确保DEBUG模式下禁用模板缓存:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            # 根据DEBUG状态切换加载器,DEBUG=true时禁用缓存
            'loaders': [
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                    'django.template.loaders.app_directories.Loader',
                ]),
            ] if not DEBUG else [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
        },
    },
]

若你的DEBUG已设为True,Django默认会禁用模板缓存,但手动配置可确保生效。

二、让Gunicorn自动重载worker(开发环境)

修改docker-compose.yml中web服务的command,添加--reload参数,触发文件变化时重启所有worker:

command: ["/wait-for-it.sh", "db:5432", "--", "gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "--reload", "mysite.wsgi:application"]

注意:--reload仅适合开发环境,生产环境禁用,避免性能损耗。

三、配置Nginx禁用动态内容缓存

打开./nginx/user_conf.d/下的Nginx配置文件,在反向代理的location块中添加缓存禁用指令:

location / {
    proxy_pass http://web:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    
    # 禁用Nginx对动态内容的缓存
    proxy_cache_bypass $http_cache_control;
    proxy_no_cache 1;
    proxy_set_header Cache-Control "no-cache, no-store, must-revalidate";
    proxy_set_header Pragma "no-cache";
    proxy_set_header Expires "0";
}

修改后重启Nginx容器:

docker-compose restart nginx

四、强制浏览器刷新

浏览器可能缓存旧页面,按Ctrl + F5(Windows/Linux)或Cmd + Shift + R(Mac)强制刷新,跳过本地缓存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:35:31