You need to enable JavaScript to run this app. Django部署至Digital Ocean Apps时collectstatic执行报错问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Django部署至Digital Ocean Apps时collectstatic执行报错问题排查

Digital Ocean Apps部署Django生产环境报错场景
  • 尝试将Django应用部署到Digital Ocean Apps生产环境,已完成所有常规排查步骤仍持续报错。
  • 部署日志中出现$ heroku config:set DISABLE_COLLECTSTATIC=1的提示,但此前仅将应用关联至Heroku Git,从未部署到Heroku生产环境,且已完全清除所有Heroku相关配置痕迹。
  • 存在同场景问题的公开讨论提到的解决方案涉及Docker部署,但当前已在使用Digital Ocean PaaS服务,需要确认该方案是否冗余,同时获取可落地的报错解决方法。

附:settings.py配置

"""
Django settings for stockbuckets project.

Generated by 'django-admin startproject' using Django 3.1.1.
"""
import os
from pathlib import Path
import dj_database_url

BASE_DIR = Path(__file__).resolve().parent.parent

# 安全配置
SECRET_KEY = os.environ.get('SECRET_KEY_DJANGO_STOCKBUCKETS')
DEBUG = False
ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1']

# 应用定义
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home.apps.HomeConfig',
    'django_plotly_dash.apps.DjangoPlotlyDashConfig',
    'dpd_static_support',
    'channels',
    'channels_redis',
    'bootstrap4',
    'blog',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django_plotly_dash.middleware.BaseMiddleware',
    'django_plotly_dash.middleware.ExternalRedirectionMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'stockbuckets.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['stockbuckets/templates', 'home/templates', 'blog/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'stockbuckets.wsgi.application'

# 数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'sb',
        'USER' : 'postgres',
        'PASSWORD' : '0',
        'HOST' : 'localhost'
    }
}
db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)

# 密码校验
AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]

# 国际化配置
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# 实时通道配置
CRISPY_TEMPLATE_PACK = 'bootstrap4'
ASGI_APPLICATION = 'stockbuckets.routing.application'
CHANNEL_LAYERS = {
    'default' : {
        'BACKEND': 'channels_redis_core.RedisChannelLayer',
        'CONFIG' : {
            'hosts' : [('127.0.0.1',6379),],
        }
    }
}

# 静态文件配置
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django_plotly_dash.finders.DashAssetFinder',
    'django_plotly_dash.finders.DashComponentFinder',
    'django_plotly_dash.finders.DashAppDirectoryFinder',
]

PLOTLY_COMPONENTS = [
    'dash_core_components',
    'dash_html_components',
    'dash_renderer',
    'dpd_components',
    'dpd_static_support',
    'dash_bootstrap_components',
]

X_FRAME_OPTIONS = 'SAMEORIGIN'
STATICFILES_LOCATION = 'static'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'stockbuckets/static')
]

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

附:部署日志

stockbuckets  | 18:45:18 -----> $ python manage.py collectstatic --noinput
stockbuckets  | 18:45:20        OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k
stockbuckets  | 18:45:20        Connecting to the PostgreSQL database...
stockbuckets  | 18:45:20        could not connect to server: Connection refused
stockbuckets  | 18:45:20                Is the server running on host "localhost" (::1) and accepting
stockbuckets  | 18:45:20                TCP/IP connections on port 5432?
stockbuckets  | 18:45:20        could not connect to server: Connection refused
stockbuckets  | 18:45:20                Is the server running on host "localhost" (127.0.0.1) and accepting
stockbuckets  | 18:45:20                TCP/IP connections on port 5432?
stockbuckets  | 18:45:21 
stockbuckets  | 18:45:21  !     Error while running '$ python manage.py collectstatic --noinput'.
stockbuckets  | 18:45:21        See traceback above for details.
stockbuckets  | 18:45:21 
stockbuckets  | 18:45:21        You may need to update application code to resolve this error.
stockbuckets  | 18:45:21        Or, you can disable collectstatic for this application:
stockbuckets  | 18:45:21 
stockbuckets  | 18:45:21           $ heroku config:set DISABLE_COLLECTSTATIC=1
stockbuckets  | 18:45:21 
stockbuckets  | 18:45:21 ERROR: failed to build: exit status 1
stockbuckets  | 18:45:21  ! Build failed (exit code 7)

问题原因定位

  1. 日志中出现Heroku相关提示的核心原因:Digital Ocean Apps的Python构建流程复用了Heroku Buildpacks的通用构建逻辑,报错提示只是通用模板文案,和项目中是否留存Heroku配置无任何关联,不需要为这个残留提示做额外清理。
  2. 实际构建失败的根本原因:collectstatic命令执行时会初始化Django项目的全量配置(包括数据库连接),但当前配置中数据库地址写死为localhost,而DO Apps的构建环境和应用运行环境是隔离的,构建阶段不存在本地的PostgreSQL服务,因此触发连接拒绝错误,导致collectstatic执行中断。
  3. 关于Docker方案的冗余判断:当前已经在使用DO PaaS服务,不需要额外引入独立的Docker部署流程,直接调整现有配置即可解决问题,无冗余。
  4. 配置中存在两处会导致运行失败的隐藏问题:
    • Channels配置的后端导入路径存在笔误,写为channels_redis_core.RedisChannelLayer,正确路径应为channels_redis.core.RedisChannelLayer
    • 硬编码的数据库账号密码存在生产环境凭据泄露风险

分步解决方法

  • 第一步:修正数据库配置逻辑
    将原有的硬编码PostgreSQL配置块整体替换为优先读取环境变量的逻辑,避免构建阶段连接不存在的本地数据库、硬编码凭据泄露:
    DATABASES = {
        'default': dj_database_url.config(
            # 构建阶段无生产数据库时自动回退到本地SQLite,不会触发连接错误
            default='sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3'),
            conn_max_age=600
        )
    }
    
    运行阶段DO会自动注入托管PostgreSQL的连接串环境变量,无需手动调整。
  • 第二步:修正ALLOWED_HOSTS配置
    将当前写死的本地地址列表替换为动态读取环境变量的逻辑,避免后续访问绑定域名时触发主机校验错误:
    ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', '0.0.0.0,localhost,127.0.0.1').split(',')
    
  • 第三步:修正Channels-Redis配置
    修正导入路径笔误,同时将硬编码的127.0.0.1地址替换为环境变量读取逻辑,避免运行阶段连接不存在的本地Redis服务:
    redis_host = os.environ.get('REDIS_HOST', '127.0.0.1')
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                "hosts": [(redis_host, 6379)],
            },
        },
    }
    
  • 第四步:静态文件服务配置
    DO Apps支持直接挂载静态文件目录,不需要通过DISABLE_COLLECTSTATIC跳过静态收集流程:在构建配置中添加静态文件输出路径映射,将STATIC_ROOT指向的目录绑定为静态资源服务路径即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 13:36:03