如何使用 Django ALLOWED_HOSTS = [my-site.com] 通过 AWS ELB 健康检查

问题描述 投票:0回答:1

我使用 Gunicorn 和 nginx 通过 ECS(Dockerized)在 AWS 上部署了一个 Django 应用程序。作为

DEBUG=False 
对于 Django 部署,我配置了一个日志记录设置,以通过
mail_admins
接收有关警告及以上的日志。

通过 nginx 配置的标准设置(如下),我开始收到大量带有“BadRequest”或“DisallowedHost”错误(最有可能是扫描/抓取机器人)的日志(邮件),这些日志(邮件)被 Django 拒绝,因为我设置了我的

ALLOWED_HOSTS=[my-site.com] 
.

nginx.conf

upstream django-backend {
    server 172.17.0.1:8000;
}

server {
    listen 80;

    location / {
        proxy_pass http://django-backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
    }
}

我按照以下解决方案中的示例来阻止访问我的 Django 应用程序的流量:

最终 nginx.conf 更新为:

server {
    listen      80;
    server_name "";
    return      444;
}

server {
    listen 80;
    server_name my-site.com;
    # Rest of configuration
}

这工作得很好,但是,我无法以这种方式设置 nginx 来允许 AWS ELB 执行运行状况检查,并且我在 AWS 中有以下日志:

xxx.xx.xx.xx - - [26/Feb/2024:19:30:03 +0000] "GET /health HTTP/1.1" 444 0 "-" "ELB-HealthChecker/2.0" "-"
xxx.xx.xx.xx - - [26/Feb/2024:19:30:03 +0000] "GET /health HTTP/1.1" 444 0 "-" "ELB-HealthChecker/2.0" "-"
xxx.xx.xx.xx - - [26/Feb/2024:19:30:03 +0000] "GET /health HTTP/1.1" 444 0 "-" "ELB-HealthChecker/2.0" "-"

我设置了健康检查:@Watt Iamsuri 在这里

有人对这种情况下如何通过AWS ELB健康检查的解决方案有任何建议吗?

django amazon-web-services nginx amazon-elb
1个回答
0
投票

健康检查会失败,因为ELB健康检查时请求的Host头设置为容器的私有IP地址。需要将此 IP 地址添加到 Django 设置中的 ALLOWED_HOSTS 列表中。

您可以将其设置为动态更新:

from socket import gethostbyname
from socket import gethostname

# assuming ALLOWED_HOSTS is set in your environment as so:
# ALLOWED_HOSTS='domain.com,anotherdomain.com'

ALLOWED_HOSTS = os.environ.get("ALLOWED_HOST").split(",") #or however you set it.
ALLOWED_HOSTS.append(gethostbyname(gethostname()))

在此处阅读有关此内容的完整文章

© www.soinside.com 2019 - 2024. All rights reserved.