2.Helm Template Ingress的使用

演示资源已提交k8s-helm-tpl - Repos (azure.com)

目录

前言

Enable Ingress

1. 更新values.yaml和ingress.yaml 

2. Helm Upgrade

​3. SwitchHosts 访问

Helm Template YAML

Chart.yaml

values.yaml 

_helpers.tpl

NOTES.txt


前言

书接上文,我们毫不夸张的演示了如何使用HelmTemplate 将一个新建的Blazor Server项目3分钟打包成Helm Chart并部署至k8s

但并没有介绍helm template的具体细节,接下来我们为部署到Cluster的service开启ingress,并且看下helm template自动生成的YAML文件是如何工作的。

Enable Ingress

!首先需要确保你的cluster有可用的 ingress-nginx

1. 更新values.yaml和ingress.yaml 

Enable Ingress Commit 95e27417: Enable ingress - Repos (azure.com)

简单修改下values.yaml和ingress.yaml 即可: 

了解过Blazor Server 的朋友知道,它是在服务端使用对象状态图来记录页面状态,并根据传来的页面事件更新状态图,之后将变化部分通过SignalR推送至浏览器渲染响应。

因此这里根据官方文档Blazor Server Kubernetes Deploy添加部分 annotations,以实现粘性会话。

2. Helm Upgrade

 3. SwitchHosts 访问

至此,一个Helm Chart所需的内容我们已基本实现。接下来,我们回头看下Helm Template为我们生成的文件都有什么作用。

Helm Template YAML

在Helm Template 使用一套简单易懂的语法规则,我们可以用来定义变量并引用;也可以通过.Values.xxx 来访问values.yaml中提供的配置参数;还可以使用range等关键字来访问一个数组变量等等。

Helm Template同样会生成deployment.yaml, ingress.yaml等常规文件,但其中只有少量的直接定义,大多配置项定义在了以下几个yaml里,并通过特定的语法规则进行引用。

Chart.yaml

Chart.yaml包含了对Helm Chart的定义,例如chart name,description,version等。

apiVersion: v2
name: helm-tpl-test-blazor-demo
description: A balzor demo helm chart for Kubernetes

# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application

# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 1.0.1

# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
appVersion: 1.0.1

values.yaml 

Helm Template会为我们自动生成deployment,ingress,serviceaccount等模板,values.yaml中为它们所需要的配置参数提供统一的定义入口。

例如我们前面演示用到的,image,imagePullSecrets,ingress configuration等等。

我们也可以在其中定义一些deployment.yaml所需要的内容,以便创建或覆盖程序运行所需要的环境变量。

# Default values for helm-tpl-test-blazor-demo.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

replicaCount: 2

image:
  repository: docker.io/phone8848/blazor-demo
  pullPolicy: IfNotPresent
  # Overrides the image tag whose default is the chart appVersion.
  tag: "v1"

imagePullSecrets: 
  - name: phone8848-auth
nameOverride: ""
fullnameOverride: ""

serviceAccount:
  # Specifies whether a service account should be created
  create: true
  # Annotations to add to the service account
  annotations: {}
  # The name of the service account to use.
  # If not set and create is true, a name is generated using the fullname template
  name: ""

podAnnotations: {}

podSecurityContext: {}
  # fsGroup: 2000

service:
  type: ClusterIP
  port: 80

ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: "affinity"
    nginx.ingress.kubernetes.io/session-cookie-expires: "14400"
    nginx.ingress.kubernetes.io/session-cookie-max-age: "14400"
  hosts:
    - host: k8s-helm-tpl-test.local
      paths: 
        - /
  tls: 
   - secretName: helm-demo-tls
     hosts:
       - k8s-helm-tpl-test.local

resources: {}
  # We usually recommend not to specify default resources and to leave this as a conscious
  # choice for the user. This also increases chances charts run on environments with little
  # resources, such as Minikube. If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #   cpu: 100m
  #   memory: 128Mi
  # requests:
  #   cpu: 100m
  #   memory: 128Mi

_helpers.tpl

_helpers.tpl 主要用来定义各种name,deployment name, ingress name, labels name等等。

{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "helm-tpl-test-blazor-demo.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "helm-tpl-test-blazor-demo.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "helm-tpl-test-blazor-demo.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Common labels
*/}}
{{- define "helm-tpl-test-blazor-demo.labels" -}}
helm.sh/chart: {{ include "helm-tpl-test-blazor-demo.chart" . }}
{{ include "helm-tpl-test-blazor-demo.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

{{/*
Selector labels
*/}}
{{- define "helm-tpl-test-blazor-demo.selectorLabels" -}}
app.kubernetes.io/name: {{ include "helm-tpl-test-blazor-demo.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{/*
Create the name of the service account to use
*/}}
{{- define "helm-tpl-test-blazor-demo.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "helm-tpl-test-blazor-demo.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}

NOTES.txt

也不要小瞧这个文件哦,每次我们helm install或者helm upgrade成功之后提示的Notes就来自于它。 

1. Get the application URL by running these commands:
{{- if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
  {{- range .paths }}
  http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ . }}
  {{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
  export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "helm-tpl-test-blazor-demo.fullname" . }})
  export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
  echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
     NOTE: It may take a few minutes for the LoadBalancer IP to be available.
           You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "helm-tpl-test-blazor-demo.fullname" . }}'
  export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "helm-tpl-test-blazor-demo.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}")
  echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
  export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "helm-tpl-test-blazor-demo.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
  echo "Visit http://127.0.0.1:8080 to use your application"
  kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:80
{{- end }}

Helm Template的大体结构与基本应用就是这样啦,是不是非常简单呢。 

<think>好的,我现在需要帮助用户解决如何在使用Helm安装模式时配置自定义的defaultBackend页面。首先,用户的问题是关于Kubernetes Ingress Controller的,特别是使用Helm来部署,并且想要使用自己的错误页面作为默认后端。 用户之前的问题涉及到多个Ingress配置和默认错误重定向的范围,现在他们进一步询问如何具体配置自己的defaultBackend。这意味着他们可能已经了解了默认后端的作用,现在需要具体的操作步骤。 首先,我需要回忆Helm chart的结构,尤其是Nginx Ingress Controller的Helm chart。通常,配置defaultBackend需要在values.yaml文件中进行设置。默认情况下,Helm chart会部署一个默认的后端服务来处理未匹配的请求,但用户想要替换成自己的。 接下来,我需要确定如何覆盖这个默认后端。可能需要用户创建一个自己的Deployment和Service,然后通过Helm的values文件指向这个Service。同时,需要注意可能的注解或配置参数,比如controller.defaultBackend.enabled是否要设置为false,以避免使用默认的后端。 另外,用户可能希望他们的自定义defaultBackend能够返回特定的错误页面,比如404页面。因此,可能需要构建一个自定义的镜像,或者使用现有的Web服务器配置来提供这些页面。例如,使用Nginx或Apache镜像,配置好自定义错误页面,然后部署到集群中。 然后,需要考虑Helm安装时的具体参数。例如,在values.yaml中,controller.defaultBackendService字段需要指向用户创建的Service的名称和命名空间。同时,可能需要禁用默认的后端部署,以避免冲突。 还需要验证配置是否正确。用户可能需要检查安装后的Ingress Controller是否正确地引用了他们的自定义后端,以及测试未匹配的请求是否返回了预期的页面。 另外,用户可能会遇到问题,比如配置未生效,这时候需要检查Service的selector是否与Pod的标签匹配,或者是否有网络策略阻止了流量。此外,确保自定义后端的Pod正常运行,并且服务可访问。 总结步骤应该是: 1. 创建自定义的defaultBackend Deployment和Service。 2. 配置Helm values.yaml文件,指向这个Service。 3. 禁用默认的defaultBackend部署。 4. 安装或升级Helm release。 5. 验证配置是否正确。 需要详细说明每个步骤的具体操作,例如如何编写Deployment和Service的YAML文件,如何在values.yaml中设置参数,以及如何通过命令行进行安装或升级。 可能还需要提醒用户注意版本兼容性,不同的Helm chart版本可能有不同的配置参数名称。例如,某些旧版本可能使用不同的字段名称,需要查阅对应版本的文档。 最后,给出一个示例的配置文件和Helm命令,让用户能够直接复制并修改,以适应他们的环境。同时,说明如何测试配置是否成功,例如使用curl命令访问不存在的路径,查看返回的页面内容。</think>--- ### **核心步骤** 通过 Helm 安装 Nginx Ingress Controller 时,若需使用**自定义的默认后端(Default Backend)**处理未匹配请求(如 `404`),需完成以下配置: --- ### **一、准备自定义 Default Backend** #### **1. 创建自定义后端应用** - **功能要求**:该应用需能返回自定义错误页(例如 HTML/JSON)。 - **示例 Deployment/Service**: ```yaml # custom-default-backend.yaml apiVersion: apps/v1 kind: Deployment metadata: name: custom-default-backend namespace: ingress-nginx spec: replicas: 1 selector: matchLabels: app: custom-default-backend template: metadata: labels: app: custom-default-backend spec: containers: - name: backend image: your-registry/custom-error-app:latest # 替换为你的镜像 ports: - containerPort: 8080 --- apiVersion: v1 kind: Service metadata: name: custom-default-backend namespace: ingress-nginx spec: ports: - port: 80 targetPort: 8080 selector: app: custom-default-backend ``` - **说明**:确保镜像能够监听端口并返回自定义错误内容(如静态页面)。 #### **2. 部署自定义后端** ```bash kubectl apply -f custom-default-backend.yaml ``` --- ### **二、配置 Helm Values 文件** #### **1. 修改 `values.yaml`** - **关键配置项**: ```yaml controller: defaultBackendService: "ingress-nginx/custom-default-backend" # 指向你的 Service # 关闭 Helm 自带的默认后端 defaultBackend: enabled: false # 必须禁用默认部署 # 可选:调整副本数、资源限制等 ``` - **注意**:`defaultBackendService` 格式为 `<namespace>/<service-name>`。 #### **2. 安装/升级 Ingress Controller** ```bash # 安装(首次) helm upgrade --install ingress-nginx ingress-nginx/ingress-nginx \ --namespace ingress-nginx \ -f values.yaml # 升级(已存在) helm upgrade ingress-nginx ingress-nginx/ingress-nginx \ --namespace ingress-nginx \ -f values.yaml ``` --- ### **三、验证配置** #### **1. 检查 Service 关联** ```bash kubectl describe ingress-nginx-controller -n ingress-nginx | grep "Default backend" ``` - **预期输出**:`Default backend: ingress-nginx/custom-default-backend:80 (10.244.0.5:8080)` #### **2. 测试未匹配请求** ```bash curl -H "Host: invalid.example.com" http://<ingress-ip>/non-existent-path ``` - **预期结果**:返回自定义错误页内容(如 `404.html`)。 --- ### **四、高级配置(按需)** #### **1. 动态错误页模板(Nginx 示例)** 若需根据不同错误码返回不同页面,可在自定义后端镜像中配置 Nginx: ```nginx # nginx.conf 片段 server { listen 8080; error_page 404 /404.html; error_page 502 /502.html; location / { root /usr/share/nginx/html; } } ``` #### **2. 自定义响应头** 在 Service 或 Ingress 中添加注解,控制错误响应的 Headers: ```yaml # Ingress 示例 metadata: annotations: nginx.ingress.kubernetes.io/default-backend: "custom-default-backend" nginx.ingress.kubernetes.io/configuration-snippet: | more_set_headers "X-Custom-Error: true"; ``` --- ### **故障排查** | **问题现象** | **解决方案** | |------------------------------|-----------------------------------------| | 返回默认后端(非自定义内容) | 检查 `defaultBackendService` 命名空间是否匹配 | | 自定义后端无响应 | 确认 Pod 日志无报错,Service 端口映射正确 | | Helm 升级失败 | 回滚并检查 `values.yaml` 格式是否正确 | --- ### **最佳实践** - **镜像优化**:使用轻量级镜像(如 Alpine + Nginx)减少资源占用。 - **监控告警**:为自定义后端配置健康检查(Readiness/Liveness Probe)。 - **多环境隔离**:为不同集群(生产/测试)配置不同的错误页模板。 通过以上步骤,即可将默认错误处理完全交由业务自定义的后端服务控制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值