无Ingress场景下在Kubernetes中配置Cert Manager的方法咨询
解决方案
不用Ingress的情况下,你可以通过将Cert Manager生成的证书Secret挂载到Spring Cloud Gateway Pod中,替换原有的自签名证书配置,具体分两种实现方式:
方式一:直接使用PEM格式证书(推荐,无需转换)
Cert Manager生成的自签名证书Secret默认包含tls.crt(证书链)和tls.key(私钥)两个PEM格式文件,Spring Cloud Gateway支持直接配置PEM证书,无需JKS密钥库:
修改Deployment挂载Secret
在你的SpringBoot应用Deployment的spec.template.spec中添加Volume和VolumeMount:volumes: - name: gateway-tls-secret secret: secretName: <你的Cert Manager证书Secret名称> # 替换为实际Secret名 containers: - name: <你的应用容器名> volumeMounts: - name: gateway-tls-secret mountPath: /etc/gateway-tls readOnly: true更新application.yml的TLS配置
替换原有的JKS密钥库配置为PEM格式:spring: cloud: gateway: httpserver: ssl: enabled: true key-store-type: PEM key-cert-chain: /etc/gateway-tls/tls.crt key-store: /etc/gateway-tls/tls.key key-password: "" # 若私钥未加密则留空 httpclient: ssl: trustedX509Certificates: - /etc/gateway-tls/tls.crt # 可选:若需要信任自身证书滚动更新Pod
执行命令让Deployment加载新配置:kubectl rollout restart deployment/<你的Deployment名称>
方式二:将PEM证书转换为JKS密钥库(兼容原有配置)
如果想保留原有的JKS密钥库配置,可以用Init容器在Pod启动前将PEM证书转换为JKS格式:
修改Deployment添加Init容器和挂载
spec: template: spec: initContainers: - name: tls-to-jks image: openjdk:17-jdk-slim # 用和应用一致的JDK版本 command: - sh - -c - | # 将PEM私钥转换为PKCS8格式(keytool要求) openssl pkcs8 -topk8 -nocrypt -in /tmp/tls/tls.key -out /tmp/tls/pkcs8.key # 生成JKS密钥库,替换<你的密钥库密码>为原配置的密码 keytool -importkeystore -srckeystore /tmp/tls/pkcs8.key -srcstoretype PKCS8 -srcstorepass "" \ -destkeystore /tmp/jks/keystore.jks -deststoretype JKS -deststorepass <你的密钥库密码> -noprompt # 可选:生成信任库 keytool -importcert -file /tmp/tls/tls.crt -keystore /tmp/jks/truststore.jks -storepass <你的信任库密码> -noprompt volumeMounts: - name: gateway-tls-secret mountPath: /tmp/tls - name: jks-volume mountPath: /tmp/jks volumes: - name: gateway-tls-secret secret: secretName: <你的Cert Manager证书Secret名称> - name: jks-volume emptyDir: {} containers: - name: <你的应用容器名> volumeMounts: - name: jks-volume mountPath: /etc/gateway-jks readOnly: true更新application.yml路径
仅修改密钥库和信任库的路径:spring: cloud: gateway: httpserver: ssl: enabled: true key-store: /etc/gateway-jks/keystore.jks key-store-password: <你的密钥库密码> httpclient: ssl: trust-store: /etc/gateway-jks/truststore.jks trust-store-password: <你的信任库密码>滚动更新Pod
执行命令重启Deployment:kubectl rollout restart deployment/<你的Deployment名称>
证书自动更新处理
当Cert Manager自动续签证书时,Secret会更新,但Pod不会自动加载新证书。可以通过以下方式实现自动滚动更新:
- 安装Stakater Reloader工具,给Deployment添加注解:
当Secret更新时,Reloader会自动触发Deployment滚动更新。metadata: annotations: secret.reloader.stakater.com/reload: "<你的Cert Manager证书Secret名称>"
内容的提问来源于stack exchange,提问作者manjosh
相关产品推荐
相关产品推荐

