Py学习  »  Django

使用nginx在Django-ALLOWED_主机中处理动态IP

Olsson • 3 年前 • 1350 次点击  

我认为我的nginx有问题。conf,这会导致实例一次又一次地重新启动,因为我的托管容器服务的运行状况检查失败。

我在AWS Lightsail容器中运行我的设置,其中有三个容器运行:

  • nginx
  • 德扬戈
  • nextjs

在我的AWS Lightsail实例上发布新版本时,它会正常运行几分钟,然后我遇到503错误,导致实例重新启动-运行几分钟,然后再次重新启动。

查看日志,我可以看到运行状况检查失败,django抛出一个错误,说我应该将请求IP添加到允许的主机:

[28/Aug/2021:13:56:23] Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add 'x.x.x.x' to ALLOWED_HOSTS.
[28/Aug/2021:13:56:23] Bad Request: /health.txt

问题是我的lightsail集装箱服务没有静态IP(我也不相信我能获得静态IP)。

我现在的nginx。下面是conf(感谢您的反馈)。 我的问题 以下是我应该如何处理这个问题?我想坐下来 ALLOWED_HOSTS = ['*'] 这不是一个好方法。我可以为健康检查或类似检查硬编码主机吗?

nginx。形态:

upstream backend {
    server ${BACKEND_HOST}:${BACKEND_PORT};
}
upstream frontend {
    server ${FRONTEND_HOST}:${FRONTEND_PORT};
}

server {
    listen 80 default_server;
    server_name example.com;
    server_tokens off;

    gzip on;
    gzip_proxied any;
    gzip_comp_level 4;
    gzip_types text/css application/javascript image/svg+xml;

    location /robots.txt {
        include proxy_params;
        proxy_pass http://backend;
    }

    location /health.txt {
        include proxy_params;
        proxy_pass http://backend;
    }

    location /api {
        include proxy_params;
        proxy_pass http://backend;
    }

    location /admin {
        include proxy_params;
        proxy_pass http://backend;
    }
    
    location / {
        proxy_pass http://frontend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133198
 
1350 次点击  
文章 [ 1 ]  |  最新文章 3 年前
RedWheelbarrow
Reply   •   1 楼
RedWheelbarrow    3 年前

我使用AWS EC2,通过健康检查,动态获取实例的ip,然后将其插入允许的_主机(我认为它也适用于Lightsail容器):

import requests

def get_instance_ip():
    try:
        ip = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4').text
    except requests.exceptions.ConnectionError:
        return None
    return ip

AWS_IP = get_ec2_instance_ip()

if AWS_IP is not None:
    ALLOWED_HOSTS += [AWS_IP]

您还可以创建一个中间件,该中间件始终为健康检查使用的路径返回200状态代码(在之前插入自定义中间件) django.middleware.security.SecurityMiddleware 在里面 MIDDLEWARE Invalid HTTP_HOST header 错误)。