【服务发现--ingress】

1、ingress介绍

在这里插入图片描述

  • Ingress 提供从集群外部到集群内服务的 HTTP 和 HTTPS 路由。 流量路由由 Ingress 资源所定义的规则来控制。

  • Ingress 是对集群中服务的外部访问进行管理的 API 对象,典型的访问方式是 HTTP。

  • Ingress 可以提供负载均衡、SSL 终结和基于名称的虚拟托管。

2、ingress 的依赖

  • 你必须拥有一个 Ingress 控制器 才能满足 Ingress 的要求。仅创建 Ingress 资源本身没有任何效果。

  • 你可能需要部署一个 Ingress 控制器,例如 ingress-nginx。 你可以从许多 (Ingress 控制器)中进行选择。

  • 理想情况下,所有 Ingress 控制器都应遵从参考规范。 但实际上,各个 Ingress 控制器操作略有不同。

3、ingress-nginx 安装流程

参考链接:https://kubernetes.github.io/ingress-nginx/deploy/

3.1 k8s的包管理器 Helm 安装

  • Helm官网:https://helm.sh/zh/docs/intro/quickstart/
  • 注:安装Helm的时候需要注意k8s的版本
# 下载helm 
[root@k8s-master ~]# wget https://get.helm.sh/helm-v3.10.0-linux-amd64.tar.gz  -O helm-v3.10.0-linux-amd64.tar.gz

[root@k8s-master ~]# tar -zxvf helm-v3.10.0-linux-amd64.tar.gz

[root@k8s-master ~]# mv linux-amd64/helm /usr/local/bin/
[root@k8s-master ~]# helm version
version.BuildInfo{Version:"v3.10.0", GitCommit:"ce66412a723e4d89555dc67217607c6579ffcb21", GitTreeState:"clean", GoVersion:"go1.18.6"}


3.2 添加helm仓库

[root@k8s-master ~]# helm repo add ingress-nginx  https://kubernetes.github.io/ingress-nginx
"ingress-nginx" has been added to your repositories
[root@k8s-master ~]# helm repo list
NAME         	URL
ingress-nginx	https://kubernetes.github.io/ingress-nginx
[root@k8s-master ~]# helm search repo  ingress-nginx
NAME                       	CHART VERSION	APP VERSION	DESCRIPTION
ingress-nginx/ingress-nginx	4.9.1        	1.9.6      	Ingress controller for Kubernetes using NGINX a...

3.3 通过helm下载ingress-nginx

下载ingress-nginx的时候需要查看版本是否匹配k8s的版本:地址链接查看新版本是否支持,由于我的k8s版本是1.25,所以最新的v1.9.6可以使用。
在这里插入图片描述

[root@k8s-master ~]# helm pull ingress-nginx/ingress-nginx
[root@k8s-master ~]# ll ingress-nginx-4.9.1.tgz
-rw-r--r--. 1 root root 53966 225 14:38 ingress-nginx-4.9.1.tgz
[root@k8s-master ~]# mv ingress-nginx-4.9.1.tgz  /opt/helm/
[root@k8s-master ~]# cd !$
cd /opt/helm

[root@k8s-master helm]# ll
总用量 4088
-rw-r--r--. 1 root root 2293749 225 14:40 helm-v3.10.0-linux-amd64.tar.gz
-rw-r--r--. 1 root root   53966 225 14:38 ingress-nginx-4.9.1.tgz

[root@k8s-master helm]# tar -xf ingress-nginx-4.9.1.tgz

[root@k8s-master helm]# cd ingress-nginx
[root@k8s-master ingress-nginx]# ll 
总用量 128
drwxr-xr-x. 2 root root  4096 225 14:40 changelog
-rw-r--r--. 1 root root   702 127 15:46 Chart.yaml
drwxr-xr-x. 2 root root  4096 225 14:40 ci
-rw-r--r--. 1 root root   213 127 15:46 OWNERS
-rw-r--r--. 1 root root 48217 127 15:46 README.md
-rw-r--r--. 1 root root 11358 127 15:46 README.md.gotmpl
drwxr-xr-x. 3 root root  4096 225 14:40 templates
drwxr-xr-x. 2 root root  4096 225 14:40 tests
-rw-r--r--. 1 root root 44163 127 15:46 values.yaml

3.4 修改values.yaml参数配置

3.4.1 修改ingress的控制器的镜像地址为国内地址

registry: registry.cn-hangzhou.aliyuncs.com
image: google_containers/nginx-ingress-controller

在这里插入图片描述

在这里插入图片描述

3.4.2 注释ingress的控制器中的哈希校验

在这里插入图片描述

3.4.3 修改dnsPolicy的值为 ClusterFirstWithHostNet

在这里插入图片描述

3.4.4 修改hostNetwork的值为true

在这里插入图片描述

3.4.5 修改kind的值为DaemonSET

在这里插入图片描述

3.4.6 在nodeSelector下添加 ingress: “true”

在这里插入图片描述

3.4.7 修改这里的type的值为ClusterIP

在这里插入图片描述

3.4.8 修改enabled的值为false

在这里插入图片描述

3.4.9 修改kube-webhook处的镜像地址和type

registry: registry.cn-hangzhou.aliyuncs.com
image: google_containers/kube-webhook-certgen

在这里插入图片描述

3.5 创建这个ingress资源

3.5.1 专门为ingress-nginx创建一个namespace

[root@k8s-master ingress-nginx]# kubectl create ns  ingress-nginx
namespace/ingress-nginx created

3.5.2 为需要部署的ingress节点上添加标签

[root@k8s-master ingress-nginx]# kubectl label node k8s-master ingress=true
node/k8s-master labeled

[root@k8s-master ingress-nginx]# kubectl get nodes  --show-labels
NAME          STATUS   ROLES           AGE     VERSION   LABELS
k8s-master    Ready    control-plane   5d21h   v1.25.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,ingress=true,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-master,kubernetes.io/os=linux,node-role.kubernetes.io/control-plane=,node.kubernetes.io/exclude-from-external-load-balancers=
k8s-node-01   Ready    <none>          5d20h   v1.25.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node-01,kubernetes.io/os=linux,type=microsvc
k8s-node-02   Ready    <none>          3d21h   v1.25.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node-02,kubernetes.io/os=linux,type=microsvc

3.5.3 安装ingress-nginx

[root@k8s-master ingress-nginx]# ll
总用量 128
drwxr-xr-x. 2 root root  4096 225 14:40 changelog
-rw-r--r--. 1 root root   702 127 15:46 Chart.yaml
drwxr-xr-x. 2 root root  4096 225 14:40 ci
-rw-r--r--. 1 root root   213 127 15:46 OWNERS
-rw-r--r--. 1 root root 48217 127 15:46 README.md
-rw-r--r--. 1 root root 11358 127 15:46 README.md.gotmpl
drwxr-xr-x. 3 root root  4096 225 14:40 templates
drwxr-xr-x. 2 root root  4096 225 14:40 tests
-rw-r--r--. 1 root root 44366 225 16:55 values.yaml
[root@k8s-master ingress-nginx]# helm install ingress-nginx  -n ingress-nginx .
NAME: ingress-nginx
LAST DEPLOYED: Sun Feb 25 19:35:55 2024
NAMESPACE: ingress-nginx
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
The ingress-nginx controller has been installed.
Get the application URL by running these commands:
  export POD_NAME="$(kubectl get pods --namespace ingress-nginx --selector app.kubernetes.io/name=ingress-nginx,app.kubernetes.io/instance=ingress-nginx,app.kubernetes.io/component=controller --output jsonpath="{.items[0].metadata.name}")"
  kubectl port-forward --namespace ingress-nginx "${POD_NAME}" 8080:80
  echo "Visit http://127.0.0.1:8080 to access your application."

An example Ingress that makes use of the controller:
  apiVersion: networking.k8s.io/v1
  kind: Ingress
  metadata:
    name: example
    namespace: foo
  spec:
    ingressClassName: nginx
    rules:
      - host: www.example.com
        http:
          paths:
            - pathType: Prefix
              backend:
                service:
                  name: exampleService
                  port:
                    number: 80
              path: /
    # This section is only required if TLS is to be enabled for the Ingress
    tls:
      - hosts:
        - www.example.com
        secretName: example-tls

If TLS is enabled for the Ingress, a Secret containing the certificate and key must also be provided:

  apiVersion: v1
  kind: Secret
  metadata:
    name: example-tls
    namespace: foo
  data:
    tls.crt: <base64 encoded cert>
    tls.key: <base64 encoded key>
  type: kubernetes.io/tls

3.5.4 在node1上添加一个标签

由于master有个污点的问题,所以ingress-nginx暂时无法创建上,这个问题后续在写,现在在node1上添加一个ingress=true的标签。在来查看下。

root@k8s-master ingress-nginx]# kubectl label nodes  k8s-node-01   ingress=true
node/k8s-node-01 labeled
[root@k8s-master ingress-nginx]# kubectl get -n ingress-nginx  po
NAME                             READY   STATUS              RESTARTS   AGE
ingress-nginx-controller-jn65t   0/1     ContainerCreating   0          12s



[root@k8s-master ingress-nginx]# kubectl describe   -n ingress-nginx  po  ingress-nginx-controller-jn65t
Name:             ingress-nginx-controller-jn65t
Namespace:        ingress-nginx
Priority:         0
Service Account:  ingress-nginx
Node:             k8s-node-01/10.10.10.177
Start Time:       Sun, 25 Feb 2024 19:42:49 +0800
Labels:           app.kubernetes.io/component=controller
                  app.kubernetes.io/instance=ingress-nginx
                  app.kubernetes.io/managed-by=Helm
                  app.kubernetes.io/name=ingress-nginx
                  app.kubernetes.io/part-of=ingress-nginx
                  app.kubernetes.io/version=1.9.6
                  controller-revision-hash=78d8f9c87c
                  helm.sh/chart=ingress-nginx-4.9.1
                  pod-template-generation=1
Annotations:      <none>
Status:           Running
IP:               10.10.10.177
IPs:
  IP:           10.10.10.177
Controlled By:  DaemonSet/ingress-nginx-controller
Containers:
  controller:
    Container ID:  docker://5a25f4de88555d15c0a335afda6dcbe02fed2bcf992c30a06c02b05397c50649
    Image:         registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-ingress-controller:v1.9.6
    Image ID:      docker-pullable://registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-ingress-controller@sha256:195a471f4765b6c752919003bf5b9a029b250531f9f48caf0beae64495daa4c2
    Ports:         80/TCP, 443/TCP
    Host Ports:    80/TCP, 443/TCP
    Args:
      /nginx-ingress-controller
      --publish-service=$(POD_NAMESPACE)/ingress-nginx-controller
      --election-id=ingress-nginx-leader
      --controller-class=k8s.io/ingress-nginx
      --ingress-class=nginx
      --configmap=$(POD_NAMESPACE)/ingress-nginx-controller
    State:          Running
      Started:      Sun, 25 Feb 2024 19:43:12 +0800
    Ready:          True
    Restart Count:  0
    Requests:
      cpu:      100m
      memory:   90Mi
    Liveness:   http-get http://:10254/healthz delay=10s timeout=1s period=10s #success=1 #failure=5
    Readiness:  http-get http://:10254/healthz delay=10s timeout=1s period=10s #success=1 #failure=3
    Environment:
      POD_NAME:       ingress-nginx-controller-jn65t (v1:metadata.name)
      POD_NAMESPACE:  ingress-nginx (v1:metadata.namespace)
      LD_PRELOAD:     /usr/local/lib/libmimalloc.so
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-dklj9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  kube-api-access-dklj9:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   Burstable
Node-Selectors:              ingress=true
                             kubernetes.io/os=linux
Tolerations:                 node.kubernetes.io/disk-pressure:NoSchedule op=Exists
                             node.kubernetes.io/memory-pressure:NoSchedule op=Exists
                             node.kubernetes.io/network-unavailable:NoSchedule op=Exists
                             node.kubernetes.io/not-ready:NoExecute op=Exists
                             node.kubernetes.io/pid-pressure:NoSchedule op=Exists
                             node.kubernetes.io/unreachable:NoExecute op=Exists
                             node.kubernetes.io/unschedulable:NoSchedule op=Exists
Events:
  Type    Reason     Age   From                      Message
  ----    ------     ----  ----                      -------
  Normal  Scheduled  45s   default-scheduler         Successfully assigned ingress-nginx/ingress-nginx-controller-jn65t to k8s-node-01
  Normal  Pulling    44s   kubelet                   Pulling image "registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-ingress-controller:v1.9.6"
  Normal  Pulled     23s   kubelet                   Successfully pulled image "registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-ingress-controller:v1.9.6" in 20.899701523s
  Normal  Created    23s   kubelet                   Created container controller
  Normal  Started    22s   kubelet                   Started container controller
  Normal  RELOAD     20s   nginx-ingress-controller  NGINX reload triggered due to a change in configuration



[root@k8s-master ingress-nginx]# kubectl get -n ingress-nginx  po  -owide
NAME                             READY   STATUS    RESTARTS   AGE   IP             NODE          NOMINATED NODE   READINESS GATES
ingress-nginx-controller-jn65t   1/1     Running   0          2m    10.10.10.177   k8s-node-01   <none>           <none>

3.5.5 配置文件

[root@k8s-master ingress-nginx]# grep -Ev  '^#|^  #|^    #|^      #|^        #|^$'  values.yaml
namespaceOverride: ""
commonLabels: {}
controller:
  name: controller
  enableAnnotationValidations: false
  image:
    chroot: false
    registry: registry.cn-hangzhou.aliyuncs.com
    image: google_containers/nginx-ingress-controller
    tag: "v1.9.6"
    pullPolicy: IfNotPresent
    runAsNonRoot: true
    runAsUser: 101
    allowPrivilegeEscalation: false
    seccompProfile:
      type: RuntimeDefault
    readOnlyRootFilesystem: false
  existingPsp: ""
  containerName: controller
  containerPort:
    http: 80
    https: 443
  config: {}
  configAnnotations: {}
  proxySetHeaders: {}
  addHeaders: {}
  dnsConfig: {}
  hostAliases: []
  hostname: {}
  dnsPolicy: ClusterFirstWithHostNet
  reportNodeInternalIp: false
  watchIngressWithoutClass: false
  ingressClassByName: false
  enableTopologyAwareRouting: false
  allowSnippetAnnotations: false
  hostNetwork: true
  hostPort:
    enabled: false
    ports:
      http: 80
      https: 443
  networkPolicy:
    enabled: false
  electionID: ""
  ingressClassResource:
    name: nginx
    enabled: true
    default: false
    controllerValue: "k8s.io/ingress-nginx"
    parameters: {}
  ingressClass: nginx
  podLabels: {}
  podSecurityContext: {}
  sysctls: {}
  containerSecurityContext: {}
  publishService:
    enabled: true
    pathOverride: ""
  scope:
    enabled: false
    namespace: ""
    namespaceSelector: ""
  configMapNamespace: ""
  tcp:
    configMapNamespace: ""
    annotations: {}
  udp:
    configMapNamespace: ""
    annotations: {}
  maxmindLicenseKey: ""
  extraArgs: {}
  extraEnvs: []
  kind: DaemonSet
  annotations: {}
  labels: {}
  updateStrategy: {}
  minReadySeconds: 0
  tolerations: []
  affinity: {}
  topologySpreadConstraints: []
  terminationGracePeriodSeconds: 300
  nodeSelector:
    kubernetes.io/os: linux
    ingress: "true"
  livenessProbe:
    httpGet:
      path: "/healthz"
      port: 10254
      scheme: HTTP
    initialDelaySeconds: 10
    periodSeconds: 10
    timeoutSeconds: 1
    successThreshold: 1
    failureThreshold: 5
  readinessProbe:
    httpGet:
      path: "/healthz"
      port: 10254
      scheme: HTTP
    initialDelaySeconds: 10
    periodSeconds: 10
    timeoutSeconds: 1
    successThreshold: 1
    failureThreshold: 3
  healthCheckPath: "/healthz"
  healthCheckHost: ""
  podAnnotations: {}
  replicaCount: 1
  minAvailable: 1
  resources:
    requests:
      cpu: 100m
      memory: 90Mi
  autoscaling:
    enabled: false
    annotations: {}
    minReplicas: 1
    maxReplicas: 11
    targetCPUUtilizationPercentage: 50
    targetMemoryUtilizationPercentage: 50
    behavior: {}
  autoscalingTemplate: []
  keda:
    apiVersion: "keda.sh/v1alpha1"
    enabled: false
    minReplicas: 1
    maxReplicas: 11
    pollingInterval: 30
    cooldownPeriod: 300
    restoreToOriginalReplicaCount: false
    scaledObject:
      annotations: {}
    triggers: []
    behavior: {}
  enableMimalloc: true
  customTemplate:
    configMapName: ""
    configMapKey: ""
  service:
    enabled: true
    external:
      enabled: true
    annotations: {}
    labels: {}
    type: ClusterIP
    clusterIP: ""
    externalIPs: []
    loadBalancerIP: ""
    loadBalancerSourceRanges: []
    loadBalancerClass: ""
    externalTrafficPolicy: ""
    sessionAffinity: ""
    ipFamilyPolicy: SingleStack
    ipFamilies:
      - IPv4
    enableHttp: true
    enableHttps: true
    ports:
      http: 80
      https: 443
    targetPorts:
      http: http
      https: https
    appProtocol: true
    nodePorts:
      http: ""
      https: ""
      tcp: {}
      udp: {}
    internal:
      enabled: false
      annotations: {}
      type: ""
      clusterIP: ""
      externalIPs: []
      loadBalancerIP: ""
      loadBalancerSourceRanges: []
      loadBalancerClass: ""
      externalTrafficPolicy: ""
      sessionAffinity: ""
      ipFamilyPolicy: SingleStack
      ipFamilies:
        - IPv4
      ports: {}
      targetPorts: {}
      appProtocol: true
      nodePorts:
        http: ""
        https: ""
        tcp: {}
        udp: {}
  shareProcessNamespace: false
  extraContainers: []
  extraVolumeMounts: []
  extraVolumes: []
  extraInitContainers: []
  extraModules: []
  opentelemetry:
    enabled: false
    name: opentelemetry
    image:
      registry: registry.k8s.io
      image: ingress-nginx/opentelemetry
      tag: "v20230721-3e2062ee5"
      digest: sha256:13bee3f5223883d3ca62fee7309ad02d22ec00ff0d7033e3e9aca7a9f60fd472
      distroless: true
    containerSecurityContext:
      runAsNonRoot: true
      runAsUser: 65532
      allowPrivilegeEscalation: false
      seccompProfile:
        type: RuntimeDefault
      capabilities:
        drop:
          - ALL
      readOnlyRootFilesystem: true
    resources: {}
  admissionWebhooks:
    name: admission
    annotations: {}
    enabled: false
    extraEnvs: []
    failurePolicy: Fail
    port: 8443
    certificate: "/usr/local/certificates/cert"
    key: "/usr/local/certificates/key"
    namespaceSelector: {}
    objectSelector: {}
    labels: {}
    existingPsp: ""
    service:
      annotations: {}
      externalIPs: []
      loadBalancerSourceRanges: []
      servicePort: 443
      type: ClusterIP
    createSecretJob:
      name: create
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        allowPrivilegeEscalation: false
        seccompProfile:
          type: RuntimeDefault
        capabilities:
          drop:
            - ALL
        readOnlyRootFilesystem: true
      resources: {}
    patchWebhookJob:
      name: patch
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        allowPrivilegeEscalation: false
        seccompProfile:
          type: RuntimeDefault
        capabilities:
          drop:
            - ALL
        readOnlyRootFilesystem: true
      resources: {}
    patch:
      enabled: true
      image:
        registry: registry.cn-hangzhou.aliyuncs.com
        image: google_containers/kube-webhook-certgen
        tag: v20231226-1a7112e06
      priorityClassName: ""
      podAnnotations: {}
      networkPolicy:
        enabled: false
      nodeSelector:
        kubernetes.io/os: linux
      tolerations: []
      labels: {}
      securityContext: {}
    certManager:
      enabled: false
      rootCert:
        duration: ""
      admissionCert:
        duration: ""
  metrics:
    port: 10254
    portName: metrics
    enabled: false
    service:
      annotations: {}
      labels: {}
      externalIPs: []
      loadBalancerSourceRanges: []
      servicePort: 10254
      type: ClusterIP
    serviceMonitor:
      enabled: false
      additionalLabels: {}
      annotations: {}
      namespace: ""
      namespaceSelector: {}
      scrapeInterval: 30s
      targetLabels: []
      relabelings: []
      metricRelabelings: []
    prometheusRule:
      enabled: false
      additionalLabels: {}
      rules: []
  lifecycle:
    preStop:
      exec:
        command:
          - /wait-shutdown
  priorityClassName: ""
revisionHistoryLimit: 10
defaultBackend:
  enabled: false
  name: defaultbackend
  image:
    registry: registry.k8s.io
    image: defaultbackend-amd64
    tag: "1.5"
    pullPolicy: IfNotPresent
    runAsNonRoot: true
    runAsUser: 65534
    allowPrivilegeEscalation: false
    seccompProfile:
      type: RuntimeDefault
    readOnlyRootFilesystem: true
  existingPsp: ""
  extraArgs: {}
  serviceAccount:
    create: true
    name: ""
    automountServiceAccountToken: true
  extraEnvs: []
  port: 8080
  livenessProbe:
    failureThreshold: 3
    initialDelaySeconds: 30
    periodSeconds: 10
    successThreshold: 1
    timeoutSeconds: 5
  readinessProbe:
    failureThreshold: 6
    initialDelaySeconds: 0
    periodSeconds: 5
    successThreshold: 1
    timeoutSeconds: 5
  updateStrategy: {}
  minReadySeconds: 0
  tolerations: []
  affinity: {}
  podSecurityContext: {}
  containerSecurityContext: {}
  podLabels: {}
  nodeSelector:
    kubernetes.io/os: linux
  podAnnotations: {}
  replicaCount: 1
  minAvailable: 1
  resources: {}
  extraVolumeMounts: []
  extraVolumes: []
  extraConfigMaps: []
  autoscaling:
    annotations: {}
    enabled: false
    minReplicas: 1
    maxReplicas: 2
    targetCPUUtilizationPercentage: 50
    targetMemoryUtilizationPercentage: 50
  networkPolicy:
    enabled: false
  service:
    annotations: {}
    externalIPs: []
    loadBalancerSourceRanges: []
    servicePort: 80
    type: ClusterIP
  priorityClassName: ""
  labels: {}
rbac:
  create: true
  scope: false
podSecurityPolicy:
  enabled: false
serviceAccount:
  create: true
  name: ""
  automountServiceAccountToken: true
  annotations: {}
imagePullSecrets: []
tcp: {}
udp: {}
portNamePrefix: ""
dhParam: ""

3.6 ingress的使用

3.6.1 编写 ingress 服务的配置

apiVersion: networking.k8s.io/v1  
kind: Ingress  # ingress类型
metadata:  
  name: ingress-nginx-example  # ingress的名字
  annotations:  
    nginx.ingress.kubernetes.io/rewrite-target: /  
spec:  
  ingressClassName: nginx  
  rules:  
  - host: k8s.test.cn   # 访问域名,可是使用通配符
    http:   
      paths:  # 相当于nginx的location配置,可以配置多个
      - path: /   # 等价与nginx中的location 路径匹配 
        # 路径类型,按照路径类型进行匹配 ImplementationSpecific  需要指定IngressClass,具体匹配规则以IngressClass中的规则为准。
        # Exact 精确匹配,URL需要与path完全匹配上,且区分大小写 
        # Prefix 前缀匹配,以/作为分隔符,来进行前缀匹配
        pathType: Prefix  # 匹配模式
        backend:  
          service:  
            name: nginx-svc   # ingress转发给service,service的名字
            port:  
              number: 80     # service的端口
  # 如果有TLS配置,可以添加tls字段  
  #tls:  
  #- hosts:  
  #  - example.com  
  #  secretName: my-tls-secret

3.6.2 创建这个ingress资源

[root@k8s-master ~]# kubectl create -f ingress-nginx-example.yaml
ingress.networking.k8s.io/ingress-nginx-example created

3.6.3 查看这个ingress资源信息

[root@k8s-master ~]# kubectl get ingress ingress-nginx-example  -o wide
NAME                    CLASS   HOSTS         ADDRESS        PORTS   AGE
ingress-nginx-example   nginx   k8s.test.cn   10.1.119.138   80      50s

[root@k8s-master ~]# kubectl get -n ingress-nginx    pod  -o wide
NAME                             READY   STATUS    RESTARTS   AGE   IP             NODE          NOMINATED NODE   READINESS GATES
ingress-nginx-controller-jn65t   1/1     Running   0          62m   10.10.10.177   k8s-node-01   <none>           <none>

3.6.4 测试使用域名访问

[root@k8s-master ~]# echo "10.10.10.177 k8s.test.cn " >> /etc/hosts
[root@k8s-master ~]# curl k8s.test.cn
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

3.6.5 查询访问日志

[root@k8s-master ~]# kubectl logs  -f -n ingress-nginx   ingress-nginx-controller-jn65t
-------------------------------------------------------------------------------
NGINX Ingress controller
  Release:       v1.9.6
  Build:         6a73aa3b05040a97ef8213675a16142a9c95952a
  Repository:    https://github.com/kubernetes/ingress-nginx
  nginx version: nginx/1.21.6

-------------------------------------------------------------------------------

W0225 11:43:12.164749       7 client_config.go:618] Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.
I0225 11:43:12.165295       7 main.go:205] "Creating API client" host="https://10.1.0.1:443"
I0225 11:43:12.177840       7 main.go:249] "Running in Kubernetes cluster" major="1" minor="25" git="v1.25.0" state="clean" commit="a866cbe2e5bbaa01cfd5e969aa3e033f3282a8a2" platform="linux/amd64"
I0225 11:43:12.436449       7 main.go:101] "SSL fake certificate created" file="/etc/ingress-controller/ssl/default-fake-certificate.pem"
I0225 11:43:12.565821       7 nginx.go:260] "Starting NGINX Ingress controller"
I0225 11:43:12.627098       7 event.go:298] Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx", Name:"ingress-nginx-controller", UID:"ffe00f65-b957-4108-ac62-9f88e3b3887f", APIVersion:"v1", ResourceVersion:"482046", FieldPath:""}): type: 'Normal' reason: 'CREATE' ConfigMap ingress-nginx/ingress-nginx-controller
I0225 11:43:13.773928       7 nginx.go:303] "Starting NGINX process"
I0225 11:43:13.774090       7 leaderelection.go:245] attempting to acquire leader lease ingress-nginx/ingress-nginx-leader...
I0225 11:43:13.777086       7 controller.go:190] "Configuration changes detected, backend reload required"
I0225 11:43:13.793435       7 leaderelection.go:255] successfully acquired lease ingress-nginx/ingress-nginx-leader
I0225 11:43:13.795060       7 status.go:84] "New leader elected" identity="ingress-nginx-controller-jn65t"
I0225 11:43:14.211765       7 controller.go:210] "Backend successfully reloaded"
I0225 11:43:14.211878       7 controller.go:221] "Initial sync, sleeping for 1 second"
I0225 11:43:14.211918       7 event.go:298] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx", Name:"ingress-nginx-controller-jn65t", UID:"aa348af4-9773-4ca2-b2fc-45eb2c842c83", APIVersion:"v1", ResourceVersion:"482645", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration
I0225 12:43:04.755446       7 store.go:440] "Found valid IngressClass" ingress="default/ingress-nginx-example" ingressclass="nginx"
I0225 12:43:04.756941       7 event.go:298] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default", Name:"ingress-nginx-example", UID:"cf861f68-6f06-4279-acda-9884e7fd3557", APIVersion:"networking.k8s.io/v1", ResourceVersion:"488205", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync
I0225 12:43:04.757794       7 controller.go:190] "Configuration changes detected, backend reload required"
I0225 12:43:04.989965       7 controller.go:210] "Backend successfully reloaded"
I0225 12:43:04.990671       7 event.go:298] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx", Name:"ingress-nginx-controller-jn65t", UID:"aa348af4-9773-4ca2-b2fc-45eb2c842c83", APIVersion:"v1", ResourceVersion:"482645", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration
I0225 12:43:13.804201       7 status.go:304] "updating Ingress status" namespace="default" ingress="ingress-nginx-example" currentValue=null newValue=[{"ip":"10.1.119.138"}]
I0225 12:43:13.813972       7 event.go:298] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default", Name:"ingress-nginx-example", UID:"cf861f68-6f06-4279-acda-9884e7fd3557", APIVersion:"networking.k8s.io/v1", ResourceVersion:"488223", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync
10.10.10.100 - - [25/Feb/2024:12:46:25 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" 75 0.008 [default-nginx-svc-80] [] 10.2.1.55:80 612 0.008 200 e2b058939e017bdfa86c953e312ea057

3.6.6 ingress配置多域名

配置多域名和单域名很相通,如下一个例子

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-nginx-example
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
  # 配置第一个域名
  - host: k8s.test.cn
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx-svc
            port:
              number: 80
  # 配置第二个域名            
  - host: k8s.test.com
    http:
      paths:
      # 配置第一个路径
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx-svc
            port:
              number: 80
      # 配置第二个路径       
      - path: /html
        pathType: Prefix
        backend:
          service:
            name: nginx-svc
            port:
              number: 80

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/409264.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

贪心算法---前端问题

1、贪心算法—只关注于当前阶段的局部最优解,希望通过一系列的局部最优解来推出全局最优----但是有的时候每个阶段的局部最优之和并不是全局最优 例如假设你需要找给客户 n 元钱的零钱&#xff0c;而你手上只有若干种面额的硬币&#xff0c;如 1 元、5 元、10 元、50 元和 100…

【变压器故障诊断分类及预测】基于GRNN神经网络

课题名称&#xff1a;基于GRNN神经网络的变压器故障诊断分类及预测 版本日期&#xff1a;2024-02-10 运行方式&#xff1a;直接运行GRNN0507.m文件 代码获取方式&#xff1a;私信博主或QQ&#xff1a;491052175 模型描述&#xff1a; 对变压器油中溶解气体进行分析是变压器…

JavaAPI常用类01

目录 概述 Object类 Object类_toString() 代码展示 重写toString()方法前后输出 Object类_equals() 代码展示 重写equals()方法前后输出对比 Arrays类 equals()方法 Binary Search&#xff08;二分查找&#xff09; copyOf()方法 sort()方法 了解sort()方法 进阶…

在使用nginx的时候快速测试配置文件,并重新启动

小技巧 Nginx修改配置文件后需要重新启动&#xff0c;常规操作是启动在任务管理器中关闭程序然后再次双击nginx.exe启动&#xff0c;但是使用命令行就可以快速的完成操作。 将cmd路径切换到nginx的安装路径 修改完成配置文件后 使用 nginx -t校验nginx 的配置文件是否出错 …

Python入门必学:reverse()和reversed()的区别

Python入门必学&#xff1a;reverse()和reversed()的区别 &#x1f4c5;2024年02月25日 &#x1f308; 个人主页&#xff1a;高斯小哥 &#x1f525; 高质量专栏&#xff1a;Matplotlib之旅&#xff1a;零基础精通数据可视化、Python基础【高质量合集】、PyTorch零基础入门教程…

Cover和contain属性

一.背景的盒子 代码&#xff1a; <body><div class"box"></div><style>.box {width: 500px;height: 500px;border: 1px solid #ccc;background: url(./20191017095131790.png) no-repeat;}</style></body> 盒子的宽度和高度是…

SpringBootRest服务调用

目录 RestTemplate 依赖配置 自定义RestTemplate webCilent 依赖配置 自定义webCilent springboot中有两种方式实现Rest远程服务调用&#xff0c;分别是RestTemplate与webCilent。下面分别介绍一下这两种方式。 RestTemplate 依赖配置 RestTemplate是Spring Framework提供的…

不会做UI自动化测试?一起设计框架再实践吧

目的 相信做过测试的同学都听说过自动化测试&#xff0c;而UI自动化无论何时对测试来说都是比较吸引人的存在。 相较于接口自动化来说它可以最大程度的模拟真实用户的日常操作与特定业务场景的模拟&#xff0c;那么存在即合理&#xff0c;自动化UI测试自然也是广大测试同学职…

2.23日学习打卡----初学Nginx(二)

2.23日学习打卡 目录: 2.23日学习打卡一. Nginx 虚拟主机虚拟主机的分类Nginx支持三种类型的虚拟主机配置Nginx虚拟主机单网卡多IP配置Nginx虚拟主机_基于域名虚拟主机配置Nginx虚拟主机基于多端口的配置4 二. Nginx 核心指令root和alias指令的区别return指令rewrite指令rewrit…

Vue | (六)使用Vue脚手架(下)| 尚硅谷Vue2.0+Vue3.0全套教程

文章目录 &#x1f4da;Vue 中的自定义事件&#x1f407;使用方法&#x1f407;案例练习&#x1f407;TodoList案例优化 &#x1f4da;全局事件总线&#x1f407;使用方法&#x1f407;案例练习&#x1f407;TodoList案例优化 &#x1f4da;消息订阅与发布&#x1f407;使用方法…

RCE (Remote ????? execution) --->CTF

看这个标题就知道今天的内容不简单&#xff01;&#xff01;&#xff01;&#xff01; 那么就来讲一下我们的RCE吧 目录 ​编辑 1. &&#xff1f; |&#xff1f; ||&#xff1f; &&&#xff1f; 2.PHP命令执行函数&& ||"" 1."" &…

USB Micro引脚及相应原理图绘制

前言&#xff1a;博主为实现绘制USB Micro输入口原理图&#xff0c;首先在 GD32F103XX的数据手册中找到引脚的功能描述&#xff0c;找到USBDM与USBDP功能&#xff0c;分别为引脚PA11与引脚PA12。然后进行相应的原理图绘制。 * USBDM。USBDM 引脚是与通用串行总线 (Universal Se…

java数据结构与算法刷题-----LeetCode106. 从中序与后序遍历序列构造二叉树

java数据结构与算法刷题目录&#xff08;剑指Offer、LeetCode、ACM&#xff09;-----主目录-----持续更新(进不去说明我没写完)&#xff1a;https://blog.csdn.net/grd_java/article/details/123063846 1. 法一&#xff1a;递归 解题思路&#xff1a;时间复杂度O(n),空间复杂度…

人工智能 — 相机模型和镜头畸变

目录 一、相机模型1、相机与图像2、坐标系1、世界坐标系2、相机坐标系3、图像物理坐标系4、图像像素坐标系 3、相机成像4、世界坐标系到摄像机坐标系5、欧氏变换6、齐次坐标7、摄像机坐标系到图像物理坐标系8、图像物理坐标系到图像像素坐标系9、摄像机坐标系到图像像素坐标系1…

图解目标检测 之 【YOLOv9】 算法 最全原理详解

YOLOv9与SOTA模型对比 什么是 YOLOv9&#xff1f;YOLOv9是YOLO系列中的最新产品&#xff0c;是一种实时目标检测模型。它通过先进的深度学习技术和架构设计&#xff0c;包括通用 ELAN (GELAN) 和可编程梯度信息 (PGI)&#xff0c;展现出更好的性能。 YOLO 系列通过引入计算机视…

C++入门学习(三十七)函数分文件编写【DEV】

创建.h后级名的头文件创建.cpp后缀名的源文件在头文件中写函数的声明在源文件中写函数的定义 一、选择文件、新建、项目 二、 选择Empty Project 三、 新建源文件New File 四、贴代码 test.cpp #include <iostream> #include "add.h" using namespace std;i…

在Sora引爆视频生成时,Meta开始用Agent自动剪视频了

未来&#xff0c;视频剪辑可能也会像视频生成领域一样迎来 AI 自动化操作的大爆发。 这几天&#xff0c;AI 视频领域异常地热闹&#xff0c;其中 OpenAI 推出的视频生成大模型 Sora 更是火出了圈。而在视频剪辑领域&#xff0c;AI 尤其是大模型赋能的 Agent 也开始大显身手。 …

PMP项目管理考试要注意些什么?

PMP考试和PMP备考过程中应该注意哪些问题&#xff1f; PMP备考完成后就要迎接实战考试了&#xff0c;考试前千万不要有多余的想法&#xff0c;顺其自然就行了&#xff0c;我想大家各种紧张、各种忧虑的原因大抵是因为考试成本考&#xff0c;担心考不过&#xff0c;其实只要你在…

Java后端服务接口性能优化常用技巧

接口性能优化常用技巧 前言1.数据库索引2.慢SQL优化3.异步执行4.批量处理5.数据预加载6.池化技术&#xff08;多线程&#xff09;8.事件回调机制9.串行改为并行调用10.深度分页问题 前言 对于高标准程序员来说提供高性能的服务接口是我们所追求的目标&#xff0c;以下梳理了一…

Linux安装Zookeeper

目录 下载配置启动 下载 下载链接 https://archive.apache.org/dist/zookeeper/上传 我直接本地下好了&#xff0c;拖到对应文件夹解压&#xff0c;重命名&#xff0c;注意路径 tar -zxvf /opt/Zookeeper/apache-zookeeper-3.7.2-bin.tar.gz -C /opt/ mv /opt/apache-zookeep…