k8s-存储-secret
一 secret三种类型
-
Service Account :用来访问 Kubernetes API,由 Kubernetes 自动创建,并且会自动挂载到 Pod 的/run/secrets/kubernetes.io/serviceaccount 目录中
-
Opaque :base64编码格式的Secret,用来存储密码、密钥等
-
kubernetes.io/dockerconfigjson :用来存储私有 docker registry 的认证信息
1 Service Account
Service Account 用来访问 Kubernetes API,由 Kubernetes 自动创建,并且会自动挂载到 Pod的/run/secrets/kubernetes.io/serviceaccount 目录中
kubectl run nginx --image nginx
deployment "nginx" created
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-3137573019-md1u2 1/1 Running 0 13s
$ kubectl exec nginx-3137573019-md1u2 ls /run/secrets/kubernetes.io/serviceaccount
ca.crt
namespace
token
2 Opaque Secret
2.1 创建并引用
Opaque 类型的数据是一个 map 类型,要求 value 是 base64 编码格式
$ echo -n "admin" | base64
YWRtaW4=
$ echo -n "1f2d1e2e67df" | base64
MWYyZDFlMmU2N2Rm
-
创建secret
[root@k8s-master01 secret]# cat secrets.yaml
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: MWYyZDFlMmU2N2Rm
username: YWRtaW4=
pod引用
[root@k8s-master01 secret]# cat pod1.yaml
apiVersion: v1
kind: Pod
metadata:
labels:
name: seret-test #标签名字
name: seret-test #pod名字
spec:
volumes:
- name: secrets
secret:
secretName: mysecret
containers:
- image: wangyanglinux/myapp:v1
name: db1
volumeMounts:
- name: secrets
mountPath: "/etc/secret"
readOnly: true
-
验证
[root@k8s-master01 secret]# kubectl exec seret-test -it /bin/sh
/ # cd /etc/secret/
/etc/secret # ls
password username
/etc/secret # cat password
/etc/secret # cat username
admin/etc/secret #
2.2 挂载引用secret
[root@k8s-master01 secret]# cat env.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: pod-deployment
spec:
replicas: 2
template:
metadata:
labels:
app: pod-deployment
spec:
containers:
- name: pod-1
image: wangyanglinux/myapp:v1
ports:
- containerPort: 80
env:
- name: TEST_USER
valueFrom:
secretKeyRef:
name: mysecret
key: username
- name: TEST_PASSWORD
valueFrom:
secretKeyRef:
name: mysecret
key: password
-
验证
3 拉取镜像时使用(kubernetes.io/dockerconfigjson)
当pod里面拉取镜像的时候,要创建一个secret,才可以拉取,否则会拉取失败
首先 自己注册的dockerhub ,在linux上面登录
docker login -u huningfei -p password
docker logout #退出
3.1 创建连接docker的用户名和密码
私有仓库的时候用这个--docker-server=hub.docker.com 需要加上地址
kubectl create secret docker-registry myregistrykey --docker-server=hub.docker.com --docker-username=huningfei --docker-password=password --docker-email=huningfei@126.com
公有仓库的时候用这个,不用加地址
kubectl create secret docker-registry registry-pull-secret --docker-username=huningfei --docker-password=password --docker-email=huningfei@126.com
查看创建的密钥名称
演示pod如何拉取私有仓库镜像
apiVersion: v1
kind: Pod
metadata:
name: foo
spec:
containers:
- name: foo
image: huningfei/demo-test:31
imagePullSecrets:
- name: registry-pull-secret #要和上面的名字一致