【k8s配置与存储--配置管理】

在这里插入图片描述

1、ConfigMap的配置

1.1 ConfigMap介绍

  • ConfigMap 是一种 API 对象,用来将非机密性的数据保存到键值对中。使用时, Pod 可以将其用作环境变量、命令行参数或者存储卷中的配置文件。

  • ConfigMap 将你的环境配置信息和容器镜像解耦,便于应用配置的修改。

  • 注意:
    ConfigMap 并不提供保密或者加密功能。 如果你想存储的数据是机密的,请使用 Secret, 或者使用其他第三方工具来保证你的数据的私密性,而不是用 ConfigMap。

1.2 ConfigMap 创建

  • 使用 kubectl create configmap -h 查看演示例子
Examples:
  # Create a new config map named my-config based on folder bar
  kubectl create configmap my-config --from-file=path/to/bar

  # Create a new config map named my-config with specified keys instead of file basenames on disk
  kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt

  # Create a new config map named my-config with key1=config1 and key2=config2
  kubectl create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2

  # Create a new config map named my-config from the key=value pairs in the file
  kubectl create configmap my-config --from-file=path/to/bar

  # Create a new config map named my-config from an env file
  kubectl create configmap my-config --from-env-file=path/to/foo.env --from-env-file=path/to/bar.env

1.2.1 查看下k8s已经创建好的configmap

可以看到这个信息是存储的一个key信息

[root@k8s-master configmap]# kubectl get configmaps
NAME               DATA   AGE
kube-root-ca.crt   1      6d1h

[root@k8s-master configmap]# kubectl describe configmaps kube-root-ca.crt
Name:         kube-root-ca.crt
Namespace:    default
Labels:       <none>
Annotations:  kubernetes.io/description:
                Contains a CA bundle that can be used to verify the kube-apiserver when using internal endpoints such as the internal service IP or kubern...

Data
====
ca.crt:
----
-----BEGIN CERTIFICATE-----
MIIC/jCCAeagAwIBAgIBADANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDEwprdWJl
cm5ldGVzMB4XDTI0MDIxOTE0MDQyNloXDTM0MDIxNjE0MDQyNlowFTETMBEGA1UE
AxMKa3ViZXJuZXRlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL31
nYOmoFp9g1nfaVmuIIRJzwlCU9EGevBi/HnpSpdaW56cGuF1MqVJWhHCUcvN6sA/
9rlXOM7JS1SxN+gdO7e3WlW1e5iMTTj+63riA5tDcOv8kOPI72vgz026fK75tueW
IxD0VT1SM5fcY0H1bKvlxdr8Wxp57vxqtWX5lkJ71Xgf7Ur0L+cXwn7CiADiYAuK
nOMkc+JSYAuTeRN1eVfnjB9EvHZ3CFpSBYk2wvjqQwFwECwfoagIY9LvRzAK+P6+
NOuFXoreLgJ1kOhjGvJJ8G8vDq7483Foy90F/NqVTfy455ii4RMEZz32q5/1il0l
E4n9f2pfsaAUXMU5R+UCAwEAAaNZMFcwDgYDVR0PAQH/BAQDAgKkMA8GA1UdEwEB
/wQFMAMBAf8wHQYDVR0OBBYEFPsTxB9wcuNswaTSxefPqK83boaXMBUGA1UdEQQO
MAyCCmt1YmVybmV0ZXMwDQYJKoZIhvcNAQELBQADggEBAEnbP3FV6/jGmSdR2s9B
CsEGHDAb9rCzE8kwodx2+N4jI/upFq0QSg+rYDXWpCX/pas3Y2Dp9CGt5b854Vmy
o3wI8FzDMHzeUsaeJlo99tWG2XeJ7tQ4uc+gWp11guPHHsCF+FtAfwTbWucwjvWh
MAfFXRx+H67d0patTpWoC0f4hMNsjCHv4WDrjzLWIh0WIJT41+st4YxAwJGeXxah
4ODzXuomahvh36NFkjCPy1VHzYLi3PjQ+YwggCL2OMrwLe/EdzzA3eZVNDkcsqOi
WEjR2HGj+QWdE7nMLRUzlTtxz6AIjBfugyV3a/XSiXaCt5CRSKeLiCCCY58INtMa
JDU=
-----END CERTIFICATE-----


BinaryData
====

Events:  <none>

1.2.2 指定目录进行创建:kubectl create configmap my-config --from-file=path/to/bar

[root@k8s-master configmap]# cat db.properties
user: root
passwd: 123456
host: 127.0.0.1

[root@k8s-master configmap]# cat host.properties
k8s-master: 10.10.10.100
k8s-node-01: 10.10.10.177
k8s-node-02: 10.10.10.113

[root@k8s-master configmap]# kubectl create configmap my-config-test1 --from-file=/root/configmap/
configmap/my-config-test1 created

[root@k8s-master configmap]# kubectl describe configmaps my-config-test1
Name:         my-config-test1
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
db.properties:
----
user: root
passwd: 123456
host: 127.0.0.1

host.properties:
----
k8s-master: 10.10.10.100
k8s-node-01: 10.10.10.177
k8s-node-02: 10.10.10.113


BinaryData
====

Events:  <none>

1.2.3 指定文件进行创建:kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt

–from-file=key1=/path/to/bar/file1.txt
这里的key1相当于是给指定的这个文件进行改名

[root@k8s-master configmap]# kubectl create configmap my-config-test2  --from-file=mykey=db.properties
configmap/my-config-test2 created
[root@k8s-master configmap]# kubectl describe configmaps my-config-test2
Name:         my-config-test2
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
mykey:
----
user: root
passwd: 123456
host: 127.0.0.1


BinaryData
====

Events:  <none>

1.2.4 通过命令行创建:kubectl create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2

[root@k8s-master configmap]# kubectl create  configmap my-config-test3  --from-literal=name=school  --from-literal=id=bj
configmap/my-config-test3 created
[root@k8s-master configmap]# kubectl describe configmaps my-config-test3
Name:         my-config-test3
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
id:
----
bj
name:
----
school

BinaryData
====

Events:  <none>
[root@k8s-master configmap]#

1.3 ConfigMap的使用

创建一个configmap的资源,在创建一个pod,把这个configmap的资源加载到pod里。

1.3.1 创建configmap

root@k8s-master configmap]# kubectl create configmap env-test  --from-literal=JAVA_HOME='/usr/local/jdk1.8/'  --from-literal=Name='您好~'
configmap/env-test created
[root@k8s-master configmap]# kubectl describe configmaps env-test
Name:         env-test
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
JAVA_HOME:
----
/usr/local/jdk1.8/
Name:
----
您好~

BinaryData
====

Events:  <none>

1.3.2 创建pod资源

apiVersion: v1
kind: Pod
metadata:
  name: test-env-cm
spec:
  containers:
    - name: env-test
      image: alpine
      imagePullPolicy: IfNotPresent
      command: ["/bin/sh","-c","env  ; sleep 3600"]
      env:
      - name: JAVA_HOME_VM
        valueFrom:
          configMapKeyRef:
            name: env-test  # configmap的名字
            key: JAVA_HOME  # 表示从name的configmap种获取名字为key的value,将其赋值给本地环境变量 JAVA_HOME_VM
      - name: Name_VM
        valueFrom:
          configMapKeyRef:
            name: env-test
            key: Name
  restartPolicy: Never
[root@k8s-master configmap]# kubectl create -f env-test.yaml
pod/test-env-cm created

[root@k8s-master configmap]# kubectl get po
NAME                           READY   STATUS    RESTARTS      AGE
dns-test                       1/1     Running   1 (45h ago)   45h
fluentd-59k8k                  1/1     Running   0             27h
fluentd-hhtls                  1/1     Running   0             27h
nginx-deploy-fdd948cf4-69b85   1/1     Running   0             23h
nginx-deploy-fdd948cf4-r8ktj   1/1     Running   0             27h
test-env-cm                    1/1     Running   0             21s

1.3.3 通过日志查看刚才的configmap信息是否在env中

在这里插入图片描述

1.3.4 通过volumes 加载configmap

apiVersion: v1
kind: Pod
metadata:
  name: test-configfile-po
spec:
  containers:
    - name: env-test
      image: alpine
      imagePullPolicy: IfNotPresent
      command: ["/bin/sh","-c","env  ; sleep 3600"]
      env:
      - name: JAVA_HOME_VM
        valueFrom:
          configMapKeyRef:
            name: env-test  # configmap的名字
            key: JAVA_HOME  # 表示从name的configmap种获取名字为key的value,将其赋值给本地环境变量 JAVA_HOME_VM
      - name: Name_VM
        valueFrom:
          configMapKeyRef:
            name: env-test
            key: Name
      volumeMounts:  #  加载数据卷
      - name: db-config  # 加载数据卷的名字
        mountPath: "/opt/test/"   #将数据卷加载到什么目录
        readOnly: true  #  是否只读
  volumes: # 数据卷挂载configmap、secret
    - name: db-config #数据卷的名字,随意设置
      configMap: # 数据卷类型为ConfigMap
        name: my-config-test1  #configMap的名字,必须跟想要加载的configmap相同
        items: #对configmap中的key进行映射,如果不指定,默认会讲configmap中所有  key全部转换为一个个同名的文件
          - key: "db.properties" # configMap中的key
            path: "db,properties"#将该key的值转换为文件
  restartPolicy: Never

通过以下容器内的文件信息可以看到,上文创建的yaml文件中对my-config-test1这个configmap种的iterm进行了定义,但是我们的这个configmap配置文件中包含了两个文件,iterms中只加载了db,并没有加载hosts。容器中的文件只有db,没有hosts。
如果不定义iterms,name就会加载全部信息。

在这里插入图片描述


[root@k8s-master configmap]# kubectl create -f test-file-po.yaml
pod/test-configfile-po created

[root@k8s-master configmap]# kubectl get po
NAME                           READY   STATUS    RESTARTS      AGE
dns-test                       1/1     Running   1 (45h ago)   45h
fluentd-59k8k                  1/1     Running   0             28h
fluentd-hhtls                  1/1     Running   0             28h
nginx-deploy-fdd948cf4-69b85   1/1     Running   0             23h
nginx-deploy-fdd948cf4-r8ktj   1/1     Running   0             27h
test-configfile-po             1/1     Running   0             7s
[root@k8s-master configmap]# kubectl exec -it test-configfile-po  -- sh
/ # cd /opt/test/
/opt/test # ll
sh: ll: not found
/opt/test # ls
db,properties
/opt/test # cat db,properties
user: root
passwd: 123456
host: 127.0.0.1
/opt/test # echo $JAVA_HOME_VM
/usr/local/jdk1.8/
/opt/test # echo $Name_Vm

/opt/test # echo $Name_VM
您好~

2、 加密数据配置Secret

2.1 Secret 介绍

  • 与ConfigMap类似,用于存储配置信息,但是主要用于存储敏感信息、需要加密的信息,Secret可以提供数据加密、解密功能。
  • 在创建Secret时,要注意如果要加密的字符中,包含了有特殊字符,需耍使用转义符转移。eg: $ 转移后为"转移符号\加上$",
  • 也可以对特殊字符使用单引号描述,这样就不需要转义。
  • eg:1$289*-! 转换为 "1$289*-! "
  • 场景使用:多用于docker镜像私有仓库的使用。
  • 加密方式为base64,可以通过 “echo “xxxx”| base64 --decode” 解密

2.2 Secret的创建

可以通过查询kubectl create secret -h命令查询secret的创建

[root@k8s-master ~]#   kubectl create secret -h
Create a secret using specified subcommand.

Available Commands:
  docker-registry   创建一个给 Docker registry 使用的 Secret
  generic           Create a secret from a local file, directory, or literal value
  tls               创建一个 TLS secret

Usage:
  kubectl create secret [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

2.2.1 创建secret资源

通过下面的命令就可以创建secret了。

[root@k8s-master ~]#   kubectl create secret -h
Create a secret using specified subcommand.

Available Commands:
  docker-registry   创建一个给 Docker registry 使用的 Secret
  generic           Create a secret from a local file, directory, or literal value
  tls               创建一个 TLS secret

Usage:
  kubectl create secret [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
  
[root@k8s-master ~]# kubectl create secret generic  test-secrete   --from-literal=username=admin --from-literal=password='12123421'
secret/test-secrete created

2.2.2 通过describe查看secret的描述

[root@k8s-master ~]# kubectl describe secrets test-secrete
Name:         test-secrete
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
password:  8 bytes
username:  5 bytes

2.2.3 通过edit 查看secret的信息

k8s-master    Ready    control-plane   6d14h   v1.25.0
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  password: MTIxMjM0MjE=
  username: YWRtaW4=
kind: Secret
metadata:
  creationTimestamp: "2024-02-26T04:28:18Z"
  name: test-secrete
  namespace: default
  resourceVersion: "519877"
  uid: 8c981ce2-7cb2-4030-8fdd-b496ae72a4fa
type: Opaque

2.2.4 通过base64反编译这个信息

通过base64 反编译出原信息,可以看到这种加密方式不是很安全

[root@k8s-master ~]# echo "MTIxMjM0MjE="  | base64 --decode
12123421

[root@k8s-master ~]# echo "YWRtaW4="  | base64 --decode
admin

2.3 secret的使用

2.3.1 创建一个docke-registry的secret

[root@k8s-master ~]#   kubectl create secret docker-registry   docker-test-secret --docker-username='lianhetiyu@1949945210135676'   --docker-password='Lanhe@123456'  --docker-email='admin@test.com'  --docker-server='registry.cn-hangzhou.aliyuncs.com'
secret/docker-test-secret created
[root@k8s-master ~]# kubectl describe sercet docker-test-secret
error: the server doesn't have a resource type "sercet"
[root@k8s-master ~]# kubectl describe secret docker-test-secret
Name:         docker-test-secret
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/dockerconfigjson

Data
====
.dockerconfigjson:  215 bytes


[root@k8s-master ~]# kubectl edit secrets test-secrete
Edit cancelled, no changes made.
[root@k8s-master ~]#
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  .dockerconfigjson: ey89JhdXRocyI6eyJyZWdpc3RyeS5jbi1oYW5nemhvdS5hbGl5dW5jcy5jb20iOnsidXNlcm5hbWUiOiJsaWFuaGV0aXl1X3doZEAxOTQ5OTQ1MjEwMTM1Njc2IiwicGFzc3dvcmQiOiJMYW5oZUAxMjM0NTYiLCJlbWFpbCI6ImFkbWluQHRlc3QuY29tIiwiYXV0aCI6ImJHbGhibWhsZEdsNWRWOTNhR1JBTVRrME9UazBOVEl4TURFek5UWTNOanBNWVc1b1pVQXhNak0wTlRZPSJ9fX0=
kind: Secret
metadata:
  creationTimestamp: "2024-02-26T06:28:49Z"
  name: docker-test-secret
  namespace: default
  resourceVersion: "530968"
  uid: d31bb3f3-6111-4848-ab51-a894df2f1be1
type: kubernetes.io/dockerconfigjson

2.3.2 创建一个拉取镜像的新pod

apiVersion: v1
kind: Pod
metadata:
  name: test-configfile-po
spec:
  imagePullSecrets:  # 配置docke仓库:docker registry 的 secret
  - name: docker-test-secret
  containers:
    - name: env-test
      image: alpine
      imagePullPolicy: IfNotPresent
      command: ["/bin/sh","-c","env  ; sleep 3600"]
      env:
      - name: JAVA_HOME_VM
        valueFrom:
          configMapKeyRef:
            name: env-test  # configmap的名字
            key: JAVA_HOME  # 表示从name的configmap种获取名字为key的value,将其赋值给本地环境变量 JAVA_HOME_VM
      - name: Name_VM
        valueFrom:
          configMapKeyRef:
            name: env-test
            key: Name
  restartPolicy: Never

2.3.3 可以通过容器的描述引用了secret资源下载镜像


[root@k8s-master configmap]# kubectl create  -f   test-docker-po.yaml
pod/test-configfile-po created


[root@k8s-master configmap]# kubectl get  po  test-configfile-po
NAME                 READY   STATUS    RESTARTS   AGE
test-configfile-po   1/1     Running   0          2m57s


[root@k8s-master configmap]# kubectl describe po  test-configfile-po
Name:             test-configfile-po
Namespace:        default
Priority:         0
Service Account:  default
Node:             k8s-node-02/10.10.10.113
Start Time:       Mon, 26 Feb 2024 16:28:01 +0800
Labels:           <none>
Annotations:      <none>
Status:           Running
IP:               10.2.1.64
IPs:
  IP:  10.2.1.64
Containers:
  env-test:
    Container ID:  docker://cbcb9ece8da46b593a766c8d0d0247e3a02a0316ba24164e3ce3d5d8bf823829
    Image:         registry.cn-hangzhou.aliyuncs.com/lhty/controller:2.1
    Image ID:      docker-pullable://registry.cn-hangzhou.aliyuncs.com/lhty/controller@sha256:96f3490f6b7693caad23f2ce143d0e23516527edcd3448589cb9498011ba19c3
    Port:          <none>
    Host Port:     <none>
    Command:
      /bin/sh
      -c
      env  ; sleep 3600
    State:          Running
      Started:      Mon, 26 Feb 2024 16:29:12 +0800
    Ready:          True
    Restart Count:  0
    Environment:
      JAVA_HOME_VM:  <set to the key 'JAVA_HOME' of config map 'env-test'>  Optional: false
      Name_VM:       <set to the key 'Name' of config map 'env-test'>       Optional: false
    Mounts:
      /opt/test/ from db-config (ro)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-nwsh6 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  db-config:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      my-config-test1
    Optional:  false
  kube-api-access-nwsh6:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  75s   default-scheduler  Successfully assigned default/test-configfile-po to k8s-node-02
  Normal  Pulling    75s   kubelet            Pulling image "registry.cn-hangzhou.aliyuncs.com/lhty/controller:2.1"
  Normal  Pulled     6s    kubelet            Successfully pulled image "registry.cn-hangzhou.aliyuncs.com/lhty/controller:2.1" in 1m8.912792712s
  Normal  Created    5s    kubelet            Created container env-test
  Normal  Started    5s    kubelet            Started container env-test

通过docker images,可以看到有刚才通过阿里云仓库拉取的镜像

在这里插入图片描述

3、SubPath的使用

场景需求:把nginx中的conf文件制作为一个configmap,后续想改动nginx的配置文件,我们只需要更新这个configmap即可,不需要重新登录进nginx容器内修改conf文件。但是

3.1 为什么需要使用SubPath?

使用configmap加载的文件到容器内目录后,如果原先有这个目录,会直接覆盖原先的目录,原先目录中的内容会丢失。

3.1.1 创建一个nginx配置文件的configmap

# 拿到容器中的nginx配置文件
root@k8s-master configmap]# kubectl exec nginx-deploy-fdd948cf4-69b85 -it -- sh -c "cat /etc/nginx/nginx.conf"  > nginx-conf-cm.conf


## 创建这个configmap
[root@k8s-master configmap]# kubectl create cm nginx-conf-cm  --from-file nginx-conf-cm.conf
configmap/nginx-conf-cm created
[root@k8s-master configmap]# kubectl describe cm nginx-conf-cm
Name:         nginx-conf-cm
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
nginx-conf-cm.conf:
----

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}


BinaryData
====

Events:  <none>

3.1.2 修改deploy信息

nginx的pod是通过deployment创建的,所以只需要修改deployment信息就可以更新nginx了。

[root@k8s-master configmap]# kubectl get deployments.apps
NAME           READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deploy   2/2     2            2           43h
[root@k8s-master configmap]# kubectl get po
NAME                           READY   STATUS    RESTARTS        AGE
dns-test                       1/1     Running   2 (5h14m ago)   2d14h
fluentd-59k8k                  1/1     Running   1 (5h14m ago)   44h
fluentd-hhtls                  1/1     Running   1 (5h14m ago)   44h
nginx-deploy-fdd948cf4-69b85   1/1     Running   1 (5h14m ago)   40h
nginx-deploy-fdd948cf4-r8ktj   1/1     Running   1 (5h14m ago)   43h
test-configfile-po             1/1     Running   0               18m

## 通过edit deploy nginx-deploy文件添加如下内容,如下内容需要和 containers 同一级别。
containers
  command: ['/bin/sh','-c','nginx daemon off; sleep 3600']  # 为了防止容器启动失败。
  volumesMounts:
  - name: nginx-conf
    mountPath: '/etc/nginx'
volumes:
- name: nginx-conf
  configMap:
  - name: nginx-conf-cm   # configmap的名字
    items:
    - key: nginx-conf-cm.conf  # configmap种文件的名字
      path: nginx.conf

在这里插入图片描述

3.1.3 查看更新后过的nginx pod

[root@k8s-master configmap]# kubectl get po
NAME                            READY   STATUS      RESTARTS        AGE
dns-test                        1/1     Running     2 (5h57m ago)   2d14h
fluentd-59k8k                   1/1     Running     1 (5h58m ago)   45h
fluentd-hhtls                   1/1     Running     1 (5h57m ago)   45h
nginx-deploy-7d6db4657b-7pzc2   1/1     Running     0               38s
nginx-deploy-7d6db4657b-qq8sc   1/1     Running     0               40s
test-configfile-po              0/1     Completed   0               62m
[root@k8s-master configmap]# kubectl describe po nginx-deploy-7d6db4657b-7pzc2
Name:             nginx-deploy-7d6db4657b-7pzc2
Namespace:        default
Priority:         0
Service Account:  default
Node:             k8s-node-01/10.10.10.177
Start Time:       Mon, 26 Feb 2024 17:29:41 +0800
Labels:           app=nginx-deploy
                  pod-template-hash=7d6db4657b
Annotations:      <none>
Status:           Running
IP:               10.2.2.39
IPs:
  IP:           10.2.2.39
Controlled By:  ReplicaSet/nginx-deploy-7d6db4657b
Containers:
  nginx:
    Container ID:  docker://6b349ede9bb23d51add64c24b28bab4a5df2804ea7bbe0e5efdcc97ba405a005
    Image:         nginx:1.20
    Image ID:      docker-pullable://nginx@sha256:03f3cb0afb7bd5c76e01bfec0ce08803c495348dccce37bcb82c347b4853c00b
    Port:          <none>
    Host Port:     <none>
    Command:
      /bin/sh
      -c
      nginx daemon off; sleep 3600
    State:          Running
      Started:      Mon, 26 Feb 2024 17:29:42 +0800
    Ready:          True
    Restart Count:  0
    Limits:
      cpu:     200m
      memory:  128Mi
    Requests:
      cpu:        100m
      memory:     128Mi
    Environment:  <none>
    Mounts:
      /etc/nginx/ from nginx-conf (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-9xskq (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  nginx-conf:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      nginx-conf-cm
    Optional:  false
  kube-api-access-9xskq:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   Burstable
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  85s   default-scheduler  Successfully assigned default/nginx-deploy-7d6db4657b-7pzc2 to k8s-node-01
  Normal  Pulled     85s   kubelet            Container image "nginx:1.20" already present on machine
  Normal  Created    85s   kubelet            Created container nginx
  Normal  Started    85s   kubelet            Started container nginx

3.1.4 /etc/nginx/ 这个路径下只有一个nginx的配置文件,其他文件全部没了

[root@k8s-master configmap]# kubectl exec -it  nginx-deploy-7d6db4657b-7pzc2  -- sh  -c  'ls /etc/nginx/'
nginx.conf
[root@k8s-master configmap]# kubectl exec -it  nginx-deploy-7d6db4657b-7pzc2  -- sh  -c  'cat  /etc/nginx/nginx.conf'

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

3.2 如何使用SubPath?

  • 1、定义volumes时需要增加items属性,配置key和path,且path的值不能从/开始
  • 2、在容器内的volumeMounts中增加subPath黑性,该值与volumes中tems.path的值相同。

3.2.1 修改deploy,添加subPath

在这里插入图片描述

在这里插入图片描述

3.2.2 在进容器查看下/etc/nginx目录内容

在这里插入图片描述

4、配置的热更新

我们通常会将项目的配置文件作为configmap然后挂载到pod,那么如果更新configmap中的配置,会不会更新到pod中呢?
这得分成几种情况:
默认方式:会更新,更新同期是更新间+缓存时间
subPath:不会更新
变量形式:如果pod中的一个变量是从configmap或secret中得到,同样也是不会更新的。
对于subPath的方式,我们可以取消subPath的使用,将配置文件挂载到一个不存在的目录,避免目录的夏盖,然后再利用软连接的形式,将该文件链接到目标位置。

4.1 通过edit 命令直接修改configmap

4.1.1 创建一个pod

apiVersion: v1
kind: Pod
metadata:
  name: configfile-po
spec:
  containers:
    - name: configmap-po
      image: alpine
      imagePullPolicy: IfNotPresent
      command: ["/bin/sh","-c","env  ; sleep 3600"]
      volumeMounts:  #  加载数据卷
      - name: db-config  # 加载数据卷的名字
        mountPath: "/opt/test/"   #将数据卷加载到什么目录
        readOnly: true  #  是否只读
  volumes: # 数据卷挂载configmap、secret
    - name: db-config #数据卷的名字,随意设置
      configMap: # 数据卷类型为ConfigMap
        name: my-config-test1  #configMap的名字,必须跟想要加载的configmap相同
        items: #对configmap中的key进行映射,如果不指定,默认会讲configmap中所有  key全部转换为一个个同名的文件
          - key: "db.properties" # configMap中的key
            path: "db.txt" # 将该key的值转换为文件
  restartPolicy: Never
[root@k8s-master configmap]# kubectl get cm
NAME               DATA   AGE
env-test           2      18h
kube-root-ca.crt   1      6d20h
my-config-test1    2      18h
my-config-test3    2      18h
nginx-conf-cm      1      102m


[root@k8s-master configmap]# kubectl create -f configfile-po.yaml
pod/configfile-po created

[root@k8s-master configmap]# kubectl get po
NAME                           READY   STATUS    RESTARTS        AGE
configfile-po                  1/1     Running   0               20s
dns-test                       1/1     Running   2 (6h53m ago)   2d15h
fluentd-59k8k                  1/1     Running   1 (6h53m ago)   46h
fluentd-hhtls                  1/1     Running   1 (6h53m ago)   46h
nginx-deploy-6fb8d6548-8khhv   1/1     Running   0               31m
nginx-deploy-6fb8d6548-fd9tx   1/1     Running   0               31m
[root@k8s-master configmap]# kubectl  exec -it configfile-po  -- sh -c 'cat /opt/test/db.txt '
user: root
passwd: 123456
host: 127.0.0.1

4.1.2 通过edit编辑my-config-test1,给configmap中添加一条信息

在这里插入图片描述

4.1.3 查看容器中的内容更新情况(需要等一段时间才会更新)

[root@k8s-master configmap]# kubectl  exec -it configfile-po  -- sh -c 'cat /opt/test/db.txt '
user: root
passwd: 123456
host: 127.0.0.1
date: '2024-02-26'

4.2 通过replace进行更新

由于conigmap我们创建通常都是基于文件创建,并不会编写yaml配置文件,因比修改时我们也是直接修改配置文件,而replace是没有 --from-file 参数的,因此无法实现基于源配置文件的替换,此时我们可以利用下方的命令实现

该命令的重点在于 --dry-run 参数,该参数的意思打印yaml文件,但不会将该文件发送给api-server,再结合 -o yaml输出yaml文件就可以得到一个配置好但是没有发给api-server的文件,然后再结合replace监听控制台得到yaml数据即可实现替换。
kubectl create cm --from-file=nginx.conf --dry-run -o yaml | kubectl replace-f-

4.2.1 更新需要添加到configmap的文件

[root@k8s-master configmap]#  echo 'service: test'  >>  ./file/db.properties

4.2.2 通过 kubectl create cm --from-file=nginx.conf --dry-run -o yaml | kubectl replace-f- 更新configmap

[root@k8s-master configmap]# kubectl create cm   my-config-test1  --from-file=./file/   --dry-run -o yaml
W0226 21:19:22.889508   89629 helpers.go:639] --dry-run is deprecated and can be replaced with --dry-run=client.
apiVersion: v1
data:
  db.properties: |
    user: root
    passwd: 123456
    host: 127.0.0.1
    service: test
  host.properties: |
    k8s-master: 10.10.10.100
    k8s-node-01: 10.10.10.177
    k8s-node-02: 10.10.10.113
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: my-config-test1


[root@k8s-master configmap]# kubectl create cm   my-config-test1  --from-file=./file/   --dry-run -o yaml | kubectl replace -f-
W0226 21:21:09.680288   90368 helpers.go:639] --dry-run is deprecated and can be replaced with --dry-run=client.
configmap/my-config-test1 replaced
[root@k8s-master configmap]#

4.2.3 查看configmap

[root@k8s-master configmap]# kubectl describe  cm my-config-test1
Name:         my-config-test1
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
db.properties:
----
user: root
passwd: 123456
host: 127.0.0.1
service: test

host.properties:
----
k8s-master: 10.10.10.100
k8s-node-01: 10.10.10.177
k8s-node-02: 10.10.10.113


BinaryData
====

Events:  <none>

4.2.4 查看容器内文件,已经更新

[root@k8s-master configmap]# kubectl exec -it  configfile-po   -- sh -c 'cat /opt/test/db.txt'
user: root
passwd: 123456
host: 127.0.0.1
service: test

5、不可变的configmap和secret

  • 对于一些敏感服务的配置文件,在线上有时是不允许修改的,此时在配置configmap时可以设置 immutable:true 来禁止修改

5.1 查看之前创建的my-confgi-test1这个configmap配置

[root@k8s-master configmap]# kubectl describe cm my-config-test1
Name:         my-config-test1
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
db.properties:
----
user: root
passwd: 123456
host: 127.0.0.1
service: test

host.properties:
----
k8s-master: 10.10.10.100
k8s-node-01: 10.10.10.177
k8s-node-02: 10.10.10.113


BinaryData
====

Events:  <none>

5.2 通过kubectl edit cm my-config-test1 添加 immutable: true

在这里插入图片描述

5.3 再次通过edit修改文件,发现已经无法更改文件了

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/418577.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

蓝牙耳机和笔记本电脑配对连接上了,播放设备里没有显示蓝牙耳机这个设备,选不了输出设备

环境&#xff1a; WIN10 杂牌蓝牙耳机6s 问题描述&#xff1a; 蓝牙耳机和笔记本电脑配对连接上了&#xff0c;播放设备里没有显示蓝牙耳机这个设备&#xff0c;选不了输出设备 解决方案&#xff1a; 1.打开设备和打印机&#xff0c;找到这个设备 2.选中这个设备&#…

Linux下gcc编译常用命令详解

在Linux环境下&#xff0c;使用gcc编译器进行源代码的编译是程序员日常工作的一部分。本篇将介绍一些常用的gcc编译命令&#xff0c;帮助开发者更好地理解和使用这些命令。 1. 基本编译命令 gcc工作流程&#xff1a; 编译单个源文件 gcc source.c -o output这个命令将sour…

java学习笔记-初级

一、变量 1.双标签 <!-- 外部js script 双标签 --><script srcmy.js></script> 在新文件my.js里面写&#xff1a; 2.字符串定义&#xff1a; //外单内双var str 我是一个"高富帅"的程序员;console.log(str);// 字符串转义字符 都是用 \ 开头 …

Jenkins自动化部署之流水线模式部署

文章目录 任务类型Pipeline流水线项目声明式的Pipeline脚本式Pipeline 示例脚本生成Tools配置示例 高级Pipeline Script from SCM 任务类型 在Jenkins中&#xff0c;有不同类型的任务&#xff08;项目&#xff09;适用于不同的构建需求。以下是一些常见的Jenkins任务类型&…

供应链投毒预警 | 恶意NPM包利用Windows反向shell后门攻击开发者

概述 本周&#xff08;2024年02月19号&#xff09;&#xff0c;悬镜供应链安全情报中心在NPM官方仓库&#xff08;https://npmjs.com&#xff09;中发现多起NPM组件包投毒事件。攻击者利用包名错误拼写方式 (typo-squatting)在NPM仓库中连续发布9个不同版本的恶意包&#xff0…

ubuntu20.04 ROS-Noetic 配置qtcreator的ROS环境

文章目录 1 安装qtcreator1.1 下载安装Qt1.2 配置命令启动qtcreator2 配置ROS2.1 直接安装qtcreator-ros2.2 在qtcreator上安装ros_qtc_plugin插件3 注意3.1 构建套件3.2 更新、删除qt4 参考链接1 安装qtcreator QT官网:Qt Downloads 下载包链接:qt5.12.12 Qt5.12.12默认qtc…

SpringBoot使用classfinal-maven-plugin插件加密Jar包

jar包加密 1、在启动类的pom.xml中加入classfinal-maven-plugin插件 <build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><plugin><…

官网万词霸屏推广+关键词排名优化源码系统 带完整的安装代码包以及搭建教程

随着搜索引擎算法的不断更新和市场竞争的加剧&#xff0c;传统的SEO方法已经难以满足企业对于快速、高效推广的需求。罗峰结合多年的互联网营销经验和最新的搜索引擎优化技术&#xff0c;给大家推荐一款集网站搭建、关键词优化、数据分析于一体的源码系统。 以下是部分代码示例…

Linux信号【产生-保存-处理】

目录 前言&#xff1a; 1、进程信号基本概念 1.1、什么是信号&#xff1f; 1.2、信号的作用 2、键盘键入 2.1、ctrlc 终止前台进程 2.1.1、signal 注册执行动作 3、系统调用 3.1、kill 函数 3.2、模拟实现 myKill 3.3、raise 函数 3.4、abort 函数 4、软件条件信号…

时间序列分析实战(十一):ECM误差修正模型

&#x1f349;CSDN小墨&晓末:https://blog.csdn.net/jd1813346972 个人介绍: 研一&#xff5c;统计学&#xff5c;干货分享          擅长Python、Matlab、R等主流编程软件          累计十余项国家级比赛奖项&#xff0c;参与研究经费10w、40w级横向 文…

服务器数据恢复-服务器RAID5上层XFS文件系统分区数据恢复案例

服务器数据恢复环境&#xff1a; MD1200磁盘柜中的磁盘通过RAID卡创建了一组RAID5阵列&#xff0c;分配了一个LUN。在Linux操作系统层面对该LUN进行了分区&#xff0c;划分sdc1和sdc2两个分区&#xff0c;通过LVM扩容的方式将sdc1分区加入到了root_lv中&#xff1b;sdc2分区格式…

代码随想录第46天|139.单词拆分 多重背包理论基础 背包总结

文章目录 单词拆分思路&#xff1a;代码 多重背包≈0-1背包题目代码 背包总结 单词拆分 3 思路&#xff1a; 代码 class Solution {public boolean wordBreak(String s, List<String> wordDict) {HashSet<String> set new HashSet<>(wordDict);boolean[]…

视频记录仪_基于联发科MT6762的智能4G记录仪方案

智能记录仪采用联发科强劲八核处理器&#xff0c;12nm制程工艺的记录仪具便是满足这些需求的理想选择。搭载4GB32GB内存&#xff0c;并运行Android 11.0操作系统&#xff0c;这款记录仪具展现出强劲的性能表现。 首先&#xff0c;这款记录仪具具备优秀的视频录制功能。它能完整…

综合练习(一)

目录 列出薪金高于部门 30 的所有员工薪金的员工姓名和薪金、部门名称、部门人数 列出与 ALLEN从事相同工作的所有员工及他们的部门名称、部门人数、领导姓名 Oracle从入门到总裁:https://blog.csdn.net/weixin_67859959/article/details/135209645 列出薪金高于部门 30 的所…

【音视频处理】使用ffmpeg实现多个视频合成一个视频(按宫格视图)

先上结果 环境 硬件&#xff1a;通用PC 系统&#xff1a;Windows 测试有效 软件&#xff1a;ffmpeg 解决 0、命令 ffmpeg.exe -i input1.mp4 -i input2.mp4 -i input3.mp4 -i input4.mp4 -filter_complex "[0:v]scaleiw/2:ih/2,pad2*iw:2*ih[a]; [1:v]scaleiw/2:ih/2…

人脸2D和3D道具SDK解决方案提供商

人脸识别和增强现实技术成为了许多企业和开发者关注的焦点&#xff0c;为了满足市场对高质量、易于集成的人脸识别SDK的需求&#xff0c;美摄科技推出了一系列领先的人脸2D/3D道具SDK解决方案。 一、产品特点 高精度识别&#xff1a;美摄科技的人脸识别技术采用深度学习算法&…

【OCR识别】使用OCR技术还原加密字体文字

文章目录 1. 写在前面2. 页面分析3. 字符知识4. 加密分析 【作者主页】&#xff1a;吴秋霖 【作者介绍】&#xff1a;Python领域优质创作者、阿里云博客专家、华为云享专家。长期致力于Python与爬虫领域研究与开发工作&#xff01; 【作者推荐】&#xff1a;对JS逆向感兴趣的朋…

VirtualBox虚拟机安装 Linux 系统

要想学习各种计算机技术&#xff0c;自然离不开Linux系统。并且目前大多数生产系统都是安装在Linux系统上。常用的Linux系统有 Redhat&#xff0c;Centos&#xff0c;OracleLinux 三种。 三者的区别简单说明如下&#xff1a; Red Hat Enterprise Linux (RHEL): RHEL 是由美国…

微信小程序构建npm失败解决方式

安装完所需要的依赖后&#xff0c;在微信开发者工具菜单栏中选择&#xff1a;“工具” -> “构建 npm”&#xff0c;但是失败。 解决方法&#xff1a;修改 project.config.json 开发者工具创建的项目&#xff0c;miniprogramRoot 默认为 miniprogram&#xff0c;package.js…

Vue3自定义文件列表页面(含上传、搜索、复制链接)

文章目录 一、代码展示二、代码解读三、结果展示 一、代码展示 <template><div class"container"><h1>文件列表</h1><div class"header-actions"><a-input placeholder"输入关键词搜索" v-model:value"…
最新文章