模拟环境举例:
# 生成带 OU 的证书配置文件
cat > csr.conf <<EOF
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn[ dn ]
C = CN
ST = Beijing
L = Beijing
O = YourCompany, Inc. # 组织名称 (必填)
OU = DevOps Department # 组织单位 (新增)
CN = yourdomain.com # 域名
EOF# 生成证书
openssl req -x509 -nodes -days 365 \-newkey rsa:2048 \-keyout tls.key \-out tls.crt \-config csr.conf# 创建 Kubernetes Secret
kubectl create secret tls tls-secret \--cert=tls.crt \--key=tls.key
ingress yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:name: ssl-ingressannotations:# 强制HTTP重定向到HTTPS (Nginx Controller)nginx.ingress.kubernetes.io/force-ssl-redirect: "true"# 通用HTTPS重定向注解 (适用于大多数Controller)ingress.kubernetes.io/ssl-redirect: "true"# 如需同时支持HTTP/HTTPS而不重定向,请注释掉以上两行# 并添加: nginx.ingress.kubernetes.io/ssl-redirect: "false"
spec:tls: # TLS配置部分- hosts:- yourdomain.com # 您的域名- api.yourdomain.com # 其他子域名secretName: tls-secret # 证书Secret名称rules:- host: yourdomain.comhttp:paths:- path: /pathType: Prefixbackend:service:name: main-serviceport: number: 80# 其他路由规则...- host: api.yourdomain.comhttp:paths:- path: /pathType: Prefixbackend:service:name: api-serviceport: number: 8080
# 检查Ingress状态
kubectl get ingress ssl-ingress# 查看TLS配置详情
kubectl describe ingress ssl-ingress# 测试访问
curl -I http://yourdomain.com # 应返回301重定向
curl -k https://yourdomain.com # 跳过证书验证
curl --resolve yourdomain.com:443:<ingress-ip> https://yourdomain.com
# 强制HTTPS
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
# 会话保持(基于Cookie)
nginx.ingress.kubernetes.io/affinity: "cookie"