这有点棘手,因为您需要使用 EB 动态声明您的 ALLOWED_HOSTS。这个article 在 Gotcha #3 中提供了一些关于如何实现这一目标的好信息
我会创建一个单独的设置文件,名为 settings_production.py,然后您可以在其中放置以下代码:
mysite/settings_production.py
from mysite.settings import *
def is_ec2_linux():
"""Detect if we are running on an EC2 Linux Instance
See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
"""
if os.path.isfile("/sys/hypervisor/uuid"):
with open("/sys/hypervisor/uuid") as f:
uuid = f.read()
return uuid.startswith("ec2")
return False
def get_linux_ec2_private_ip():
"""Get the private IP Address of the machine if running on an EC2 linux server"""
from urllib.request import urlopen
if not is_ec2_linux():
return None
try:
response = urlopen('http://169.254.169.254/latest/meta-data/local-ipv4')
return response.read().decode("utf-8")
except:
return None
finally:
if response:
response.close()
# ElasticBeanstalk healthcheck sends requests with host header = internal ip
# So we detect if we are in elastic beanstalk,
# and add the instances private ip address
private_ip = get_linux_ec2_private_ip()
if private_ip:
ALLOWED_HOSTS += [private_ip, 'your-django-env.elasticbeanstalk.com']
# Other production overrides
DEBUG = False
现在您将“DJANGO_SETTINGS_MODULE”环境变量设置为mysite.production_settings,用于您的生产环境(即您的EB 环境)。
更新:
我决定用它来进行测试,并设法让它运行起来。不过我发现了一些东西。上述代码将每个实例的内部 IP 添加到 ALLOWED_HOSTS。这纯粹是为了健康检查,以便 AWS 控制台可以在内部 ping 实例并接收 200OK 响应。我将离开上述解决方案,因为它仍然适用于此目的。但它不会解决您的特定错误。要为您服务,只需添加您的 EB 网址即可。您可以在 AWS 控制台(下面以红色突出显示)或通过键入 eb status 并检查 CNAME 属性在 cli 中找到它。
配置:
这是我在源代码中手动创建的基本配置文件:
.ebextensions/django.config
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: mysite/wsgi.py
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: mysite.settings_production
.ebextensions/db-migrate.config
container_commands:
01_migrate:
command: "django-admin.py migrate"
leader_only: true
option_settings:
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: mysite.settings_production