实现目标
通过Ingress资源实现通过域名与URI从Kubernetes集群外向集群内服务进行访问
实现思路
1. 从Kubernetes集群外向集群访问,访问时使用域名(通过DNS解析)
2.Kubernetes处理请求,请求从Ingress-Controller进入,通过Ingress路由规则将流量向指定Service进行转发
3.流量经由Service资源转向选择的具体Pod服务
实现过程
1. 准备Ingress资源
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: traefik-ingress spec: ingressClassName: traefik rules: - host: ingress.crossanda.com http: paths: - path: /who pathType: Prefix backend: service: name: whoami-svc port: number: 80
2. 准备IngressClass
apiVersion: networking.k8s.io/v1 kind: IngressClass metadata: name: traefik annotations: ingressclass.kubernetes.io/is-default-class: "true" spec: controller: traefik.io/ingress-controller
3. 准备IngressController
3.1 IngressController 实例
kind: Deployment apiVersion: apps/v1 metadata: name: traefik-deployment labels: app: traefik spec: replicas: 1 selector: matchLabels: app: traefik template: metadata: labels: app: traefik spec: serviceAccountName: traefik-account containers: - name: traefik image: traefik:v3.0 args: - --api.insecure - --providers.kubernetesingress ports: - name: web containerPort: 80 - name: dashboard containerPort: 8080
3.2 集群内端口暴露
apiVersion: v1 kind: Service metadata: name: traefik-dashboard-service spec: type: NodePort ports: - port: 8080 targetPort: dashboard selector: app: traefik --- apiVersion: v1 kind: Service metadata: name: traefik-web-service spec: type: NodePort ports: - targetPort: web port: 80 selector: app: traefik
4. 配置连接关系
4.1 集群角色
kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: traefik-role rules: - apiGroups: - "" resources: - services - endpoints - secrets verbs: - get - list - watch - apiGroups: - extensions - networking.k8s.io resources: - ingresses - ingressclasses verbs: - get - list - watch - apiGroups: - extensions - networking.k8s.io resources: - ingresses/status verbs: - update
4.2 服务账号
apiVersion: v1 kind: ServiceAccount metadata: name: traefik-account
4.3 集群角色绑定
kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: traefik-role-binding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: traefik-role subjects: - kind: ServiceAccount name: traefik-account namespace: default
4.4 应用实例
apiVersion: apps/v1 kind: Deployment metadata: name: whoami labels: app: whoami spec: replicas: 3 template: metadata: name: whoami labels: app: whoami spec: containers: - name: whoami image: traefik/whoami imagePullPolicy: IfNotPresent restartPolicy: Always selector: matchLabels: app: whoami
4.5 应用服务
apiVersion: v1 kind: Service metadata: name: whoami-svc spec: selector: app: whoami ports: - port: 80 type: ClusterIP
4.6 DNS配置
此处以hosts为例