资源管理的两种方式
1、secret
保存密码、token、敏感的k8s资源,这类数据可以直接存放在镜像中,但放在Secret中便于控制,以及减少暴露的风险
保存加密的信息
2、Configmap* 【面试必问】
保存不需要加密的信息
一、 secret
1、secret类型
查看secret

创建secret


|-------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------|
| docker-registry | 存储docker仓库的认证信息,以及docker组件的认证信息(私有) |
| generic | secret的默认模式,opaque方式,存储用户自定义的密码、密钥等 |
| tls | 存储证书和私钥,用于https |
| kubernetes.io/service-account-token | 系统默认自带,用于访问自动的APIserver。pod会默认使用kubernetes.io/service-account-token创建的secret和apiserver进行通信,自动挂载到pod的/run/secretkubernetes.io/serviceaccount |
2、创建secret
(1)指定文件 创建secret(陈述式)
cat password.txt
1054 kubectl create secret generic mysecret --from-file=/opt/username.txt --from-file=/opt/password.txt


Opaque加密类型
(2) 以 Opaque bash64加密格式 创建secret(声明式)





data里保存的是加密信息
3 、 pod使用secret的三种方式
(1) 将secret挂载到pod中的一个或多个容器上的卷 (常用)
把加密的文件传到容器内部。保存的是加密的内容,到容器内部后是解密的内容,可以直接引用
(2) 将secret作为容器的环境变量
(3) docker-registry 可以作为集群拉取镜像时使用,使用secret可以实现免密登录
方式1: 将secret挂载到pod中的一个或多个容器上的卷
创建secret
引用secret创建pod




①声明式创建secret,引用此secret创建pod
②陈述式创建secret,引用此secret创建pod
kubectl create secret generic mysecret --from-file=/etc/passwd --from-file=/etc/shadow
声明对象secret 声明类型generic 名称mysecret
方式2:环境变量传参到容器内部
创建secret
引用此secret创建pod
环境变量名USER1,引用mysecret中的加密变量username1(羊羊羊)
方式3:通过secret加密方式直接获取镜像仓库的账号
陈述式创建secret
kubectl create secret docker-registry myharbor --docker-server=20.0.0.27 --docker-username=admin --docker-password=123456







注:从本地仓库下载镜像是秒级的
二、 configmap (以键值对形式保存) 【面试】
1、定义
保存的是不需要加密的信息,将信息传给容器内部。configmap是1.2引入的功能,应用程序会从配置文件、命令参数、环境变量中读取配置信息,configmap在创建容器时,注入我们需要的配置信息,既可以是单个属性,也可以是整个容器的配置文件
2、 configmap创建方式
(1)陈述式
(2)声明式
方式1:陈述式创建configmap
①从指定文件创建configmap,可以是一个或多个文件
kubectl create configmap myconfigmap --from-file=/opt/name.txt --from-file=/opt/password.txt
②可以使用字面值创建
kubectl create configmap myconfigmap --from-literal=name=羊羊羊 --from-literal=passeord=123456
方式2:声明式 创建configmap
3 、 使用 configmap
方式1:数据卷使用configmap 【重点】
①设置配置文件


②创建configmap
kubectl create configmap myconfigmap --from-file=/opt/nginx-configmap/nginx.conf


③创建pod
|---------------|------------|-----------------------|
| 容器外部 | 含义 | 容器内部 |
| myconfigmap的值 | 传给 | /etc/nginx |
| /opt/html | 挂载 | /usr/share/nginx/html |
④测试





所以无法访问默认页面文件/usr/share/nginx/html/index.html
⑤修改外部变量

无法访问的原因:修改配置文件要重启服务,配置文件才能生效
configmap机制:不用重启pod即可将文件传入容器

通过数据卷的形式,将配置文件传给容器内部
configmap的热更新
在pod运行的情况下,对configmap的配置信息进行修改,直接生效(反应到容器当中),configmap的热更新不会触发pod的滚动更新机制(基于deployment创建的pod),通过设置version/config来触发滚动更新机制
⑥触发滚动更新机制
kubectl patch deployments.apps nginx --patch '{"spec": {"template": {"metadata": {"annotations": {"version/config": "20240116"}}}}}'

方式2:环境变量
kubectl create configmap myconfigmap --from-literal=name1=yang --from-literal=name2=shu
