Django + Docker - 服务器错误 500。长帖子
Posted
技术标签:
【中文标题】Django + Docker - 服务器错误 500。长帖子【英文标题】:Django + Docker - Server Error 500. Long Post 【发布时间】:2021-06-04 11:42:01 【问题描述】:我目前正在尝试让我的 Django 应用程序为部署做好准备。我正在尝试通过使用 docker、dockerfile 和 uwsgi 创建应用程序的映像来“dockerize”我的应用程序。我可以使用以下命令来做到这一点:
sudo docker create --name container --network network --network-alias container -t -p 40001:8001 image_name
docker build -t image_name .
镜像构建完成,我可以启动它,并且可以访问容器化应用程序的主页。但是,当我尝试导航到应用程序中的其他页面时,我收到服务器错误 (500),在控制台 (Firefox) 中,我收到此错误:
The character encoding of the html document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.
我的 base.html 中有这个:
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8">
每个网页都扩展了这个页面。
我相信这可能是我使用 WhiteNoise 时静态文件配置的问题。但是我的 dockerfile 和 uwsgi.ini 文件有问题。
settings.py
import os
import socket
from pathlib import Path
from whitenoise.storage import CompressedManifestStaticFilesStorage
import docker_config
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'LisgreyWebApp',
'reservations',
'takeaway',
'food_menus',
'crispy_forms',
'bootstrap4',
'corsheaders'
]
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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'LisgreyWebApp_FYP.urls'
TEMPLATES = [
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
,
,
]
WSGI_APPLICATION = 'LisgreyWebApp_FYP.wsgi.application'
DATABASES =
'default':
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'lisgrey_database',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '25432'
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',
,
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
CRISPY_FAIL_SILENTLY = not DEBUG
BOOTSTRAP4 =
'include_jquery': True,
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home' # new
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = False
USE_TZ = True
STATIC_URL = "/static/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'dist')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
TIME_INPUT_FORMATS = [
'%H:%M %p'
]
DATE_INPUT_FORMATS = [
'%d-%m-%Y'
]
Dockerfile
FROM python:3.8
RUN apt-get -y update && apt-get -y upgrade && apt-get -y install libgdal-dev
# Make a working directoir in the image and set it as working dir.
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# make sure that pip & setuptools are installed and to date
RUN pip install --upgrade pip setuptools wheel
# Get the following libraries. We caan install them "globally" on the image as it will contain only our project
RUN apt-get -y install build-essential python-cffi libcairo2 libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 libffi-dev shared-mime-info
# You should have already exported your Python library reuirements to a "requiremnts.txt" file using pip.
# Now copy this to the image and install everything in it.
COPY requirements.txt /usr/src/app
RUN pip install -r requirements.txt
# Copy everything in your Django project to the image.
COPY . /usr/src/app
# Make sure that static files are up to date and available
RUN python manage.py collectstatic --no-input
# Expose port 8001 on the image. We'll map a localhost port to this later.
EXPOSE 8001
# Run "uwsgi". uWSGI is a Web Server Gateway Interface (WSGI) server implementation that is typically used to run Python
# web applications.
CMD ["uwsgi", "--ini", "uwsgi.ini"]
uwsgi.ini
[uwsgi]
chdir = %d
# %d is the dir this configuration file is in
#socket = %dapp.sock
http = :8001
module = LisgreyWebApp_FYP.wsgi:application
chmod-socket=664
master = true
processes = 4
vacuum = true
enable-threads = true
容器日志
[uWSGI] getting INI configuration from uwsgi.ini
*** Starting uWSGI 2.0.19.1 (64bit) on [Fri Mar 5 18:59:51 2021] ***
compiled with version: 8.3.0 on 05 March 2021 15:28:29
os: Linux-5.8.0-44-generic #50-Ubuntu SMP Tue Feb 9 06:29:41 UTC 2021
nodename: ebc63a00d1a7
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /usr/src/app
detected binary path: /usr/local/bin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
chdir() to /usr/src/app/
your memory page size is 4096 bytes
detected max file descriptor number: 1048576
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :8001 fd 4
uwsgi socket 0 bound to TCP address 127.0.0.1:33037 (port auto-assigned) fd 3
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
Python version: 3.8.8 (default, Feb 19 2021, 17:55:44) [GCC 8.3.0]
Python main interpreter initialized at 0x559f4a88c290
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 364600 bytes (356 KB) for 4 cores
*** Operational MODE: preforking ***
WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x559f4a88c290 pid: 1 (default app)
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** uWSGI is running in multiple interpreter mode ***
【问题讨论】:
改为查看 Django 日志。 @IvanStarostin 如何检查 Django 容器日志,它在我的本地工作正常,而 docker 不在服务器上工作 【参考方案1】:发现我正在尝试连接到不同名称的数据库。检查了我的数据库容器和应用程序容器的日志以找出这一点。
【讨论】:
以上是关于Django + Docker - 服务器错误 500。长帖子的主要内容,如果未能解决你的问题,请参考以下文章
Django docker 容器无法连接到 mysql 容器,出现错误“无法连接到 'db' (111) 上的 MySQL 服务器”)
Docker + Django + Vue.js + Webpack 如何正确配置 nginx?
创建测试数据库时出错 - django、docker、mysql
无法使用 django-channels 连接到 websocket,docker 上的 nginx 作为服务