RESTful
.GET,PUT,DELETE,POST,.... 完成操作
.kubectl run,get,edit,...
资源:对象
workload:Pod,ReplicaSet,Deployment,StatefulSet,DaemonSet,Job,Cronjob,...
服务发现及负载均衡:Service,Ingress,...
配置与存储:Volume,CSI
ConfigMap,Secret
DownwardAPI
集群级别资源
Namespace,Node,Role,Cluster,RoleBinding,ClusterRoleBinding
元数据型资源
HPA,PodTemplate,LimitRange
kubectl get pod nginx-7849c4bbcd-dscjr -o yaml 这里输出位yaml格式
创建资源的方法:
apiserver仅接收JSON格式的资源定义;
yaml格式提供配置清单,apiserver自动将其转换为json格式,而后再提交;
大部分资源配置清单组成:
apiVersion:group/version
kubectl api-versions
kind:资源类别
metadata:元数据
name
namespaces
labels 键值数据,每种资源都可以使用
annotations
每个资源的引用路径PATH
/api/GROUP/VERSION/namespace/NAMESPACE/TYPE/NAME
/api/v1/namespaces/default/pods/nginx-7849c4bbcd-dscjr
spec:期望状态,disired state
不同资源各不相同
status:当前状态current state,本字段由kubenetes集群维护。
下面的命令查看资源定义
kubectl explain pods
kubectl explain pods.metadata
kubectl explain pods.spec
kubectl explain pods.spec.containers
kubectl explain pods.spec.containers.livenessProbe
下面开始定义最基本的资源
mkdir manifests
cd manifests
vim pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-demo
namespace: default
labels:
app: myapp
tier: frontend
spec:
containers:
- name: myapp
image: nginx:1.14-alpine
- name: apache
image: httpd:2.4
command:
- "/bin/sh"
- "-c"
- "date > /usr/share/nginx/html/index.html; sleep 5"
[root@master manifests]# kubectl create -f pod-demo.yaml
pod/pod-demo created
[root@master manifests]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-7849c4bbcd-dscjr 1/1 Running 0 46h
nginx-7849c4bbcd-vdd45 1/1 Running 0 46h
nginx-7849c4bbcd-wrvks 1/1 Running 0 46h
nginx-deploy-84cbfc56b6-mjcw5 1/1 Running 0 2d
pod-demo 2/2 Running 1 11s
[root@master manifests]# kubectl describe pods pod-demo
Name: pod-demo
Namespace: default
Priority: 0
PriorityClassName: <none>
Node: node02/10.249.6.102
Start Time: Sun, 03 Mar 2019 10:48:45 -0500
Labels: app=myapp
tier=frontend
Annotations: <none>
Status: Running
IP: 10.244.2.16
Containers:
myapp:
Container ID: docker://2fef9be71b712596da67c9514f7f8a9742e17ae8b75424f24d4377b5a4c76c39
Image: nginx:1.14-alpine
Image ID: docker-pullable://nginx@sha256:b96aeeb1687703c49096f4969358d44f8520b671da94848309a3ba5be5b4c632
Port: <none>
Host Port: <none>
State: Running
Started: Sun, 03 Mar 2019 10:48:46 -0500
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-6q28w (ro)
apache:
Container ID: docker://cd7fd89398cca5d6e0daf7124fdcc156cc726172c6302fc9bd0e2aa4d51bb18d
Image: httpd:2.4
Image ID: docker-pullable://httpd@sha256:5e7992fcdaa214d5e88c4dfde274befe60d5d5b232717862856012bf5ce31086
Port: <none>
Host Port: <none>
Command:
/bin/sh
-c
sleep 3600
State: Running
Started: Sun, 03 Mar 2019 10:48:52 -0500
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-6q28w (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-6q28w:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-6q28w
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 37s default-scheduler Successfully assigned default/pod-demo to node02
Normal Pulled 36s kubelet, node02 Container image "nginx:1.14-alpine" already present on machine
Normal Created 36s kubelet, node02 Created container
Normal Started 36s kubelet, node02 Started container
Normal Pulling 36s kubelet, node02 pulling image "httpd:2.4"
Normal Pulled 30s kubelet, node02 Successfully pulled image "httpd:2.4"
Normal Created 30s kubelet, node02 Created container
Normal Started 30s kubelet, node02 Started container
直接删除文件也一样删除容器
kubectl delete -f pod-demo.yaml
======================================================
[root@master ~]# kubectl get pod,svc
NAME READY STATUS RESTARTS AGE
pod/nginx-7849c4bbcd-dscjr 1/1 Running 0 43h
pod/nginx-7849c4bbcd-vdd45 1/1 Running 0 43h
pod/nginx-7849c4bbcd-wrvks 1/1 Running 0 43h
pod/nginx-deploy-84cbfc56b6-mjcw5 1/1 Running 0 45h
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3d1h
service/nginx-deploy ClusterIP 10.100.251.191 <none> 80/TCP 2d20h
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-7849c4bbcd-dscjr 1/1 Running 0 44h
nginx-7849c4bbcd-vdd45 1/1 Running 0 44h
nginx-7849c4bbcd-wrvks 1/1 Running 0 44h
nginx-deploy-84cbfc56b6-mjcw5 1/1 Running 0 45h
[root@master ~]# kubectl get pod nginx-7849c4bbcd-dscjr
NAME READY STATUS RESTARTS AGE
nginx-7849c4bbcd-dscjr 1/1 Running 0 44h
[root@master ~]# kubectl get pod nginx-7849c4bbcd-dscjr -o yaml 这里输出位yaml格式
apiVersion: v1
kind: Pod workload
metadata: 元数据
creationTimestamp: "2019-03-01T16:47:01Z"
generateName: nginx-7849c4bbcd-
labels:
pod-template-hash: 7849c4bbcd
run: nginx
name: nginx-7849c4bbcd-dscjr
namespace: default
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet
name: nginx-7849c4bbcd
uid: 116ab716-3c3d-11e9-a704-a0369f95b76e
resourceVersion: "150656"
selfLink: /api/v1/namespaces/default/pods/nginx-7849c4bbcd-dscjr
uid: a2f6ac10-3c41-11e9-a704-a0369f95b76e
spec: 用户定义资源目标状态
containers:
- image: nginx:1.14-alpine
imagePullPolicy: IfNotPresent
name: nginx
ports:
- containerPort: 80
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-6q28w
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node01
priority: 0
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
tolerations:
- effect: NoExecute
key: node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds: 300
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds: 300
volumes:
- name: default-token-6q28w
secret:
defaultMode: 420
secretName: default-token-6q28w
status: 当前状态
conditions:
- lastProbeTime: null
lastTransitionTime: "2019-03-01T16:47:01Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2019-03-01T16:47:02Z"
status: "True"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2019-03-01T16:47:02Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2019-03-01T16:47:01Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: docker://6d095904f8259b1bd458030c67c295bb46600a09a69ec97eaa502241f95ee31a
image: nginx:1.14-alpine
imageID: docker-pullable://nginx@sha256:b96aeeb1687703c49096f4969358d44f8520b671da94848309a3ba5be5b4c632
lastState: {}
name: nginx
ready: true
restartCount: 0
state:
running:
startedAt: "2019-03-01T16:47:02Z"
hostIP: 10.249.6.101
phase: Running
podIP: 10.244.1.13
qosClass: BestEffort
startTime: "2019-03-01T16:47:01Z"
========================================
[root@master ~]# kubectl explain pod
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/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/api-conventions.md#types-kinds
metadata <Object>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
spec <Object>
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/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/api-conventions.md#spec-and-status
[root@master ~]# kubectl explain pods.metadata
KIND: Pod
VERSION: v1
RESOURCE: metadata <Object>
DESCRIPTION:
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
ObjectMeta is metadata that all persisted resources must have, which
includes all objects users must create.
FIELDS:
annotations <map[string]string>
Annotations is an unstructured key value map stored with a resource that
may be set by external tools to store and retrieve arbitrary metadata. They
are not queryable and should be preserved when modifying objects. More
info: http://kubernetes.io/docs/user-guide/annotations
clusterName <string>
The name of the cluster which the object belongs to. This is used to
distinguish resources with same name and namespace in different clusters.
This field is not set anywhere right now and apiserver is going to ignore
it if set in create or update request.
creationTimestamp <string>
CreationTimestamp is a timestamp representing the server time when this
object was created. It is not guaranteed to be set in happens-before order
across separate operations. Clients may not set this value. It is
represented in RFC3339 form and is in UTC. Populated by the system.
Read-only. Null for lists. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
deletionGracePeriodSeconds <integer>
Number of seconds allowed for this object to gracefully terminate before it
will be removed from the system. Only set when deletionTimestamp is also
set. May only be shortened. Read-only.
deletionTimestamp <string>
DeletionTimestamp is RFC 3339 date and time at which this resource will be
deleted. This field is set by the server when a graceful deletion is
requested by the user, and is not directly settable by a client. The
resource is expected to be deleted (no longer visible from resource lists,
and not reachable by name) after the time in this field, once the
finalizers list is empty. As long as the finalizers list contains items,
deletion is blocked. Once the deletionTimestamp is set, this value may not
be unset or be set further into the future, although it may be shortened or
the resource may be deleted prior to this time. For example, a user may
request that a pod is deleted in 30 seconds. The Kubelet will react by
sending a graceful termination signal to the containers in the pod. After
that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL)
to the container and after cleanup, remove the pod from the API. In the
presence of network partitions, this object may still exist after this
timestamp, until an administrator or automated process can determine the
resource is fully terminated. If not set, graceful deletion of the object
has not been requested. Populated by the system when a graceful deletion is
requested. Read-only. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
finalizers <[]string>
Must be empty before the object is deleted from the registry. Each entry is
an identifier for the responsible component that will remove the entry from
the list. If the deletionTimestamp of the object is non-nil, entries in
this list can only be removed.
generateName <string>
GenerateName is an optional prefix, used by the server, to generate a
unique name ONLY IF the Name field has not been provided. If this field is
used, the name returned to the client will be different than the name
passed. This value will also be combined with a unique suffix. The provided
value has the same validation rules as the Name field, and may be truncated
by the length of the suffix required to make the value unique on the
server. If this field is specified and the generated name exists, the
server will NOT return a 409 - instead, it will either return 201 Created
or 500 with Reason ServerTimeout indicating a unique name could not be
found in the time allotted, and the client should retry (optionally after
the time indicated in the Retry-After header). Applied only if Name is not
specified. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#idempotency
generation <integer>
A sequence number representing a specific generation of the desired state.
Populated by the system. Read-only.
initializers <Object>
An initializer is a controller which enforces some system invariant at
object creation time. This field is a list of initializers that have not
yet acted on this object. If nil or empty, this object has been completely
initialized. Otherwise, the object is considered uninitialized and is
hidden (in list/watch and get calls) from clients that haven't explicitly
asked to observe uninitialized objects. When an object is created, the
system will populate this list with the current set of initializers. Only
privileged users may set or modify this list. Once it is empty, it may not
be modified further by any user.
labels <map[string]string>
Map of string keys and values that can be used to organize and categorize
(scope and select) objects. May match selectors of replication controllers
and services. More info: http://kubernetes.io/docs/user-guide/labels
name <string>
Name must be unique within a namespace. Is required when creating
resources, although some resources may allow a client to request the
generation of an appropriate name automatically. Name is primarily intended
for creation idempotence and configuration definition. Cannot be updated.
More info: http://kubernetes.io/docs/user-guide/identifiers#names
namespace <string>
Namespace defines the space within each name must be unique. An empty
namespace is equivalent to the "default" namespace, but "default" is the
canonical representation. Not all objects are required to be scoped to a
namespace - the value of this field for those objects will be empty. Must
be a DNS_LABEL. Cannot be updated. More info:
http://kubernetes.io/docs/user-guide/namespaces
ownerReferences <[]Object>
List of objects depended by this object. If ALL objects in the list have
been deleted, this object will be garbage collected. If this object is
managed by a controller, then an entry in this list will point to this
controller, with the controller field set to true. There cannot be more
than one managing controller.
resourceVersion <string>
An opaque value that represents the internal version of this object that
can be used by clients to determine when objects have changed. May be used
for optimistic concurrency, change detection, and the watch operation on a
resource or set of resources. Clients must treat these values as opaque and
passed unmodified back to the server. They may only be valid for a
particular resource or set of resources. Populated by the system.
Read-only. Value must be treated as opaque by clients and . More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency
selfLink <string>
SelfLink is a URL representing this object. Populated by the system.
Read-only.
uid <string>
UID is the unique in time and space value for this object. It is typically
generated by the server on successful creation of a resource and is not
allowed to change on PUT operations. Populated by the system. Read-only.
More info: http://kubernetes.io/docs/user-guide/identifiers#uids
[root@master ~]# kubectl explain pods.spec
KIND: Pod
VERSION: v1
RESOURCE: spec <Object>
DESCRIPTION:
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
PodSpec is a description of a pod.
FIELDS:
activeDeadlineSeconds <integer>
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 <Object>
If specified, the pod's scheduling constraints
automountServiceAccountToken <boolean>
AutomountServiceAccountToken indicates whether a service account token
should be automatically mounted.
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 <Object>
Specifies the DNS parameters of a pod. Parameters specified here will be
merged to the generated DNS configuration based on DNSPolicy.
dnsPolicy <string>
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 <boolean>
EnableServiceLinks indicates whether information about services should be
injected into pod's environment variables, matching the syntax of Docker
links.
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 <boolean>
Use the host's ipc namespace. Optional: Default to false.
hostNetwork <boolean>
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 <boolean>
Use the host's pid namespace. Optional: Default to false.
hostname <string>
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:
https://kubernetes.io/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, or Liveness 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:
https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
nodeName <string>
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 <map[string]string>
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:
https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
priority <integer>
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 <string>
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:
https://github.com/kubernetes/community/blob/master/keps/sig-network/0007-pod-ready%2B%2B.md
restartPolicy <string>
Restart policy for all containers within the pod. One of Always, OnFailure,
Never. Default to Always. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
runtimeClassName <string>
RuntimeClassName refers to a RuntimeClass object in the node.k8s.io 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:
https://github.com/kubernetes/community/blob/master/keps/sig-node/0014-runtime-class.md
This is an alpha feature and may change in the future.
schedulerName <string>
If specified, the pod will be dispatched by specified scheduler. If not
specified, the pod will be dispatched by default scheduler.
securityContext <Object>
SecurityContext holds pod-level security attributes and common container
settings. Optional: Defaults to empty. See type description for default
values of each field.
serviceAccount <string>
DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
Deprecated: Use serviceAccountName instead.
serviceAccountName <string>
ServiceAccountName is the name of the ServiceAccount to use to run this
pod. More info:
https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
shareProcessNamespace <boolean>
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. This field is beta-level and may be
disabled with the PodShareProcessNamespace feature.
subdomain <string>
If specified, the fully qualified Pod hostname will be
"<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not
specified, the pod will not have a domainname at all.
terminationGracePeriodSeconds <integer>
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.
volumes <[]Object>
List of volumes that can be mounted by containers belonging to the pod.
More info: https://kubernetes.io/docs/concepts/storage/volumes
群名称:k8s学习群 群 号:153144292