要将信任证书添加到 Kubernetes 集群中,可以按照以下步骤进行操作:
- 创建一个 Secret 对象,用于存储 CA 证书。
kubectl create secret generic ca-cert --from-file=<path-to-ca-cert>
其中,<path-to-ca-cert>
是指向 CA 证书的路径和文件名。这里创建了一个名为 ca-cert
的 Secret 对象,并将 CA 证书保存在其中。
- 在需要使用该 CA 证书的 Pod 或 Service 中,添加 Volume 和 VolumeMount 配置。
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: my-image
volumeMounts:
- name: ca-certs
mountPath: /etc/ssl/certs/my-ca.crt
readOnly: true
volumes:
- name: ca-certs
secret:
secretName: ca-cert
在上面的示例中,创建了一个名为 ca-certs
的 Volume,并将其挂载到 /etc/ssl/certs/my-ca.crt
目录下。然后,在容器配置中通过 volumeMounts
属性将该 Volume 挂载到容器内部。最后,在 Volume 中引用了之前创建的 Secret 对象(名称为 ca-cert
),并将其类型设置为 secret
。
- 在容器内部使用该 CA 证书来进行 TLS 连接等操作。例如,在 Node.js 应用程序中可以使用以下代码加载该 CA 证书:
const fs = require('fs');
const https = require('https');
const options = {
ca: fs.readFileSync('/etc/ssl/certs/my-ca.crt'),
};
https.get('https://example.com', options, (res) => {
// handle response
});
在上面的示例中,通过 fs
模块加载了之前挂载到容器内部的 CA 证书,并将其传递给 https.get()
方法中的 options
参数。