K8s之YAML文件

Kubernetes支持YAML和JSON格式创建资源对象

1,JSON格式用于接口之间消息的传递
2,YAML格式用于配置和管理
3,YAML是一种简洁的非标记性语言

语法格式:

缩进标识层级关系
不支持制表符(tab)缩进,使用空格缩进
通常开头缩进两个空格
字符后缩进一个空格,如冒号,逗号等
“---”表示YAML格式,一个文件的开始
“#”表示注释


`查看应用名称`
[[email protected] ~]# 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

[[email protected] ~]# mkdir demo
[[email protected] ~]# cd demo/
[[email protected] demo]# vim nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.15.4
        ports:
        - containerPort: 80

#插入内容后按Esc退出插入模式,输入:wq保存退出
[[email protected] demo]# kubectl create -f my-nginx.yaml
deployment.apps/my-nginx created

[[email protected] demo]# kubectl get pods
NAME                                READY   STATUS    RESTARTS   AGE
`my-nginx-d55b94fd-kc2gl             1/1     Running   0          47s`
`my-nginx-d55b94fd-tkr42             1/1     Running   0          47s`
nginx-6c94d899fd-8pf48              1/1     Running   0          23h
nginx-deployment-5477945587-f5dsm   1/1     Running   0          22h
nginx-deployment-5477945587-hmgd2   1/1     Running   0          22h
nginx-deployment-5477945587-pl2hn   1/1     Running   0          22h

[[email protected] demo]# vim my-nginx-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-nginx-service
  labels:
    app: nginx
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
  selector:
    app: nginx
#插入内容后按Esc退出插入模式,输入:wq保存退出

[[email protected] demo]# kubectl create -f my-nginx-service.yaml
service/my-nginx-service created

`查看服务`
[[email protected] demo]# kubectl get svc
NAME               TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes         ClusterIP   10.0.0.1     <none>        443/TCP        8d
`my-nginx-service   NodePort    10.0.0.210   <none>        80:40377/TCP   20s`
nginx-service      NodePort    10.0.0.242   <none>        80:40422/TCP   33h

1.自动测试命令的正确性,并不执行创建:

[[email protected] demo]# kubectl run my-nginx --image=nginx --port=80 --replicas=2 --dry-run
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/my-nginx created (dry run)

2.查看生成yaml格式:

[[email protected] demo]# kubectl run my-nginx --image=nginx --port=80 --replicas=2 --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: my-nginx
  name: my-nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      run: my-nginx
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: my-nginx
    spec:
      containers:
      - image: nginx
        name: my-nginx
        ports:
        - containerPort: 80
        resources: {}
status: {}

3.生成yaml模板文件:

[[email protected] demo]# kubectl run my-nginx --image=nginx --port=80 --replicas=2 --dry-run -o yaml > nginx-deploy.yaml
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.

4.导出json格式文件:

[[email protected] demo]# kubectl run my-nginx --image=nginx --port=80 --replicas=2 --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": "my-nginx",
        "creationTimestamp": null,
        "labels": {
            "run": "my-nginx"
        }
    },
    "spec": {
        "replicas": 2,
        "selector": {
            "matchLabels": {
                "run": "my-nginx"
            }
        },
        "template": {
            "metadata": {
                "creationTimestamp": null,
                "labels": {
                    "run": "my-nginx"
                }
            },
            "spec": {
                "containers": [
                    {
                        "name": "my-nginx",
                        "image": "nginx",
                        "ports": [
                            {
                                "containerPort": 80
                            }
                        ],
                        "resources": {}
                    }
                ]
            }
        },
        "strategy": {}
    },
    "status": {}
}

5.将现有的资源生成模板导出:

[[email protected] demo]# kubectl get deploy/nginx --export -o yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "2"
  creationTimestamp: null
  generation: 1
  labels:
    run: nginx
  name: nginx
  selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/nginx
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      run: nginx
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx
    spec:
      containers:
      - image: nginx:1.14
        imagePullPolicy: Always
        name: nginx
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status: {}

6.保存到文件中:

[[email protected] demo]# kubectl get deploy/nginx --export -o yaml > my-deploy.yaml

7.查看字段帮助信息:

[[email protected] demo]# 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.

原文地址:https://blog.51cto.com/14464303/2470952

时间: 2024-10-09 10:55:51

K8s之YAML文件的相关文章

k8s之yaml文件基本格式及底层负载均衡实现原理

本文只是自己的精简后的总结,若需要详细的资料,请绕步. 注:yaml文件严格要求缩进,默认不同层次等级是两个空格的缩进. 1.使用httpd镜像创建一个Deployment资源对象 [[email protected] ~]# vim lvjianzhao.yaml #编写yaml文件 kind: Deployment #指定要创建的资源对象类型 apiVersion: extensions/v1beta1 #指定deployment所对应的API版本 metadata: name: lvjia

.net core i上 K8S(三)Yaml文件运行.netcore程序

上一章我们通过kubectl run简单运行了一个.netcore网站,但实际的开发中,我们都是通过yaml来实现的. 1.编写yaml文件 关于yaml文件的格式在此就不多描述了,不熟悉的可以去网上搜一下示例. apiVersion: apps/v1beta2 #指定版本,支持的版本可以通过kubectl api-versions查询 kind: Deployment #指定类型,这一次我们要创建一个Deployment metadata: #元数据 name: cys-netcore #de

k8s的yaml文件配置详解(转))

来源:https://www.cnblogs.com/arrow-kejin/p/10058758.html 1 apiVersion: v1 #指定api版本,此值必须在kubectl apiversion中 2 kind: Pod #指定创建资源的角色/类型 3 metadata: #资源的元数据/属性 4 name: django-pod #资源的名字,在同一个namespace中必须唯一 5 labels: #设定资源的标签,使这个标签在service网络中备案,以便被获知 6 k8s-

k8s yaml文件说明

nginx yaml文件说明 --- #定义nginx命名空间 apiVersion: v1 kind: Namespace metadata: name: k8s-nginx #自定义的命名空间 --- #定义nginx service apiVersion: v1 kind: Service metadata: name: k8s-nginx namespace: k8s-nginx labels: app: k8s-nginx spec: type: NodePort ports: - p

Kubernetes之yaml文件详解-v1.15.x

Kubernetes之yaml文件详解 K8S 创建资源的方式 K8S有两种创建资源的方式:kubectl 命令和 yaml 配置文件. kubectl命令行:最为简单,一条命令就OK,但缺点也很明显,你并不知道这条命令背后到底做了哪些事!yaml配置文件:提供了一种让你知其然更知其所以然的方式.优势如下: 完整性:配置文件描述了一个资源的完整状态,可以很清楚地知道一个资源的创建背后究竟做了哪些事:灵活性:配置文件可以创建比命令行更复杂的结构:可维护性:配置文件提供了创建资源对象的模板,能够重复

K8s使用YAML文件创建资源

由于K8s技术的火爆,导致现在大大小小的企业都在使用,虽然没有普及,但本人相信时迟早的事情,所以抓紧时间多学习一下吧! 在K8s中创建资源的方式有两种:命令行和YAML文件,本次博文主要介绍使用YAML文件的方式,如需使用命令行创建资源请参考K8s资源对象的基本管理 Kubernetes中的YAML文件与配置清单是一样的,根据个人习惯.本次博文统称为YAML文件! 一.YAML文件基础 YAML是专门用来配置文件的语言,非常简洁和强大.与了解的properties.XML.json等数据格式,习

python解析yaml文件

YAML语法规则: http://www.ibm.com/developerworks/cn/xml/x-cn-yamlintro/ 下载PyYAML: http://www.yaml.org/ 解压安装: python setup.py install 1.新建test.yaml文件,内容如下: name: Tom Smith age: 37 spouse: name: Jane Smith age: 25 children: - name: Jimmy Smith age: 15 - nam

Python读取Yaml文件

近期看到好多使用Yaml文件做为配置文件或者数据文件的工程,随即也研究了下,发现Yaml有几个优点:可读性好.和脚本语言的交互性好(确实非常好).使用实现语言的数据类型.有一个一致的数据模型.易于实现. 既然有这么多好处,为什么不用呢,随后开始研究在Python中怎么读取Yaml文件,下面我们来看下: 1.首先需要下载Python的yaml库PyYAML,下载地址:http://pyyaml.org/,安装过程就省略...... 2.建立一个.py文件 3.import yaml 4.f = o

OPENCV(3) &mdash;&mdash; 对XML和YAML文件实现I/O 操作

XML\YAML文件在OpenCV中的数据结构为FileStorage string filename = "I.xml"; FileStorage fs(filename, FileStorage::WRITE); \\... fs.open(filename, FileStorage::READ); fs.release();   写入文件使用  <<  运算符 ,读取文件,使用 >> 运算符 fs << "iterationNr&qu