BHOL405 - k8s应用开发部署 - 使用Secrets保存和使用密钥信息

在这几节实验中,我们将完成我们的 Hello Boathouse 应用的k8s部署过程,其中会涉及到一下k8s中的对象

  • Pod
  • Deployment
  • Service
    • Secret
  • Namespace

这些内容基本上覆盖了我们k8s集群进行应用开发部署的主要对象。

01 - 实验准备

使用以下命令清理之前的部署:

  1. kubectl delete -f kube-deploy/hello-boathouse-lb-service.yaml
  2. kubectl delete -f kube-deploy/hello-boathouse-nodeport-service.yaml
  3. kubectl delete -f kube-deploy/hello-boathouse-deployment.yaml

02 - 使用 Secrets 保存密钥信息

使用 secrets 我们可以将密钥信息保存在k8s集群中,并给到不同的pod使用。

使用 vscode 创建两个文件:

  • hello-boathouse-secrets.yaml
  • hello-boathouse-secrets-volumes.yaml

hello-boathouse-secrets.yaml

  1. apiVersion: v1
  2. kind: Secret
  3. metadata:
  4. name: db-secrets
  5. type: Opaque
  6. data:
  7. username: cm9vdA==
  8. password: cGFzc3dvcmQ=

hello-boathouse-secrets-volumes.yaml

  1. apiVersion: apps/v1
  2. kind: Deployment
  3. metadata:
  4. name: hello-boathouse-deployment
  5. spec:
  6. replicas: 3
  7. selector:
  8. matchLabels:
  9. app: hello-boathouse
  10. template:
  11. metadata:
  12. labels:
  13. app: hello-boathouse
  14. spec:
  15. containers:
  16. - name: hello-boathouse
  17. image: registry.cn-hangzhou.aliyuncs.com/boathouse216/hello-boathouse:v1
  18. ports:
  19. - name: nodejs-port
  20. containerPort: 3000
  21. volumeMounts:
  22. - name: cred-volume
  23. mountPath: /etc/creds
  24. readOnly: true
  25. volumes:
  26. - name: cred-volume
  27. secret:
  28. secretName: db-secrets

使用以下命令提交部署

  1. ## 提交部署
  2. kubectl apply -f kube-deploy/hello-boathouse-secrets
  3. kubectl apply -f kube-deploy/hello-boathouse-secrets-volumes.yaml
  4. ## 检查部署结果
  5. kubectl get secrets
  6. kubectl get pods

使用以下命令进入其中一个pod查看 /etc/creds 内容

  1. ## 进入其中一个pod
  2. kubectl exec {pod id} -it -- /bin/bash
  3. cd /etc/creds
  4. cat username
  5. cat password