2023年6月30日发(作者:)
Kubernetes中yaml⽂件Pod模板详解编写yaml⽂件启动服务编写Kubernetes中编写yaml⽂件,Pod模板详解K8s的yaml⽂件功能⼗分强⼤,对于新⼿来说,想要快速照掌握且灵活运⽤就显得有些困难。下⽂将给出Pod模板常⽤的⼀些代码及解释,如何快速运⽤。Pod中 yaml 的详解注意:都是以两个空格为递进,⽽⾮tabapiVersion: v1 #必选,版本号,例如v1kind: Pod #必选,资源类型,例如 Pod,Deployment,ReplicaSet,Replicationmetadata: #必选,元数据 name: string #必选,Pod名称 namespace: string #Pod所属的命名空间,默认为"default" labels: #⾃定义标签列表 - name: string
spec: #必选,Pod中容器的详细定义 containers: #必选,Pod中容器列表 - name: string #必选,容器名称 image: string #必选,容器的镜像名称 imagePullPolicy: [ Always|Never|IfNotPresent ] #获取镜像的策略
command:
args:
#容器的启动命令列表,如不指定,使⽤打包时使⽤的启动命令 #容器的启动命令参数列表 workingDir: string #容器的⼯作⽬录 volumeMounts: #挂载到容器内部的存储卷配置 - name: string #引⽤pod定义的共享存储卷的名称,需⽤volumes[]部分定义的的卷名 mountPath: string #存储卷在容器内mount的绝对路径,应少于512字符 readOnly: boolean #是否为只读模式
volumes: #在该pod上定义共享存储卷列表 - name: string #共享存储卷名称
(volumes类型有很多种) emptyDir: {} #类型为emtyDir的存储卷,与Pod同⽣命周期的⼀个临时⽬录。为空值 hostPath: string #类型为hostPath的存储卷,表⽰挂载Pod所在宿主机的⽬录 path: string #Pod所在宿主机的⽬录,将被⽤于同期中mount的⽬录 secret: #类型为secret的存储卷,挂载集群与定义的secret对象到容器内部 scretname: string
items:
- key: string path: string configMap: #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部 name: string items: - key: string path: string
ports: #需要暴露的端⼝库号列表 - name: string #端⼝的名称 containerPort: int #容器需要监听的端⼝号 hostPort: int #容器所在主机需要监听的端⼝号,默认与Container相同 protocol: string #端⼝协议,⽀持TCP和UDP,默认TCP
env: #容器运⾏前需设置的环境变量列表 - name: string #环境变量名称 value: string #环境变量的值
resources: #资源限制和请求的设置 limits: #资源限制的设置 cpu: string #Cpu的限制,单位为core数,将⽤于docker run --cpu-shares参数 memory: string #内存限制,单位可以为Mib/Gib,将⽤于docker run --memory参数 requests: #资源请求的设置 cpu: string #Cpu请求,容器启动的初始可⽤数量 memory: string #内存请求,容器启动的初始可⽤数量
lifecycle: #⽣命周期钩⼦ postStart: #容器启动后⽴即执⾏此钩⼦,如果执⾏失败,会根据重启策略进⾏重启 preStop: #容器终⽌前执⾏此钩⼦,⽆论结果如何,容器都会终⽌
livenessProbe: #对Pod内各容器健康检查的设置,当探测⽆响应⼏次后将⾃动重启该容器 exec: #对Pod容器内检查⽅式设置为exec⽅式 command:
initialDelaySeconds #
容器启动后等待多少秒执⾏第⼀次探测 timeoutSeconds #
探测超时时间。默认1秒,最⼩1秒 periodSeconds #
执⾏探测的频率。默认是10秒,最⼩1秒 failureThreshold #
连续探测失败多少次才被认定为失败。默认是3。最⼩值是1 successThreshold #
连续探测成功多少次才被认定为成功。默认是1
httpGet: #对Pod内个容器健康检查⽅法设置为HttpGet,需要制定Path、port path: string port: number host: string scheme: string HttpHeaders: - name: string value: string
tcpSocket: #对Pod内个容器健康检查⽅式设置为tcpSocket⽅式 port: number initialDelaySeconds: 0 #容器启动完成后⾸次探测的时间,单位为秒 timeoutSeconds: 0 #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒 periodSeconds: 0 #对容器监控检查的定期探测时间设置,单位秒,默认10秒⼀次 successThreshold: 0 failureThreshold: 0 securityContext: privileged: false restartPolicy: #Pod的重启策略 nodeName: #设置NodeName表⽰将该Pod调度到指定到名称的node节点上 nodeSelector: obeject #设置NodeSelector表⽰将该Pod调度到包含这个label的node上 imagePullSecrets: #Pull镜像时使⽤的secret名称,以key:secretkey格式指定 - name: string hostNetwork: false #是否使⽤主机⽹络模式,默认为false,如果设置为true,表⽰使⽤宿主机⽹络 #exec⽅式需要制定的命令或脚本在编写yaml的时候,可结合帮助,灵活运⽤,找到所需的那个代码。k8s查看yaml⽂件帮助的命令构建pod,ns,rs,rc等等,只需在后⾯加上即可出现对应模板kubectl explain pod/ns/rs/rc/networkpolicy/hpa以pod为例以pod为例[root@master ~]# kubectl explain podKIND: PodVERSION: v1DESCRIPTION: Pod is a collection of containers that can run on a host. This resource is created by clients and scheduled onto : apiVersion 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: /community/contributors/devel/sig-architecture/#resources kind 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: /community/contributors/devel/sig-architecture/#types-kinds metadata Standard object's metadata. More info: /community/contributors/devel/sig-architecture/#metadata spec Specification of the desired behavior of the pod. More info: /community/contributors/devel/sig-architecture/#spec-and-status status Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: /community/contributors/devel/sig-architecture/#spec-and-status逐层往下查看以pod中的spec为例它会给出spec下的所有可写的代码,可以 . 为分隔符依此往下查阅# kubectl explain ND: PodVERSION: v1RESOURCE: spec DESCRIPTION: Specification of the desired behavior of the pod. More info: /community/contributors/devel/sig-architecture/#spec-and-status PodSpec is a description of a : activeDeadlineSeconds Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer. affinity If specified, the pod's scheduling constraints automountServiceAccountToken AutomountServiceAccountToken indicates whether a service account token should be automatically mounted. containers <[]Object> -required- containers <[]Object> -required- 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. dnsConfig Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy. dnsPolicy Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'. enableServiceLinks EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true. ephemeralContainers <[]Object> List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource. This field is alpha-level and is only honored by servers that enable the EphemeralContainers feature. hostAliases <[]Object> HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods. hostIPC Use the host's ipc namespace. Optional: Default to false. hostNetwork Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false. hostPID Use the host's pid namespace. Optional: Default to false. hostname Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value. imagePullSecrets <[]Object> ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: /docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod initContainers <[]Object> List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: /docs/concepts/workloads/pods/init-containers/ /docs/concepts/workloads/pods/init-containers/ nodeName NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements. nodeSelector NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: /docs/concepts/configuration/assign-pod-node/ overhead Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: /enhancements/keps/sig-node/ This field is alpha-level as of Kubernetes v1.16, and is only honored by servers that enable the PodOverhead feature. preemptionPolicy PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. This field is alpha-level and is only honored by servers that enable the NonPreemptingPriority feature. priority The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. priorityClassName If specified, indicates the pod's priority. "system-node-critical" and "system-cluster-critical" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default. readinessGates <[]Object> If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to "True" More info: /enhancements/keps/sig-network/0007-pod-ready%2B% restartPolicy Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: /docs/concepts/workloads/pods/pod-lifecycle/#restart-policy runtimeClassName RuntimeClassName refers to a RuntimeClass object in the group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: /enhancements/keps/sig-node/ This is a beta feature as of Kubernetes v1.14. schedulerName If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler. securityContext SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. serviceAccount DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead. serviceAccountName ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: /docs/tasks/configure-pod-container/configure-service-account/ shareProcessNamespace Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false. subdomain If specified, the fully qualified Pod hostname will be "...svc.". If not specified, the pod will not have a domainname at all. terminationGracePeriodSeconds Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds. tolerations <[]Object> If specified, the pod's tolerations. topologySpreadConstraints <[]Object> TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. This field is only honored by clusters that enable the EvenPodsSpread feature. All topologySpreadConstraints are ANDed. volumes <[]Object> List of volumes that can be mounted by containers belonging to the pod. More info: /docs/concepts/storage/volumes例1yaml中的实战pod案例,先写个简单的使⽤该yaml⽂件创建Pod要求如下:名称:nginx-pod;2.使⽤:nginx 镜像;3.拉取策略为:IfNotPresent;4.容器名称:mynginx;5.容器端⼝:80其yaml⽂件如下[root@master ~]# vim
apiVersion: v1 #版本号为v1kind: Pod #资源类型为Podmetadata: #元数据 name: nginx-pod #Pod名称spec: #pod容器的详细定义 containers: #容器列表 - name: mynginx #容器名称 image: nginx:latest #容器镜像 imagePullPolicy: IfNotPresent #容器镜像拉取策略 ports: #需要暴露的端⼝库号列表 - containerPort: 80 #容器需监听的端⼝号将其启动,且访问⼀下,试看是否能够访问到nginx⾸页启动编写好的yaml⽂件# kubectl apply -f
pod/nginx-pod created查看pod列表# kubectl get pod -o wideNAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATESnginx-pod 1/1 Running 0 28s 10.244.1.21 node 访问pod# curl 10.244.1.21:80Welcome to nginx! Welcome to nginx! If you see this page, the nginx web server is successfully installed andworking. Further configuration is required.
For online documentation and support please refer to . Commercial support is available at .
Thank you for using nginx.
可见是能够启动成功且可以访问到nginx⾸页例2上点难度吧,写个常⽤⼀点的实战案例:名称:liveness-exec;2.命名空间:default;3.镜像: busybox;容器名称: liveness;4.容器启动时运⾏命令 “touch /tmp/healthy; sleep 60; rm -rf /tmp/healthy; sleep 600”,此命令在容器启动时创建/tmp/healthy ⽂件,并于60秒之后将其删除;5.存活性探针运⾏“test -e /tmp/healthy”命令检查⽂件的存在性,若⽂件存在则返回状态码为0,表⽰成功通过测试;6.启动后延时5秒开始运⾏检测;7.每隔5秒执⾏⼀次liveness probe;其yaml的编写如下:[root@master ~]# vim liveness_
apiVersion: v1 #版本号为v1kind: Pod #资源类型为Podmetadata: #元数据必写 name: liveness-exec #pod名称为liveness-execspec: #容器的详细定义
必写 containers: #容器列表
必写 - name: liveness #容器名称为 liveness image: busybox:latest #容器所使⽤的镜像 busybox args: #容器的启动命令参数列表
必写 - /bin/sh #所要执⾏的命令 - -c - touch /tmp/healthy; sleep 60; rm -rf /tmp/healthy; sleep 600 livenessProbe: #Pod内各容器健康检查的设置 exec: #对Pod容器内检查⽅式设置为exec⽅式 command: #exec⽅式需要制定的命令或脚本 - test - /tmp/healthy initialDelaySeconds: 5 #容器启动后等待5秒执⾏第⼀次探测 periodSeconds: 5 #执⾏探测的频率每5秒执⾏⼀次[root@master ~]# kubectl apply -f liveness_
pod/liveness-exec created[root@master ~]# kubectl get pod -o wideNAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATESliveness-exec 1/1 Running 0 18s 10.244.1.23 node 当pod创建成功以后进⼊pod查看是否命令是否有被执⾏[root@master ~]# kubectl exec -it liveness-exec /bin/shkubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead./ # ls /tmp/healthy/ #
可见 healthy ⽂件创建成功,可等待60秒,再次查看,会发现这个⽂件已经被删除了,已达到上述的要求。再例举⼀个RS的例⼦:使⽤yaml⽂件创建ReplicaSet 要求如下:(1)Replicaset名称:nginx;(2)命名空间:default;(3)副本数:3;(4)镜像:nginx。可借⽤yaml⽂件的帮助:# kubectl explain ND: ReplicaSetVERSION: apps/v1RESOURCE: spec DESCRIPTION: Spec defines the specification of the desired behavior of the ReplicaSet. More info: /community/contributors/devel/sig-architecture/#spec-and-status ReplicaSetSpec is the specification of a : minReadySeconds Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready) replicas Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: /docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller selector -required- Selector is a label query over pods that should match the replica count. Label keys and values that must match in order to be controlled by this replica set. It must match the pod template's labels. More info: /docs/concepts/overview/working-with-objects/labels/#label-selectors template Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: /docs/concepts/workloads/controllers/replicationcontroller#pod-template编写rs的yaml⽂件[root@master ~]# vim
apiVersion: apps/v1kind: ReplicaSetmetadata: name: nginxspec: replicas: 3 selector: matchLabels: nginx: replicaset template: metadata: labels: nginx: replicaset spec: containers: - name: nginx image: nginx:latest将其启动# kubectl apply -f
/nginx created# kubectl get rsNAME DESIRED CURRENT READY AGEnginx 3 3 3 69s# kubectl get pod -o wideNAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATESnginx-qjq88 1/1 Running 0 38s 10.244.1.25 node nginx-xkxvz 1/1 Running 0 38s 10.244.1.24 node nginx-z8gwx 1/1 Running 0 38s 10.244.0.28 master 访问任意⼀个IP,都能返回nginx⾸页内容[root@master ~]# curl 10.244.0.28Welcome to nginx!If you see this page, the nginx web server is successfully installed and working. Further configuration is online documentation and support please refer to .Commercial support is available at .Thank you for using nginx.到此over!!
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688057377a72463.html
评论列表(0条)