我在Azure Kubernetes群集中具有一些基本配置的前端服务的Django部署。但是请注意,同样的问题适用于我的本地Minikube集群。我从远程容器注册表中获取了Django前端容器映像,并公开了port 8010
。我的服务配置也很简单。
frontend.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-v1
labels:
app: frontend-v1
spec:
replicas: 1
selector:
matchLabels:
app: frontend-v1
template:
metadata:
labels:
app: frontend-v1
spec:
containers:
- name: frontend-v1
imagePullPolicy: Always
image: yourremotename.azurecr.io/frontend-remote:v1
ports:
- containerPort: 8010
imagePullSecrets:
- name: acr-secret
frontend.service.yaml
kind: Service
apiVersion: v1
metadata:
name: frontend-v1
spec:
selector:
app: frontend-v1
ports:
- NodePort:
protocol: TCP
port: 8010
targetPort: 8010
type: NodePort
现在,当我在浏览器中访问我部署的前端服务时,即http://172.17.194.253:31436 与Django的设置DEBUG = True
,我得到了错误:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py", line 93, in __call__
response = self.process_request(request)
File "/usr/local/lib/python3.6/dist-packages/django/middleware/common.py", line 48, in process_request
host = request.get_host()
File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 122, in get_host
raise DisallowedHost(msg)
Exception Type: DisallowedHost at /
Exception Value: Invalid HTTP_HOST header: '172.17.194.253:31436'. You may need to add '172.17.194.253' to ALLOWED_HOSTS.
但是如何将Pod的动态创建的HostIp绑定到Django的ALLOWED_HOSTS
?
答案 0 :(得分:4)
从Kubernetes 1.7开始,可以在kubernetes部署文件中请求Pod的HostIp。(1)
首先调整部署文件以设置HostIp所需的环境变量。在下面的方案中,我设置了POD_IP和HOST_IP,因为它们是不同的。您可以使用环境变量在Kubernetes部署文件中注入各种Kubernetes应用程序数据变量,有关此主题的更多信息,请查看here。
frontend.service.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-v1
labels:
app: frontend-v1
spec:
replicas: 1
selector:
matchLabels:
app: frontend-v1
template:
metadata:
labels:
app: frontend-v1
spec:
containers:
- name: frontend-v1
imagePullPolicy: Always
image: yourremotename.azurecr.io/frontend-remote:v1
ports:
- containerPort: 8010
env:
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: HOST_IP
valueFrom:
fieldRef:
fieldPath: status.hostIP
imagePullSecrets:
- name: acr-secret
现在,您的Django设置将ALLOWED_HOSTS
配置调整为指向HOST_IP
环境变量。
settings.py
import os
...
ALLOWED_HOSTS = [os.environ.get('HOST_IP'), '127.0.0.1']
....
请注意,这允许pod的HostIP以及本地主机用于本地开发。
警告!!一些博客文章或教程建议您将ALLOWED_HOSTS = ['*']
设置为接受所有主机IP,但这是一个严重的安全漏洞。不要这样做!
现在重新部署您的pod,并且Django应用程序应该可以再次平稳运行。