「Kubernetes」- 在 Ingress 中,使用 cert-manager 证书

  CREATED BY JENKINSBOT

问题描述

当我们在 Kubernetes Cluster 中部署 cert-manager 之后,便能够在 Ingress 中使用 cert-manager 提供 TLS 证书。

该笔记将记录:在 Kubernetes Cluster 中,如何配置 Ingress 使用 cert-manager 来提供 TLS 证书。

解决方案

第一步、部署 Web 应用

首先,我们需要部署简单的 Web 应用(参考 Example 笔记),来作为实验环境。

后面的操作将基于该 Web 应用,这里不再深入展开 Web 应用的部署。

第二步、修改 Ingress 资源

我们需要做的便是修改 Ingress 资源:

cp -v myweb-ingress.yaml myweb-ingress.yaml.backup

cat > myweb-ingress.yaml <<EOF
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: myweb-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    # 修改此处,添加 Issuer 或 ClusterIssuer 定义
    cert-manager.io/cluster-issuer: "letsencrypt" # 根据自己的 ClusterIssuser 定义来填写
spec:
  # 添加 TLS 配置
  tls:
  - hosts:
    - k8s-ingress.example.xyz
    # cert-manager 将使用该字符串作为 Secret 名称
    secretName: myk8singress-cert
  rules:
  - host: "k8s-ingress.example.xyz"
    http:
      paths:
      - path: /
        backend:
          serviceName: myweb
          servicePort: 8080
EOF

kubectl apply -f ./myweb-ingress.yaml

第三步、检查 TLS 证书的签发

检查 TLS 证书是否自动申请(即创建 CertificaterRequests 资源,并成功签发):

# kubectl get certificaterequests.cert-manager.io myk8singress-cert-whtzp
NAME                      APPROVED   DENIED   READY   ISSUER        REQUESTOR                                         AGE
myk8singress-cert-whtzp   True                True    letsencrypt   system:serviceaccount:cert-manager:cert-manager   84s

# kubectl describe certificates.cert-manager.io myk8singress-cert
...
  Not After:               2021-08-05T10:46:37Z
  Not Before:              2021-05-07T10:46:37Z
  Renewal Time:            2021-07-06T10:46:37Z
  Revision:                1
Events:
  Type    Reason     Age    From          Message
  ----    ------     ----   ----          -------
  Normal  Issuing    4m1s   cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  4m1s   cert-manager  Stored new private key in temporary Secret resource "myk8singress-cert-p25hl"
  Normal  Requested  4m1s   cert-manager  Created new CertificateRequest resource "myk8singress-cert-whtzp"
  Normal  Issuing    2m42s  cert-manager  The certificate has been successfully issued

第四步、访问站点,验证 HTTPS 生效

# curl https://k8s-ingress.example.xyz

参考文献

Securing Ingress Resources | cert-manager