啃k8s之YAML文件概论与演示

一:YAML文件概论与演示

1.1:概述

  • k8s支持使用YAML和JSON格式的文件来创建资源对象,相比较而言:

    • json格式的文件用于接口之间消息的传递,更适合二次开发
    • yaml格式的文件只是一种简洁的非标记性语言,更适合运维
  • YAML的文件格式和注意事项

1、不支持制表符tab键缩进,需要使用空格缩进,使用缩进表示层级关系
2、通常开头缩进2个空格,缩进的空格数不重要,只要相同层级的元素左对齐即可
3、字符后缩进一个空格,如冒号、逗号、横杆
4、用#号注释
5、如果包含特殊字符用单引号引起来
6、布尔值必须用引号括起来
7、—表示yaml文件格式的分割

1.2:使用YAML文件创建资源对象

  • 查看资源版本标签
[root@master ~]# kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
  • 创建目录,编辑测试文件
[root@master ~]# mkdir test 
[root@master ~]# cd test/
[root@master test]# vim nginx-test.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.15.4
        ports:
        - containerPort: 80
  • 创建资源对象
[root@master test]# kubectl create -f nginx-test.yaml
deployment.apps/nginx-deployment created
[root@master test]# kubectl get pod		'创建成功'
NAME                              READY   STATUS    RESTARTS   AGE
nginx-dbddb74b8-9csfl             1/1     Running   0          24h
nginx-deployment-d55b94fd-q9vcm   1/1     Running   0          57s
nginx-deployment-d55b94fd-r5nr2   1/1     Running   0          57s
nginx-deployment-d55b94fd-xj67v   1/1     Running   0          57s
  • 创建service服务对外提供访问并测试
[root@master test]#  vim nginx-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  labels:
    app: nginx
spec:
  type: NodePort
  ports:

  - port: 80
    targetPort: 80
      selector:
    app: nginx
[root@master test]# kubectl create -f nginx-service.yaml
service/nginx-service created
[root@master test]# kubectl get svc
NAME            TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        26h
nginx-service   NodePort    10.0.0.174   <none>        80:30928/TCP   62s
  • 访问网站

在这里插入图片描述

1.3:使用命令快速生成YAML或者JSON文件

  • 测试创建资源对象的命令正确性,并不真正执行创建
[root@master test]# kubectl run nginx-test01 --image=nginx --port=80 --replicas=3 --dry-run
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx-test01 created (dry run)
  • 自动生成yaml格式的文件不保存
[root@master test]# kubectl run nginx-test01 --image=nginx --port=80 --replicas=3 --dry-run -o yaml
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    run: nginx-test01
  name: nginx-test01
spec:
  replicas: 3
  selector:
    matchLabels:
      run: nginx-test01
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx-test01
    spec:
      containers:
      - image: nginx
        name: nginx-test01
        ports:
        - containerPort: 80
        resources: {}
status: {}
[root@master test]# kubectl run nginx-test01 --image=nginx --port=80 --replicas=3 --dry-run -o json
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
{
    "kind": "Deployment",
    "apiVersion": "apps/v1beta1",
    "metadata": {
        "name": "nginx-test01",
        "creationTimestamp": null,
        "labels": {
            "run": "nginx-test01"
        }
    },
    "spec": {
        "replicas": 3,
        "selector": {
            "matchLabels": {
                "run": "nginx-test01"
            }
        },
        "template": {
            "metadata": {
                "creationTimestamp": null,
                "labels": {
                    "run": "nginx-test01"
                }
            },
            "spec": {
                "containers": [
                    {
                        "name": "nginx-test01",
                        "image": "nginx",
                        "ports": [
                            {
                                "containerPort": 80
                            }
                        ],
                        "resources": {}
                    }
                ]
            }
        },
        "strategy": {}
    },
    "status": {}
}
  • 自动生成yaml格式的文件并保存
[root@master test]# kubectl run nginx-test01 --image=nginx --port=80 --replicas=3 --dry-run -o yaml > nginx-test01.yaml
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
[root@master test]# ls
nginx-service.yaml  nginx-test01.yaml  nginx-test.yaml
  • 将现有的资源生成模板并导出
[root@master test]# kubectl get pod
NAME                              READY   STATUS    RESTARTS   AGE
nginx-dbddb74b8-9csfl             1/1     Running   0          25h
nginx-deployment-d55b94fd-q9vcm   1/1     Running   0          13m
nginx-deployment-d55b94fd-r5nr2   1/1     Running   0          13m
nginx-deployment-d55b94fd-xj67v   1/1     Running   0          13m
[root@master test]# kubectl get deployment/nginx --export -o yaml > nginx-test02.yaml
[root@master test]# ls
nginx-service.yaml  nginx-test01.yaml  nginx-test02.yaml  nginx-test.yaml
  • 查看yaml文件某一字段的帮助信息
[root@master test]# kubectl explain pods.spec.containers
KIND:     Pod
VERSION:  v1

RESOURCE: containers <[]Object>

DESCRIPTION:
     List of containers belonging to the pod. Containers cannot currently be
     added or removed. There must be at least one container in a Pod. Cannot be
     updated.

     A single application container that you want to run within a pod.

FIELDS:
   args	<[]string>
     Arguments to the entrypoint. The docker image's CMD is used if this is not
     provided. Variable references $(VAR_NAME) are expanded using the
     container's environment. If a variable cannot be resolved, the reference in
     the input string will be unchanged. The $(VAR_NAME) syntax can be escaped
     with a double $$, ie: $$(VAR_NAME). Escaped references will never be
     expanded, regardless of whether the variable exists or not. Cannot be
     updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

   command	<[]string>
     Entrypoint array. Not executed within a shell. The docker image's
     ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
     are expanded using the container's environment. If a variable cannot be
     resolved, the reference in the input string will be unchanged. The
     $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME).
     Escaped references will never be expanded, regardless of whether the
     variable exists or not. Cannot be updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

   env	<[]Object>
     List of environment variables to set in the container. Cannot be updated.

   envFrom	<[]Object>
     List of sources to populate environment variables in the container. The
     keys defined within a source must be a C_IDENTIFIER. All invalid keys will
     be reported as an event when the container is starting. When a key exists
     in multiple sources, the value associated with the last source will take
     precedence. Values defined by an Env with a duplicate key will take
     precedence. Cannot be updated.

   image	<string>
     Docker image name. More info:
     https://kubernetes.io/docs/concepts/containers/images This field is
     optional to allow higher level config management to default or override
     container images in workload controllers like Deployments and StatefulSets.

   imagePullPolicy	<string>
     Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always
     if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated.
     More info:
     https://kubernetes.io/docs/concepts/containers/images#updating-images

   lifecycle	<Object>
     Actions that the management system should take in response to container
     lifecycle events. Cannot be updated.

   livenessProbe	<Object>
     Periodic probe of container liveness. Container will be restarted if the
     probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   name	<string> -required-
     Name of the container specified as a DNS_LABEL. Each container in a pod
     must have a unique name (DNS_LABEL). Cannot be updated.

   ports	<[]Object>
     List of ports to expose from the container. Exposing a port here gives the
     system additional information about the network connections a container
     uses, but is primarily informational. Not specifying a port here DOES NOT
     prevent that port from being exposed. Any port which is listening on the
     default "0.0.0.0" address inside a container will be accessible from the
     network. Cannot be updated.

   readinessProbe	<Object>
     Periodic probe of container service readiness. Container will be removed
     from service endpoints if the probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   resources	<Object>
     Compute Resources required by this container. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

   securityContext	<Object>
     Security options the pod should run with. More info:
     https://kubernetes.io/docs/concepts/policy/security-context/ More info:
     https://kubernetes.io/docs/tasks/configure-pod-container/security-context/

   stdin	<boolean>
     Whether this container should allocate a buffer for stdin in the container
     runtime. If this is not set, reads from stdin in the container will always
     result in EOF. Default is false.

   stdinOnce	<boolean>
     Whether the container runtime should close the stdin channel after it has
     been opened by a single attach. When stdin is true the stdin stream will
     remain open across multiple attach sessions. If stdinOnce is set to true,
     stdin is opened on container start, is empty until the first client
     attaches to stdin, and then remains open and accepts data until the client
     disconnects, at which time stdin is closed and remains closed until the
     container is restarted. If this flag is false, a container processes that
     reads from stdin will never receive an EOF. Default is false

   terminationMessagePath	<string>
     Optional: Path at which the file to which the container's termination
     message will be written is mounted into the container's filesystem. Message
     written is intended to be brief final status, such as an assertion failure
     message. Will be truncated by the node if greater than 4096 bytes. The
     total message length across all containers will be limited to 12kb.
     Defaults to /dev/termination-log. Cannot be updated.

   terminationMessagePolicy	<string>
     Indicate how the termination message should be populated. File will use the
     contents of terminationMessagePath to populate the container status message
     on both success and failure. FallbackToLogsOnError will use the last chunk
     of container log output if the termination message file is empty and the
     container exited with an error. The log output is limited to 2048 bytes or
     80 lines, whichever is smaller. Defaults to File. Cannot be updated.

   tty	<boolean>
     Whether this container should allocate a TTY for itself, also requires
     'stdin' to be true. Default is false.

   volumeDevices	<[]Object>
     volumeDevices is the list of block devices to be used by the container.
     This is an alpha feature and may change in the future.

   volumeMounts	<[]Object>
     Pod volumes to mount into the container's filesystem. Cannot be updated.

   workingDir	<string>
     Container's working directory. If not specified, the container runtime's
     default will be used, which might be configured in the container image.
     Cannot be updated.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值