分享交流
合作共赢!

Kubernetes/K8S基础使用方法总结【三】——用yaml配置清单创建资源

一、简述

由于apiserver仅接收JSON格式的资源定义格式,所以使用kubectl run命令或者yaml文件创建资源的形式会都被自动转为JSON格式的文件,然后提交执行。用yaml文件创建资源,配置清单一般包括apiVersion, kind, matadata, spec, status最基本的五种资源清单,如下所示:

[root@master1 ~]# kubectl explain pods
KIND: Pod
VERSION: v1

DESCRIPTION:
Pod is a collection of containers that can run on a host. This resource is
created by clients and scheduled onto hosts.

FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representation of an
object. Servers should convert recognized schemas to the latest internal
value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

kind <string>
Kind is a string value representing the REST resource this object
represents. Servers may infer this from the endpoint the client submits
requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

metadata <Object>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

spec <Object>
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

status <Object>
Most recently observed status of the pod. This data may not be up to date.
Populated by the system. Read-only. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

1.apiVersion

kubectl api-versions: 显示所有支持的群组

[root@master1 ~]# kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
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/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1  # 核心群组

2.kind

常用资源类别:workload, Pod, ReplicaSet, Deployment, StatefulSet, DaemonSet, Job, Cronjob等。

查看所有资源api-resources

[root@master1 ~]# kubectl api-resources
NAME                              SHORTNAMES   APIGROUP                       NAMESPACED   KIND
bindings                                                                      true         Binding
componentstatuses                 cs                                          false        ComponentStatus
configmaps                        cm                                          true         ConfigMap
endpoints                         ep                                          true         Endpoints
events                            ev                                          true         Event
limitranges                       limits                                      true         LimitRange
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumeclaims            pvc                                         true         PersistentVolumeClaim
persistentvolumes                 pv                                          false        PersistentVolume
pods                              po                                          true         Pod
podtemplates                                                                  true         PodTemplate
replicationcontrollers            rc                                          true         ReplicationController
resourcequotas                    quota                                       true         ResourceQuota
secrets                                                                       true         Secret
serviceaccounts                   sa                                          true         ServiceAccount
services                          svc                                         true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
controllerrevisions                            apps                           true         ControllerRevision
daemonsets                        ds           apps                           true         DaemonSet
deployments                       deploy       apps                           true         Deployment
replicasets                       rs           apps                           true         ReplicaSet
statefulsets                      sts          apps                           true         StatefulSet
tokenreviews                                   authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch                          true         CronJob
jobs                                           batch                          true         Job
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
leases                                         coordination.k8s.io            true         Lease
endpointslices                                 discovery.k8s.io               true         EndpointSlice
events                            ev           events.k8s.io                  true         Event
ingresses                         ing          extensions                     true         Ingress
ingressclasses                                 networking.k8s.io              false        IngressClass
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
poddisruptionbudgets              pdb          policy                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io      true         RoleBinding
roles                                          rbac.authorization.k8s.io      true         Role
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment

3.metadata

  • name: 名称
  • namespace: 名称空间
  • labels: 资源标签
  • annotations:
  • 每个资源可以通过路径PATH被引用:/aip/GROUP/NAME/namespaces/NAMESPACE/TYPE/NAME

4.spec

  • disired定义用户期望的状态信息
  • status: 当前状态,current state, 本字段由kubernetes集群维护

重要:kubectl explain <object>: 查看官方object资源对象定义介绍,通过在此命令后面添加”.<object>“可以查看二级和三级等子对象的使用说明。

5.status

由系统自动生成,只读形式显示最近状态。

二、yaml配置文件常用选项

spec的基本选项:

spec:
  containers:
    name
    image
    imagePullPolicy: Always, Never, IfNotPresent
    ports:
      name
      containerPort
    livenessProbe
    readnessProbe
    lifecycle
  ExecAction: exec
  TCPSocketAction: tcpSocket
  HTTPGetAction: httpGet

spec除基本选项外,常用的资源配置选项还有:

containers <[]Object> -required: 定义此pod的容器的列表,至少一个,其子选项主要包含name, image, imagePullPolicy(Always, Never, IfNotPresent), ports(子选项: name, containerPort)等。

nodeSelector <map[string]string>:节点标签选择器,让资源固定运行在一类匹配到的标签的node上面;

nodeName <string>: 指定node名称,让资源固定运行在某个node上面

annotations: 与label不同之处在于,其不能用于筛选资源对象,仅用于为对象提供”源数据”。

restartPolicy <string>: 容器重启策略,可选值:Always,OnFailure,Never,默认值是Always;

livenessProbe <Object>: 监控容器是否是运行状态,或叫监测探针;

readinessProbe <Object>: 监控进程是否能提供服务;

探针类型:ExecAction、TCPSocketAction、HTTPGetAction

lifecycle: 指定在pod开始前(postStart)和结束后(preStop)所指定的命令;

imagePullSecrets <[]Object>: pod中的image从私有仓库拉取镜像时需要输入用户名密码,可以设置此参数;

除此以外,serviceaccount选项也可以起到此作用,如下的Image pull secrets可以进行配置(创建的secret对象直接定义到sa,然后将sa定义到pod上面,防止在pod资源中泄露账户信息);

[root@master1 volumes]# kubectl describe sa admin
Name: admin
Namespace: default
Labels: <none>
Annotations: <none>
Image pull secrets: <none>
Mountable secrets: admin-token-xrz4c
Tokens: admin-token-xrz4c
Events: <none>

三、根据yaml管理资源

1.创建资源

根据上面yaml编写说明写好yaml文件后,即可开始创建应用,命令如下:

kubectl create -f podname.yaml
  # -f, --filename=[]: Filename, directory, or URL to files to use to create the resource

2.删除资源

kubectl delete -f podname.yaml

四、重要说明

通过以上yaml配置清单创建的资源(pod),删除之后不会自动重建,可以称之为命令式yaml清单,或自主式命令清单或自主式pod资源,即删除资源后系统会自动生成自定义数量的资源。不过用pod控制器创建的pod资源删除后会自动重建,参考:Kubernetes/K8S基础使用方法总结【四】——Pod控制器

赞(1) 打赏
未经允许不得转载:琼杰笔记 » Kubernetes/K8S基础使用方法总结【三】——用yaml配置清单创建资源

评论 抢沙发

评论前必须登录!

 

分享交流,合作共赢!

联系我们加入QQ群

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏