Ingress 与 DNS
约 497 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › K8s › 网络与服务(在新窗口打开) › Ingress 与 DNS
Ingress vs Service
| 对比 | Service | Ingress |
|---|---|---|
| 层级 | L4(TCP/UDP) | L7(HTTP/HTTPS) |
| 路由规则 | 简单负载均衡 | 域名/路径路由 |
| TLS | 手动 | 内置 TLS 终结 |
| 适用场景 | 内部服务暴露 | 外部 HTTP 流量入口 |
Ingress 示例
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: app.example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service:
name: api-service
port:
number: 80
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80# 需要先部署 Ingress Controller(如 Nginx Ingress)
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml
# 创建 Ingress
kubectl apply -f ingress.yaml
# 查看
kubectl get ingress
# NAME CLASS HOSTS ADDRESS PORTS AGE
# myapp-ingress nginx app.example.com 192.168.49.2 80 5mTLS 配置
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: tls-ingress
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: myapp-tls # TLS 证书的 Secret
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80# 创建 TLS Secret
kubectl create secret tls myapp-tls \
--cert=example.crt \
--key=example.key路径类型
| pathType | 说明 | 示例 |
|---|---|---|
Prefix | 前缀匹配 | /api 匹配 /api/users、/api/v1 |
Exact | 精确匹配 | /api 仅匹配 /api |
ImplementationSpecific | 由 Controller 决定 | Nginx Ingress 支持正则 |
集群 DNS(CoreDNS)
K8s 集群内部通过 CoreDNS 提供 DNS 解析服务。
# 查看 CoreDNS Pod
kubectl get pods -n kube-system -l k8s-app=kube-dns
# Pod 内 DNS 配置
kubectl exec my-pod -- cat /etc/resolv.conf
# nameserver 10.96.0.10 # CoreDNS ClusterIP
# search default.svc.cluster.local svc.cluster.local cluster.local
# ndots: 5DNS 解析规则
# 完整格式
<service>.<namespace>.svc.cluster.local
# 同 Namespace 可简写
<service>
# 跨 Namespace
<service>.<namespace>常用 Ingress Annotation
metadata:
annotations:
# 限制请求体大小
nginx.ingress.kubernetes.io/proxy-body-size: "10m"
# CORS
nginx.ingress.kubernetes.io/enable-cors: "true"
# 重写路径
nginx.ingress.kubernetes.io/rewrite-target: /$2
# 速率限制
nginx.ingress.kubernetes.io/limit-rps: "10"
# SSL 重定向
nginx.ingress.kubernetes.io/ssl-redirect: "true"小结
- Ingress 是集群外部 HTTP/HTTPS 流量的入口,提供域名/路径路由和 TLS 终结。
- 需要先部署 Ingress Controller(如 Nginx Ingress、Traefik)才能使用。
pathType支持Prefix(前缀)、Exact(精确)、ImplementationSpecific。- CoreDNS 提供集群内部 DNS 解析,格式
<svc>.<ns>.svc.cluster.local。 - Annotation 提供 Ingress Controller 的额外配置(限流、CORS、路径重写)。
上一节:Service 基础 下一节:NetworkPolicy
