使用Waitress部署Django/PostgreSQL到Heroku遇R10端口绑定错误
我正尝试用Waitress将Django/PostgreSQL项目部署到Heroku(多年前用Gunicorn成功部署过一次),最终遇到错误:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
完整错误日志:
2025-04-09T07:09:48.289599+00:00 heroku[web.1]: State changed from crashed to starting 2025-04-09T07:09:52.235046+00:00 heroku[web.1]: Starting process with command `waitress-serve project.wsgi:application` 2025-04-09T07:09:52.781389+00:00 app[web.1]: Python buildpack: Detected 512 MB available memory and 8 CPU cores. 2025-04-09T07:09:52.781847+00:00 app[web.1]: Python buildpack: Defaulting WEB_CONCURRENCY to 2 based on the available memory. 2025-04-09T07:09:53.244456+00:00 app[web.1]: INFO:waitress:Serving on http://0.0.0.0:8080 2025-04-09T07:10:52.357945+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2025-04-09T07:10:52.370446+00:00 heroku[web.1]: Stopping process with SIGKILL 2025-04-09T07:10:52.421789+00:00 heroku[web.1]: Process exited with status 137 2025-04-09T07:10:52.445044+00:00 heroku[web.1]: State changed from starting to crashed"
我最初以为是PORT定义问题,但从Procfile中移除相关设置后,Heroku似乎已自动指定本地PORT,该问题仍未解决。想知道导致“failed to bind to $PORT”的可能原因,是否与DATABASE_URL有关?我正在使用Heroku的SSL,但相关设置尚未理清。
附上我的配置文件:
Procfile
web: waitress-serve project.wsgi:application
.env
WEB_CONCURRENCY=3 PORT=PORT SECRET_KEY=[text-of-secret-key]
base.py
import os import django_on_heroku import environ from environ import Env from dotenv import load_dotenv import dj_database_url load_dotenv() env = Env() BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) environ.Env.read_env(os.path.join(BASE_DIR, '.env')) SECRET_KEY = env('SECRET_KEY') PORT = env('PORT') SECURE_HSTS_SECONDS = 3600 SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True DEBUG = True ALLOWED_HOSTS = ['.herokuapp.com/', 'localhost'] INSTALLED_APPS = [ 'cgp.apps.CgpConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'ajax_datatable', 'whitenoise.runserver_nostatic', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], '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', 'django.template.context_processors.request', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' IS_HEROKU_APP = "DYNO" in os.environ and "CI" not in os.environ if IS_HEROKU_APP: DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'cgp', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } 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_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') ##same as beta STATIC_URL = '/static/' ##same as beta STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ##same as beta STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'cgp/static'), ] DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' django_on_heroku.settings(locals())
(不确定DATABASES的条件定义是否必要,但移除Heroku条件后仍出现相同错误。)
heroku.py
import environ #import dj_database_url # If using in your own project, update the project namespace below from project.settings.base import * env = environ.Env( # set casting, default value DEBUG=(bool, True) ) # False if not in os.environ DEBUG = env('DEBUG') # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = env.list('ALLOWED_HOSTS') # Parse database connection url strings like psql://user:pass@127.0.0.1:8458/db DATABASES = { # read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found 'default': env.db(), }
requirements.txt
asgiref==3.7.2 dj-database-url==2.3.0 Django==4.2.5 django-ajax-datatable==4.5.0 django-environ==0.12.0 django-heroku==0.3.1 django-on-heroku==1.1.2 gunicorn==23.0.0 packaging==24.2 psycopg2==2.9.7 psycopg2-binary==2.9.10 python-dotenv==1.0.1 sqlparse==0.4.4 typing_extensions==4.12.2 tzdata==2023.3 waitress==3.0.2 whitenoise==6.9.0
从错误日志能明显看到核心问题:Waitress绑定了固定端口8080,但Heroku要求应用必须绑定到环境变量$PORT指定的端口,而不是硬编码的端口。
1. 修正Procfile,让Waitress读取Heroku的$PORT
当前Procfile没有指定端口参数,Waitress默认用8080,不符合Heroku要求。修改Procfile,明确让Waitress绑定到$PORT:
web: waitress-serve --port=$PORT project.wsgi:application
2. 清理不必要的PORT配置
- 从
.env中删除PORT=PORT这一行,Heroku会自动设置这个环境变量,本地开发时可单独设置或使用Waitress默认端口。 - 从
base.py中删除PORT = env('PORT')这一行,Django本身不需要该变量,端口由WSGI服务器(Waitress)处理。
3. 数据库配置检查(当前错误与数据库无关,但需确保配置正确)
日志中无数据库连接失败提示,所以当前R10错误和DATABASE_URL无关,但可优化配置:
- 保留
IS_HEROKU_APP的条件判断合理,能区分本地和生产环境。 - 确保Heroku上已添加PostgreSQL插件,且
DATABASE_URL环境变量正确设置(可通过heroku config:get DATABASE_URL命令查看)。
4. SSL配置调整(可选,避免后续问题)
当前SECURE_SSL_REDIRECT=False,在Heroku建议开启:
if IS_HEROKU_APP: SECURE_SSL_REDIRECT = True
同时将ALLOWED_HOSTS里的.herokuapp.com/改为'.herokuapp.com',避免主机匹配失败。
5. 重新部署验证
修改完成后,重新提交代码并部署:
git add . git commit -m "Fix Waitress port binding for Heroku" git push heroku main
部署后查看日志,若看到类似INFO:waitress:Serving on http://0.0.0.0:xxxx(xxxx为Heroku分配的随机端口),说明端口绑定成功,R10错误应会消失。
内容的提问来源于stack exchange,提问作者relp lamfred

