Contour 是一个基于 Envoy 的服务网格入口网关,它为Kubernetes提供了一种易于部署和管理的服务发现解决方案。本文将深入探讨如何在 Kubernetes 中使用 Contour 来进行网络配置,帮助读者掌握从基础到高级的网络配置方法。
Contour 是通过 Helm 图表来部署的,在正式开始配置之前,需要确保已经安装了 Kustomize 和 Helm。Kustomize 是一个用于修改和扩展 Kubernetes 配置文件的强大工具。
# 安装 Kustomize
curl -s https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install-kustomize.sh | bash
# 添加 Helm 仓库(如果尚未添加)
helm repo add contour https://contour.projectcontour.io/charts
# 创建 Contour 所需的命名空间
kubectl create namespace contour
# 部署 Contour 图表
helm install contour --namespace contour -f values.yaml contour/contour
其中 values.yaml
文件中可以配置多种参数,具体设置根据实际需求调整。
ServiceMeshConfiguration 是 Contour 中的高级配置对象。该文件定义了如何路由服务之间的流量、启用的插件以及其它相关的网络规则等。
apiVersion: projectcontour.io/v1
kind: ServiceMeshConfiguration
metadata:
name: contour
spec:
services:
- name: example-service
hosts:
- "example.local"
routes:
- match: |
prefix "/"
destination:
kind: Service
name: example-backend
port:
number: 80
Gateway 资源定义了如何配置服务的入口点。在 Kubernetes 中,可以通过创建 Gateway 和 HTTPRoute 对象来管理外部流量。
apiVersion: projectcontour.io/v1
kind: Gateway
metadata:
name: example-gateway
spec:
selector:
matchLabels:
app: example
listeners:
- port:
number: 80
protocol: HTTP
- port:
number: 443
protocol: HTTPS
##
apiVersion: projectcontour.io/v1
kind: HTTPRoute
metadata:
name: example-httproute
spec:
hostnames:
- "example.local"
routes:
- matchers:
- prefix "/"
actions:
- match:
method: GET
destination:
kind: Service
name: example-backend
port:
number: 80
使用 Contour 的另一个优点是可以轻松配置自定义的 DNS 解析。通过将 projectcontour.io
标签添加到 Pod 或服务上,可以使其出现在 Envoy 上所维护的 DNS 缓存中。
apiVersion: v1
kind: Service
metadata:
name: example-service
labels:
projectcontour.io/dns-namespace: local
spec:
selector:
app: example
ports:
- protocol: TCP
port: 80
targetPort: 80
在 HTTPRoute 中启用 TLS 终止,可确保外部流量经过加密处理。
apiVersion: projectcontour.io/v1
kind: HTTPRoute
metadata:
name: example-httproute-ssl
spec:
tlsSecretRef: my-tls-secret
hostnames:
- "example.local"
routes:
- matchers:
- prefix "/"
actions:
- match:
method: GET
destination:
kind: Service
name: example-backend
port:
number: 80
为了实现更高级别的安全性,可以配置客户端和服务器之间的相互认证。
apiVersion: projectcontour.io/v1
kind: Gateway
metadata:
name: example-gateway-mtls
spec:
tlsSecretRef: my-tls-secret
selector:
matchLabels:
app: example
listeners:
- port:
number: 443
protocol: HTTPS
通过上述步骤,读者可以基本了解如何在 Kubernetes 中使用 Contour 进行网络配置。从简单的路由规则到高级的 SSL/TLS 配置,Contour 提供了灵活且强大的工具来满足不同场景的需求。
随着 Kubernetes 生态系统的不断发展,像 Contour 一样专为服务网格设计的应用也将越来越多地被采用和探索。希望本文对读者有所帮助!