Azure部署Django+React应用失败:路径错误与端口问题排查
Django+React+Postgres部署Azure遇到的启动错误及端口问题
已完成关键操作
- 使用django-webpack-loader和webpack-bundle-tracker实现前后端代码单应用部署
- 基于Azure App Service搭建Django应用
- 通过Azure Database for PostgreSQL灵活服务器完成Postgres数据库迁移
当前进展
- 已通过GitHub持续部署成功推送代码
- 在应用设置中配置了数据库、allowed_hosts、SECRET_KEY及端口参数
- 通过Azure门户Web SSH将Django文件夹迁移至Azure环境
遇到的问题
访问应用URL时出现超时,页面显示“Application Error”,排查后发现两个核心问题:
- 错误日志抛出
TypeError: expected str, bytes or os.PathLike object, not PosixPath - 在SSH中执行
python manage.py runserver时提示8000端口被占用,终止进程后端口仍无法释放;切换至9000端口启动服务器后,依然无法正常访问应用
Azure错误日志
/home/LogFiles/2023_01_20_lw0sdlwk0000X9_default_docker.log 2023-01-20T10:10:15.109452667Z File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2023-01-20T10:10:15.109456467Z File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2023-01-20T10:10:15.109460067Z File "/tmp/8dafa589514f05f/project/settings.py", line 94, in <module> 2023-01-20T10:10:15.109463967Z 'DIRS': [os.path.join(BASE_DIR, 'client') 2023-01-20T10:10:15.109467367Z File "/opt/python/3.9.7/lib/python3.9/posixpath.py", line 76, in join 2023-01-20T10:10:15.109471167Z a = os.fspath(a) 2023-01-20T10:10:15.109474567Z TypeError: expected str, bytes or os.PathLike object, not PosixPath 2023-01-20T10:10:15.109478267Z [2023-01-20 10:10:15 +0000] [122] [INFO] Worker exiting (pid: 122) 2023-01-20T10:10:15.227401497Z mkdir() got an unexpected keyword argument 'exist_ok' /home/LogFiles/2023_01_20_lw0sdlwk0000X9_docker.log 2023-01-20T10:05:20.883Z INFO - Stopping site -test because it failed during startup. 2023-01-20T10:09:33.036Z INFO - Starting container for site 2023-01-20T10:09:33.037Z INFO - docker run -d --expose=8000 --name-test_1_547d9150 -e WEBSITES_PORT=8000 -e WEBSITE_SITE_NAME=-test -e WEBSITE_AUTH_ENABLED=False -e PORT=8000 -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=-test.azurewebsites.net -e WEBSITE_INSTANCE_ID=xyz -e HTTP_LOGGING_ENABLED=1 -e WEBSITE_USE_DIAGNOSTIC_SERVER=True appsvc/python:3.9_20221128.12.tuxprod 2023-01-20T10:09:36.544Z INFO - Initiating warmup request to container-test_1_547d9150 for site-test 2023-01-20T10:09:52.315Z INFO - Waiting for response to warmup request for container -test_1_547d9150. Elapsed time = 15.7713165 sec 2023-01-20T10:10:08.131Z INFO - Waiting for response to warmup request for container -test_1_547d9150. Elapsed time = 31.5870197 sec 2023-01-20T10:13:47.693Z ERROR - Container -test_1_547d9150 for site-test did not start within expected time limit. Elapsed time = 251.1494362 sec 2023-01-20T10:13:47.733Z ERROR - Container -test_1_547d9150 didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging. 2023-01-20T10:13:47.753Z INFO - Stopping site -test because it failed during startup. /home/LogFiles/AppServiceAppLogs_Feature_Installer/startup_0.log 2023-01-20 09:45:55,527 [Thread-1 ] [DEBUG] : Did not find any previously bound socket 2023-01-20 09:55:42,312 [MainThread] [DEBUG] : Initializating AppServiceAppLogging 2023-01-20 09:55:42,316 [MainThread] [DEBUG] : Initialized AppServiceAppLogging 2023-01-20 09:55:42,359 [Thread-1 ] [DEBUG] : Did not find any previously bound socket 2023-01-20 10:05:11,655 [MainThread] [DEBUG] : Initializating AppServiceAppLogging 2023-01-20 10:05:11,658 [MainThread] [DEBUG] : Initialized AppServiceAppLogging 2023-01-20 10:05:11,706 [Thread-1 ] [DEBUG] : Did not find any previously bound socket 2023-01-20 10:10:08,028 [MainThread] [DEBUG] : Initializating AppServiceAppLogging 2023-01-20 10:10:08,030 [MainThread] [DEBUG] : Initialized AppServiceAppLogging 2023-01-20 10:10:08,039 [Thread-1 ] [DEBUG] : Did not find any previously bound socket
Django Settings.py代码
from pathlib import Path import environ import os env = environ.Env() environ.Env.read_env() BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = env('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = [env('ALLOWED_HOSTS')] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader', 'rest_framework', 'jwt_auth', 'etc etc', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'client') ] , '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', ], }, }, ] print('templates ->', TEMPLATES) WSGI_APPLICATION = 'project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DBNAME'), 'HOST': env('DBHOST'), 'PORT': 5432, 'USER': env('DBUSER'), 'PASSWORD': env('DBPASS') } } 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_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "client", "build", "static"), ) print('static-files ->', STATICFILES_DIRS) STATIC_ROOT = ( os.path.join(BASE_DIR, "static") ) print('static-root ->', STATIC_ROOT) DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' AUTH_USER_MODEL = 'jwt_auth.User' REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'jwt_auth.authentication.JWTAuthentication', ), } WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'], } }
解决方案
1. 修复PosixPath类型错误
错误原因是BASE_DIR是Path对象,但os.path.join仅接受字符串/字节类型路径,两种修复方式二选一:
- 方式一:将BASE_DIR转为字符串
修改settings.py中BASE_DIR的定义:BASE_DIR = str(Path(__file__).resolve().parent.parent) - 方式二:统一使用Path对象的join方法
替换所有os.path.join为Path对象的路径拼接:# TEMPLATES配置 'DIRS': [BASE_DIR / 'client'] # STATICFILES_DIRS配置 STATICFILES_DIRS = (BASE_DIR / "client" / "build" / "static",) # STATIC_ROOT配置 STATIC_ROOT = BASE_DIR / "static" # WEBPACK_LOADER配置 'STATS_FILE': BASE_DIR / 'webpack-stats.json',
另外日志中出现的mkdir() got an unexpected keyword argument 'exist_ok',大概率是依赖版本不兼容,建议升级whitenoise、django-environ等依赖到与Python3.9匹配的稳定版本。
2. 解决端口占用与无法访问问题
- Azure App Service会自动通过
PORT环境变量分配端口,不要手动指定8000/9000,启动命令改为:python manage.py runserver 0.0.0.0:$PORT - 不要在SSH中手动启动runserver,Azure会自动管理应用进程,手动启动会导致端口冲突,直接重启App Service实例即可清理残留进程。
- 确保应用监听
0.0.0.0而非127.0.0.1,否则外部请求无法访问容器内服务。
内容的提问来源于stack exchange,提问作者raspberry_coulis
相关产品推荐
相关产品推荐

