应用配置--容器化应用配置

容器化应用配置方法:

1.启动容器时直接向应用程序传递参数

2.将定义好的配置文件硬编码(嵌入)于镜像文件中

3.通过环境变量传递配置数据

4.基于存储卷传递配置文件

 

通过环境变量向容器注入配置信息

Kubernetes系统支持在为Pod资源配置容器时使用spec.containers.env为容器的环境变量传值从而完成应用的配置。

env字段,它的值由一个环境变量构建的列表。每个环境变量通常由name和value(或者valueFrom)字段构成。

value:环境变量的值(自定义的);valueFrom:环境变量值的引用源,例如当前pod资源的名称,名称空间,标签等,不能与非空值的value字段同时使用;

valueFrom字段可引用的值有多种来源,包括当前pod资源的属性值,容器相关的系统资源配置,ConfigMap对象中的key以及Secert对象中的key,他们分别要使用不同的嵌套字段进行定义。

fieldRef:用于pod资源

configMapKeyRef:用于configMap

secretKeyRef:用于secret

resourceFieldRef:用于当前容器的特定系统资源的最小值(配额)或者最大值(限额),目前支持的引用包括limits.cpu、limits.memory、limits.ephemeral-storage(最小空间)  、requests.cpu、requests.memory、requests.ephemeral-storage

 

下面资源清单文件env-demo.yaml是定义pod资源

 

[root@k8s-master01 yaml]# cat env-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: env-demo
  labels:
    purpose: demonstrate-environment-variables
spec:
  containers:
  - name: env-demo-container
    image: busybox
    command: ["httpd"]
    args: ["-f"]
    env:
    - name: HELLO_WORLD
      value: just a demo
    - name: MY_NODE_NAME
      valueFrom:
        fieldRef:
          fieldPath: spec.nodeName
    - name: MY_NODE_IP
      valueFrom:
        fieldRef:
          fieldPath: status.hostIP
    - name: MY_POD_NAMESPACE
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace
  restartPolicy: OnFailure

 

[root@k8s-master01 yaml]# kubectl apply -f env-demo.yaml -n dev
pod/env-demo created
[root@k8s-master01 yaml]# kubectl get pods/env-demo
Error from server (NotFound): pods "env-demo" not found
[root@k8s-master01 yaml]# kubectl get pods/env-demo -n dev
NAME       READY   STATUS    RESTARTS   AGE
env-demo   1/1     Running   0          32s
[root@k8s-master01 yaml]# kubectl get pods/env-demo -n dev -o wide
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE         NOMINATED NODE   READINESS GATES
env-demo   1/1     Running   0          42s   10.244.2.7   k8s-node02   <none>           <none>

[root@k8s-master01 yaml]# kubectl exec env-demo printenv -n dev
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=env-demo
MY_POD_NAMESPACE=dev
HELLO_WORLD=just a demo
MY_NODE_NAME=k8s-node02
MY_NODE_IP=192.168.3.22
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_SERVICE_PORT=443
HOME=/root

 

[root@k8s-master01 yaml]# kubectl describe pod/env-demo -n dev
Name:         env-demo
Namespace:    dev
Priority:     0
Node:         k8s-node02/192.168.3.22
Start Time:   Fri, 20 Aug 2021 10:04:26 +0800
Labels:       purpose=demonstrate-environment-variables
Annotations:  <none>
Status:       Running
IP:           10.244.2.7
IPs:
  IP:  10.244.2.7
Containers:
  env-demo-container:
    Container ID:  docker://b473bd3b5edf257e58adaf14488d5a03e6c9972f05d0c47cc9cf598a52d1fa4c
    Image:         busybox
    Image ID:      docker-pullable://busybox@sha256:0f354ec1728d9ff32edcd7d1b8bbdfc798277ad36120dc3dc683be44524c8b60
    Port:          <none>
    Host Port:     <none>
    Command:
      httpd
    Args:
      -f
    State:          Running
      Started:      Fri, 20 Aug 2021 10:04:32 +0800
    Ready:          True
    Restart Count:  0
    Environment:
      HELLO_WORLD:       just a demo
      MY_NODE_NAME:       (v1:spec.nodeName)
      MY_NODE_IP:         (v1:status.hostIP)
      MY_POD_NAMESPACE:  dev (v1:metadata.namespace)
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-7p2m9 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-7p2m9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-7p2m9
    Optional:    false
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  94s                        Successfully assigned dev/env-demo to k8s-node02
  Normal  Pulling    92s   kubelet, k8s-node02  Pulling image "busybox"
  Normal  Pulled     88s   kubelet, k8s-node02  Successfully pulled image "busybox" in 3.374459704s
  Normal  Created    88s   kubelet, k8s-node02  Created container env-demo-container
  Normal  Started    88s   kubelet, k8s-node02  Started container env-demo-container

 

 

ConfigMap

configMap资源用于在运行时将配置文件、命令行参数、环境变量、端口号以及其他配置工作绑定至pod的容器和系统组件。

configMap资源用于存储和共享非敏感和未加密的配置信息。

 下面是字面量(literal) 值数据源

创建configMap对象

[root@k8s-master01 yaml]# kubectl create configmap demoapp-config --from-literal=demoapp.host='0.0.0.0' --from-literal=demoapp.port='80' --namespace='dev'
configmap/demoapp-config created

创建demoapp-config时传递了2个键值对。

[root@k8s-master01 yaml]# kubectl get configmaps demoapp-config -n dev -o yaml
apiVersion: v1
data:
  demoapp.host: 0.0.0.0
  demoapp.port: "80"
kind: ConfigMap
metadata:
  creationTimestamp: "2021-08-20T05:00:20Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:demoapp.host: {}
        f:demoapp.port: {}
    manager: kubectl-create
    operation: Update
    time: "2021-08-20T05:00:20Z"
  name: demoapp-config
  namespace: dev
  resourceVersion: "394543"
  selfLink: /api/v1/namespaces/dev/configmaps/demoapp-config
  uid: af5e4b1e-5c24-477e-b271-9ac18b4dfc00

get configmap 命令输出的demoapp-config对象yaml格式信息可以看出,comfigmap资源没有spec和status字段,而是直接使用data字段嵌套键值信息。

所以,若是要基于配置清单创建configmap资源时仅仅需要指定 apiversion、kind、data、metadata这4个字段

 

下面是文件数据源

 

configmap资源也可以用于为应用程序提供大段配置,可以kubectl create configmap命令通过--from-file选项一次加载一个配置文件的内容为指定键的值,多个文件的加载可以重复使用。

先安装nginx

[root@k8s-master01 ~]# vim /etc/yum.repos.d/nginx.repo 
[nginx] 
name=nginx repo 
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ 
gpgcheck=0 
enabled=1


yum  install  -y  nginx

 

[root@k8s-master01 ~]# kubectl create configmap nginx-confs --from-file=/etc/nginx/conf.d/default.conf  --namespace='dev'

[root@k8s-master01 ~]# kubectl get configmap nginx-confs -n dev -o yaml
apiVersion: v1
data:
  default.conf: |+
    server {
        listen       80;
        server_name  localhost;

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

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

kind: ConfigMap
metadata:
  creationTimestamp: "2021-08-20T12:48:50Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:default.conf: {}
    manager: kubectl-create
    operation: Update
    time: "2021-08-20T12:48:50Z"
  name: nginx-confs
  namespace: dev
  resourceVersion: "1926904"
  selfLink: /api/v1/namespaces/dev/configmaps/nginx-confs
  uid: 1498c8f3-9822-46b9-94f6-bc7676b0fc7a

上面是单个文件,对于配置文件比较多,且无需自定义键名的时候,可以直接把选项附加上一个路径

[root@k8s-master01 ~]# kubectl create configmap nginx-config-files --from-file=/etc/nginx/
configmap/nginx-config-files created
[root@k8s-master01 ~]# kubectl describe configmap nginx-config-files
Name:         nginx-config-files
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
fastcgi_params:
----

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

mime.types:
----

types {
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
    image/jpeg                                       jpeg jpg;
    application/javascript                           js;
    application/atom+xml                             atom;
    application/rss+xml                              rss;

    text/mathml                                      mml;
    text/plain                                       txt;
    text/vnd.sun.j2me.app-descriptor                 jad;
    text/vnd.wap.wml                                 wml;
    text/x-component                                 htc;

    image/png                                        png;
    image/svg+xml                                    svg svgz;
    image/tiff                                       tif tiff;
    image/vnd.wap.wbmp                               wbmp;
    image/webp                                       webp;
    image/x-icon                                     ico;
    image/x-jng                                      jng;
    image/x-ms-bmp                                   bmp;

    font/woff                                        woff;
    font/woff2                                       woff2;

    application/java-archive                         jar war ear;
    application/json                                 json;
    application/mac-binhex40                         hqx;
    application/msword                               doc;
    application/pdf                                  pdf;
    application/postscript                           ps eps ai;
    application/rtf                                  rtf;
    application/vnd.apple.mpegurl                    m3u8;
    application/vnd.google-earth.kml+xml             kml;
    application/vnd.google-earth.kmz                 kmz;
    application/vnd.ms-excel                         xls;
    application/vnd.ms-fontobject                    eot;
    application/vnd.ms-powerpoint                    ppt;
    application/vnd.oasis.opendocument.graphics      odg;
    application/vnd.oasis.opendocument.presentation  odp;
    application/vnd.oasis.opendocument.spreadsheet   ods;
    application/vnd.oasis.opendocument.text          odt;
    application/vnd.openxmlformats-officedocument.presentationml.presentation
                                                     pptx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                                                     xlsx;
    application/vnd.openxmlformats-officedocument.wordprocessingml.document
                                                     docx;
    application/vnd.wap.wmlc                         wmlc;
    application/x-7z-compressed                      7z;
    application/x-cocoa                              cco;
    application/x-java-archive-diff                  jardiff;
    application/x-java-jnlp-file                     jnlp;
    application/x-makeself                           run;
    application/x-perl                               pl pm;
    application/x-pilot                              prc pdb;
    application/x-rar-compressed                     rar;
    application/x-redhat-package-manager             rpm;
    application/x-sea                                sea;
    application/x-shockwave-flash                    swf;
    application/x-stuffit                            sit;
    application/x-tcl                                tcl tk;
    application/x-x509-ca-cert                       der pem crt;
    application/x-xpinstall                          xpi;
    application/xhtml+xml                            xhtml;
    application/xspf+xml                             xspf;
    application/zip                                  zip;

    application/octet-stream                         bin exe dll;
    application/octet-stream                         deb;
    application/octet-stream                         dmg;
    application/octet-stream                         iso img;
    application/octet-stream                         msi msp msm;

    audio/midi                                       mid midi kar;
    audio/mpeg                                       mp3;
    audio/ogg                                        ogg;
    audio/x-m4a                                      m4a;
    audio/x-realaudio                                ra;

    video/3gpp                                       3gpp 3gp;
    video/mp2t                                       ts;
    video/mp4                                        mp4;
    video/mpeg                                       mpeg mpg;
    video/quicktime                                  mov;
    video/webm                                       webm;
    video/x-flv                                      flv;
    video/x-m4v                                      m4v;
    video/x-mng                                      mng;
    video/x-ms-asf                                   asx asf;
    video/x-ms-wmv                                   wmv;
    video/x-msvideo                                  avi;
}

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;
}

scgi_params:
----

scgi_param  REQUEST_METHOD     $request_method;
scgi_param  REQUEST_URI        $request_uri;
scgi_param  QUERY_STRING       $query_string;
scgi_param  CONTENT_TYPE       $content_type;

scgi_param  DOCUMENT_URI       $document_uri;
scgi_param  DOCUMENT_ROOT      $document_root;
scgi_param  SCGI               1;
scgi_param  SERVER_PROTOCOL    $server_protocol;
scgi_param  REQUEST_SCHEME     $scheme;
scgi_param  HTTPS              $https if_not_empty;

scgi_param  REMOTE_ADDR        $remote_addr;
scgi_param  REMOTE_PORT        $remote_port;
scgi_param  SERVER_PORT        $server_port;
scgi_param  SERVER_NAME        $server_name;

uwsgi_params:
----

uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;

uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  REQUEST_SCHEME     $scheme;
uwsgi_param  HTTPS              $https if_not_empty;

uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;

Events:  <none>

查看该对象的数据条目

[root@k8s-master01 ~]# kubectl get configmaps/nginx-config-files
NAME DATA AGE
nginx-config-files 5 4m10s  #5条

 

基于字面量值和基于文件创建可以混合使用

[root@k8s-master01 ~]# kubectl create configmap nginx-config-literal --from-file=/etc/nginx/ --from-literal=nginx.host='0.0.0.0' --from-literal=nginx.port='8080'
configmap/nginx-config-literal created
[root@k8s-master01 ~]# kubectl get configmaps/nginx-config-literal
NAME                   DATA   AGE
nginx-config-literal   7      20s      #变成7条数据

 

通过环境变量引用configMao键值

[root@k8s-master01 yaml]# kubectl apply -f configmaps-env-demo.yaml -n dev
pod/configmaps-env-demo created
error: unable to recognize "configmaps-env-demo.yaml": no matches for kind "configMap" in version "v1"
##
错误原因是configMap的c没有大写

[root@k8s-master01 yaml]# cat configmaps-env-demo.yaml 
apiVersion : v1
kind: ConfigMap   #注意不要忘记c大写
metadata:
  name: demoapp-config
  namespace: dev
data:
  demoapp.port: "8080"
  demoapp.host: 0.0.0.0

---
apiVersion: v1
kind: Pod
metadata:
  name: configmaps-env-demo
  namespace: dev
spec:
  containers:
  - image: ikubernetes/demoapp:v1.0
    name: demoapp
    env:
    - name: PORT
      valueFrom: 
        configMapKeyRef:
          name: demoapp-config
          key: demoapp.port
          optional: false
    - name: HOST
      valueFrom:
        configMapKeyRef:
          name: demoapp-config
          key: demoapp.host
          optional: true

[root@k8s-master01 yaml]# kubectl  exec configmaps-env-demo -n dev -- netstat -tnl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      

 

posted @ 2021-08-20 10:54  拥抱大海,面向天空  阅读(374)  评论(0)    收藏  举报