作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.资源对象管理方式
kubectl的命令可分为三类:
陈述式命令(Imperative Commands)
陈述式对象配置(Imperative Object Configuration)
声明式对象配置(Declarative Object Configuration)
第一种方式即此前用到的run,expose,delete和get等命令,它们直接作用于kubernetes系统上的活动对象,简单易用,但不是支持代码复用,修改复审及审计日志等功能,这些功能的实现通常要依赖于资源配置文件中,这些文件也被称为资源清单。
1>.陈述式命令创建名称空间案例(执行命令的方式缺点就是每次都得去敲,复用性极差,因此它相比陈述式,声明式对象配置压根就没有复用性)
[root@master200.yinzhengjie.org.cn ~]# kubectl get namespace #查看名称空间
NAME STATUS AGE
default Active 9h
kube-node-lease Active 9h
kube-public Active 9h
kube-system Active 9h
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns #也是查看名称空间,只不过这里是简写形式而已
NAME STATUS AGE
default Active 9h
kube-node-lease Active 9h
kube-public Active 9h
kube-system Active 9h
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl create namespace operation #创建一个叫做"operation"的名称空间
namespace/operation created
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl create ns development
namespace/development created
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl create ns testing
namespace/testing created
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns
NAME STATUS AGE
default Active 9h
development Active 38s
kube-node-lease Active 9h
kube-public Active 9h
kube-system Active 9h
operation Active 65s
testing Active 3s
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
2>.陈述式对象配置创建名称空间案例(重复创建时会报错,生产环境不推荐使用)
[root@master200.yinzhengjie.org.cn ~]# mkdir -pv /yinzhengjie/data/k8s/manifests/basic
mkdir: created directory ‘/yinzhengjie/data’
mkdir: created directory ‘/yinzhengjie/data/k8s’
mkdir: created directory ‘/yinzhengjie/data/k8s/manifests’
mkdir: created directory ‘/yinzhengjie/data/k8s/manifests/basic’
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cd /yinzhengjie/data/k8s/manifests/basic/
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# vim develop-ns.yaml
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# cat develop-ns.yaml
apiVersion: v1
kind: Namespace
metadata:
name: develop
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl get ns
NAME STATUS AGE
default Active 17h
kube-node-lease Active 17h
kube-public Active 17h
kube-system Active 17h
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# ll
total 4
-rw-r--r-- 1 root root 59 Feb 5 12:53 develop-ns.yaml
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl create -f develop-ns.yaml #使用陈述式对象配置创建名称空间
namespace/develop created
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# ll
total 4
-rw-r--r-- 1 root root 59 Feb 5 12:53 develop-ns.yaml
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl get ns
NAME STATUS AGE
default Active 17h
develop Active 8s
kube-node-lease Active 17h
kube-public Active 17h
kube-system Active 17h
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl create -f develop-ns.yaml #由于咱们定义的"develop"名称空间已经存在,因此给咱们抛出异常
Error from server (AlreadyExists): error when creating "develop-ns.yaml": namespaces "develop" already exists
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
3>.声明式对象配置创建名称空间案例(重复创建时并不会报错)
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# cp develop-ns.yaml production-ns.yaml
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# vim production-ns.yaml
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# cat production-ns.yaml
apiVersion: v1
kind: Namespace
metadata:
name: production
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# ll
total 8
-rw-r--r-- 1 root root 59 Feb 5 12:53 develop-ns.yaml
-rw-r--r-- 1 root root 62 Feb 5 12:55 production-ns.yaml
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl get ns
NAME STATUS AGE
default Active 17h
develop Active 2m26s
kube-node-lease Active 17h
kube-public Active 17h
kube-system Active 17h
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl get namespace
NAME STATUS AGE
default Active 17h
develop Active 2m35s
kube-node-lease Active 17h
kube-public Active 17h
kube-system Active 17h
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl apply -f production-ns.yaml #使用声明式对象配置创建名称空间
namespace/production created
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl get namespace
NAME STATUS AGE
default Active 17h
develop Active 2m57s
kube-node-lease Active 17h
kube-public Active 17h
kube-system Active 17h
production Active 2s
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]# kubectl apply -f production-ns.yaml #重复创建同一个名称空间时并不会报错,而是友好的提示咱们没有发生任何改变。
namespace/production unchanged
[root@master200.yinzhengjie.org.cn /yinzhengjie/data/k8s/manifests/basic]#
二.使用声明式对象配置创建pod(在一个pod中创建一个容器)
查看官方的参数参考文档:
https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#pod-v1-core
1>.使用"--export"选项将一个容器的创建作为模板导出(注意,该参数已经被废弃了,生产环境中尽量避免使用它,推荐大家使用Helm去管理)
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
mynginx-677d85dbd5-gkdb6 1/1 Running 0 5h12m
mynginx-677d85dbd5-vk5p5 1/1 Running 0 5h39m
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods mynginx-677d85dbd5-gkdb6 -o yaml --export > /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
Flag --export has been deprecated, This flag is deprecated and will be removed in future.
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
generateName: mynginx-677d85dbd5-
labels:
app: mynginx
pod-template-hash: 677d85dbd5
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet
name: mynginx-677d85dbd5
uid: c5ff8e76-768b-4673-8df3-b5d3246a929d
selfLink: /api/v1/namespaces/default/pods/mynginx-677d85dbd5-gkdb6
spec:
containers:
- image: nginx:1.14-alpine
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-4jpjf
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node201.yinzhengjie.org.cn
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-4jpjf
secret:
defaultMode: 420
secretName: default-token-4jpjf
status:
phase: Pending
qosClass: BestEffort
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
2>.修改上一步生成的模板,只保留必要的参数
[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
name: pod-demo
namespace: develop
spec:
containers:
- image: nginx:1.14-alpine
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node203.yinzhengjie.org.cn
priority: 0
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod01-demo.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
name: pod01-demo
namespace: develop
spec:
containers:
- image: nginx:1.14-alpine
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
dnsPolicy: ClusterFirst
enableServiceLinks: true
priority: 0
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod01-demo.yaml
3>.使用声明式对象配置创建pod
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 5h23m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 5h51m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml #使用声明式对象配置创建pod
pod/pod-demo created
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/pod01-demo.yaml #同上
pod/pod01-demo configured
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide #注意,此处我没有指定名称空间,因此我们查看的默认就是"default"这个名称空间哟~
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 5h34m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 6h2m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide #综上所述,如果我们想要查看创建的pod,应该去相应的名称空间去查看,很显然,我们在"develop"这个名称空间查看到了。
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-demo 1/1 Running 0 13m 10.244.3.4 node203.yinzhengjie.org.cn <none> <none>
pod01-demo 1/1 Running 0 5m56s 10.244.3.5 node203.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
三.使用声明式对象配置创建pod(在一个pod中创建2个容器)
1>.通过命令行查看pod这个资源如何定义的帮助文档
[root@master200.yinzhengjie.org.cn ~]# 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
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.apiVersion
KIND: Pod
VERSION: v1
FIELD: apiVersion <string>
DESCRIPTION:
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
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.apiVersion #我们还可以继续查看每个字段的使用帮助信息,当然也可以去查看帮助给的URL的帮助信息,下面的查询方式相同
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.kind
KIND: Pod
VERSION: v1
FIELD: kind <string>
DESCRIPTION:
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
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.kind
[root@master200.yinzhengjie.org.cn ~]# 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/sig-architecture/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/sig-architecture/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/sig-architecture/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. Finalizers may be processed and removed in
any order. Order is NOT enforced because it introduces significant risk of
stuck finalizers. finalizers is a shared field, any actor with permission
can reorder it. If the finalizer list is processed in order, then this can
lead to a situation in which the component responsible for the first
finalizer in the list is waiting for a signal (field value, external
system, or other) produced by a component responsible for a finalizer later
in the list, resulting in a deadlock. Without enforced ordering finalizers
are free to order amongst themselves and are not vulnerable to ordering
changes in the list.
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/sig-architecture/api-conventions.md#idempotency
generation <integer>
A sequence number representing a specific generation of the desired state.
Populated by the system. Read-only.
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
managedFields <[]Object>
ManagedFields maps workflow-id and version to the set of fields that are
managed by that workflow. This is mostly for internal housekeeping, and
users typically shouldn't need to set or understand this field. A workflow
can be the user's name, a controller's name, or the name of a specific
apply path like "ci-cd". The set of fields is always in the version that
the workflow used when modifying the object.
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/sig-architecture/api-conventions.md#concurrency-control-and-consistency
selfLink <string>
SelfLink is a URL representing this object. Populated by the system.
Read-only. DEPRECATED Kubernetes will stop propagating this field in 1.20
release and the field is planned to be removed in 1.21 release.
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@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.metadata
[root@master200.yinzhengjie.org.cn ~]# 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/sig-architecture/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. 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 <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, 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:
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/
overhead <map[string]string>
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:
https://git.k8s.io/enhancements/keps/sig-node/20190226-pod-overhead.md This
field is alpha-level as of Kubernetes v1.16, and is only honored by servers
that enable the PodOverhead feature.
preemptionPolicy <string>
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 <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://git.k8s.io/enhancements/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://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This is a
beta feature as of Kubernetes v1.14.
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.
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.
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 alpha-level and is only honored by
clusters that enables the EvenPodsSpread feature. All
topologySpreadConstraints are ANDed.
volumes <[]Object>
List of volumes that can be mounted by containers belonging to the pod.
More info: https://kubernetes.io/docs/concepts/storage/volumes
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec #注意,如果字段后面跟的有"-required-"关键词,说明这个字段必须定义
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.status
KIND: Pod
VERSION: v1
RESOURCE: status <Object>
DESCRIPTION:
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
PodStatus represents information about the status of a pod. Status may
trail the actual state of a system, especially if the node that hosts the
pod cannot contact the control plane.
FIELDS:
conditions <[]Object>
Current service state of pod. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions
containerStatuses <[]Object>
The list has one entry per container in the manifest. Each entry is
currently the output of `docker inspect`. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status
ephemeralContainerStatuses <[]Object>
Status for any ephemeral containers that have run in this pod. This field
is alpha-level and is only populated by servers that enable the
EphemeralContainers feature.
hostIP <string>
IP address of the host to which the pod is assigned. Empty if not yet
scheduled.
initContainerStatuses <[]Object>
The list has one entry per init container in the manifest. The most recent
successful init container will have ready = true, the most recently started
container will have startTime set. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status
message <string>
A human readable message indicating details about why the pod is in this
condition.
nominatedNodeName <string>
nominatedNodeName is set only when this pod preempts other pods on the
node, but it cannot be scheduled right away as preemption victims receive
their graceful termination periods. This field does not guarantee that the
pod will be scheduled on this node. Scheduler may decide to place the pod
elsewhere if other nodes become available sooner. Scheduler may also decide
to give the resources on this node to a higher priority pod that is created
after preemption. As a result, this field may be different than
PodSpec.nodeName when the pod is scheduled.
phase <string>
The phase of a Pod is a simple, high-level summary of where the Pod is in
its lifecycle. The conditions array, the reason and message fields, and the
individual container status arrays contain more detail about the pod's
status. There are five possible phase values: Pending: The pod has been
accepted by the Kubernetes system, but one or more of the container images
has not been created. This includes time before being scheduled as well as
time spent downloading images over the network, which could take a while.
Running: The pod has been bound to a node, and all of the containers have
been created. At least one container is still running, or is in the process
of starting or restarting. Succeeded: All containers in the pod have
terminated in success, and will not be restarted. Failed: All containers in
the pod have terminated, and at least one container has terminated in
failure. The container either exited with non-zero status or was terminated
by the system. Unknown: For some reason the state of the pod could not be
obtained, typically due to an error in communicating with the host of the
pod. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-phase
podIP <string>
IP address allocated to the pod. Routable at least within the cluster.
Empty if not yet allocated.
podIPs <[]Object>
podIPs holds the IP addresses allocated to the pod. If this field is
specified, the 0th entry must match the podIP field. Pods may be allocated
at most 1 value for each of IPv4 and IPv6. This list is empty if no IPs
have been allocated yet.
qosClass <string>
The Quality of Service (QOS) classification assigned to the pod based on
resource requirements See PodQOSClass type for available QOS classes More
info:
https://git.k8s.io/community/contributors/design-proposals/node/resource-qos.md
reason <string>
A brief CamelCase message indicating details about why the pod is in this
state. e.g. 'Evicted'
startTime <string>
RFC 3339 date and time at which the object was acknowledged by the Kubelet.
This is before the Kubelet pulled the container image(s) for the pod.
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.status
[root@master200.yinzhengjie.org.cn ~]# 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/
startupProbe <Object>
StartupProbe indicates that the Pod has successfully initialized. If
specified, no other probes are executed until this completes successfully.
If this probe fails, the Pod will be restarted, just as if the
livenessProbe failed. This can be used to provide different probe
parameters at the beginning of a Pod's lifecycle, when it might take a long
time to load data or warm a cache, than during steady-state operation. This
cannot be updated. This is an alpha feature enabled by the StartupProbe
feature flag. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
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 a beta feature.
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.
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.env
KIND: Pod
VERSION: v1
RESOURCE: env <[]Object>
DESCRIPTION:
List of environment variables to set in the container. Cannot be updated.
EnvVar represents an environment variable present in a Container.
FIELDS:
name <string> -required-
Name of the environment variable. Must be a C_IDENTIFIER.
value <string>
Variable references $(VAR_NAME) are expanded using the previous defined
environment variables in the container and any service environment
variables. 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. Defaults to "".
valueFrom <Object>
Source for the environment variable's value. Cannot be used if value is not
empty.
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.env
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.env.name
KIND: Pod
VERSION: v1
FIELD: name <string>
DESCRIPTION:
Name of the environment variable. Must be a C_IDENTIFIER.
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.env.name
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.env.valueFrom
KIND: Pod
VERSION: v1
RESOURCE: valueFrom <Object>
DESCRIPTION:
Source for the environment variable's value. Cannot be used if value is not
empty.
EnvVarSource represents a source for the value of an EnvVar.
FIELDS:
configMapKeyRef <Object>
Selects a key of a ConfigMap.
fieldRef <Object>
Selects a field of the pod: supports metadata.name, metadata.namespace,
metadata.labels, metadata.annotations, spec.nodeName,
spec.serviceAccountName, status.hostIP, status.podIP, status.podIPs.
resourceFieldRef <Object>
Selects a resource of the container: only resources limits and requests
(limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu,
requests.memory and requests.ephemeral-storage) are currently supported.
secretKeyRef <Object>
Selects a key of a secret in the pod's namespace
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.env.valueFrom
2>.自定义yaml文件创建两个容器
[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/pod02-demo.yaml
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod02-demo.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod02-demo
namespace: production
spec:
containers:
- name: mynginx
image: nginx:1.14-alpine
- name: mybox
image: busybox:latest
imagePullPolicy: IfNotPresent
command: ["/bin/sh","-c","sleep 86400"]
[root@master200.yinzhengjie.org.cn ~]#
3>.使用声明式对象配置创建pod
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production
No resources found in production namespace.
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/pod02-demo.yaml
pod/pod02-demo created
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production #很明显,任务被调度到一台服务器后,需要一个创建过程(要先下载镜像文件),此时状态为"ContainerCreating"
NAME READY STATUS RESTARTS AGE
pod02-demo 0/2 ContainerCreating 0 3s
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production
NAME READY STATUS RESTARTS AGE
pod02-demo 2/2 Running 0 19s
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production -o wide #POD创建成功后状态为"Running",注意"READY"那一列是2个容器哟,我们上面定义了一个mynginx,另一个叫mybox
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod02-demo 2/2 Running 0 4m32s 10.244.1.4 node201.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production -o yaml
apiVersion: v1
items:
- apiVersion: v1
kind: Pod
metadata:
annotations:
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"name":"pod02-demo","namespace":"production"},"spec":{"containers":[{"image":"nginx:1.14-alpine","name":"mynginx"},{"command":["/bin/sh","-c","sleep 86400"],"image":"busybox:latest","imagePullPolicy":"
IfNotPresent","name":"mybox"}]}} creationTimestamp: "2020-02-05T06:28:49Z"
name: pod02-demo
namespace: production
resourceVersion: "95129"
selfLink: /api/v1/namespaces/production/pods/pod02-demo
uid: fe72e30f-dee5-4d8a-a7f2-aafd976b747e
spec:
containers:
- image: nginx:1.14-alpine
imagePullPolicy: IfNotPresent
name: mynginx
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-rcm5g
readOnly: true
- command:
- /bin/sh
- -c
- sleep 86400
image: busybox:latest
imagePullPolicy: IfNotPresent
name: mybox
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-rcm5g
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node201.yinzhengjie.org.cn
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-rcm5g
secret:
defaultMode: 420
secretName: default-token-rcm5g
status:
conditions:
- lastProbeTime: null
lastTransitionTime: "2020-02-05T06:28:49Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2020-02-05T06:28:54Z"
status: "True"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2020-02-05T06:28:54Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2020-02-05T06:28:49Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: docker://28282d6f41623874032ec415293fbfcbe2876458b331cbce80637c3050707eee
image: busybox:latest
imageID: docker-pullable://busybox@sha256:6915be4043561d64e0ab0f8f098dc2ac48e077fe23f488ac24b665166898115a
lastState: {}
name: mybox
ready: true
restartCount: 0
started: true
state:
running:
startedAt: "2020-02-05T06:28:54Z"
- containerID: docker://e1d847b3484f38825a5442c4e8cfaefa3f4e6be0a3d5508b920e79d4128cda29
image: nginx:1.14-alpine
imageID: docker-pullable://nginx@sha256:485b610fefec7ff6c463ced9623314a04ed67e3945b9c08d7e53a47f6d108dc7
lastState: {}
name: mynginx
ready: true
restartCount: 0
started: true
state:
running:
startedAt: "2020-02-05T06:28:50Z"
hostIP: 172.200.1.201
phase: Running
podIP: 10.244.1.4
podIPs:
- ip: 10.244.1.4
qosClass: BestEffort
startTime: "2020-02-05T06:28:49Z"
kind: List
metadata:
resourceVersion: ""
selfLink: ""
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production -o yaml #我们发现K8S集群会自动帮咱们补齐一些咱们没有设置的(默认)参数
4>.连接名为"pod02-demo"的其中的一个"mybox"容器,访问该pod中的另外一个容器"mynginx"(因为它们公用同一个网络空间,所以可以通过回环地址访问哟~)
@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod02-demo 2/2 Running 0 11m 10.244.1.4 node201.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl exec pod02-demo -c mybox -n production -it -- /bin/sh
/ #
/ # ifconfig
eth0 Link encap:Ethernet HWaddr 36:88:5B:4A:79:AD
inet addr:10.244.1.4 Bcast:0.0.0.0 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1450 Metric:1
RX packets:1 errors:0 dropped:0 overruns:0 frame:0
TX packets:1 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:42 (42.0 B) TX bytes:42 (42.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
/ #
/ # netstat -ntl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
/ #
/ # ps aux
PID USER TIME COMMAND
1 root 0:00 sleep 86400
6 root 0:00 /bin/sh
13 root 0:00 ps aux
/ #
/ # wget -O - -q 127.0.0.1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
/ #
[root@master200.yinzhengjie.org.cn ~]# kubectl exec pod02-demo -c mybox -n production -it -- /bin/sh
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production
NAME READY STATUS RESTARTS AGE
pod02-demo 2/2 Running 0 15m
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl exec pod02-demo -c mynginx -n production -it -- /bin/sh
/ #
/ # ifconfig
eth0 Link encap:Ethernet HWaddr 36:88:5B:4A:79:AD
inet addr:10.244.1.4 Bcast:0.0.0.0 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1450 Metric:1
RX packets:1 errors:0 dropped:0 overruns:0 frame:0
TX packets:1 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:42 (42.0 B) TX bytes:42 (42.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:11 errors:0 dropped:0 overruns:0 frame:0
TX packets:11 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1381 (1.3 KiB) TX bytes:1381 (1.3 KiB)
/ #
/ # netstat -ntl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
/ #
/ # ps aux
PID USER TIME COMMAND
1 root 0:00 nginx: master process nginx -g daemon off;
6 nginx 0:00 nginx: worker process
7 root 0:00 /bin/sh
14 root 0:00 ps aux
/ #
/ #
[root@master200.yinzhengjie.org.cn ~]# kubectl exec pod02-demo -c mynginx -n production -it -- /bin/sh
5>.连接名为"pod02-demo"的其中的一个"mynginx"容器,查看日志信息
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n production -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod02-demo 2/2 Running 0 28m 10.244.1.4 node201.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl logs pod02-demo -c mynginx -n production
127.0.0.1 - - [05/Feb/2020:06:43:11 +0000] "GET / HTTP/1.1" 200 612 "-" "Wget" "-"
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl logs pod02-demo -c mynginx -n production
四.配置pod直接使用宿主机网络方案一(hostNetwork)
1>.编写pod的yaml文件并创建pod
[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
namespace: default
spec:
containers:
- name: mynginx
image: nginx:1.14-alpine
hostNetwork: true
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 6h58m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h26m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
pod/mypod created
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 6h58m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h26m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
mypod 1/1 Running 0 2s 172.200.1.202 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
2>. 浏览器访问宿主机的IP地址并查看日志
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 6h58m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h26m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
mypod 1/1 Running 0 2s 172.200.1.202 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl logs mypod #注意,当我们的pod中只有一个容器时,我们无需使用"-c"参数指定容器名称哟~
172.200.0.1 - - [05/Feb/2020:07:11:26 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" "-"
172.200.0.1 - - [05/Feb/2020:07:11:26 +0000] "GET /favicon.ico HTTP/1.1" 404 571 "http://172.200.1.202/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" "-"
2020/02/05 07:11:26 [error] 6#6: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.200.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "172.200.1.202", referrer: "http://172.200.1.202/"
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl logs mypod #注意,当我们的pod中只有一个容器时,我们无需使用"-c"参数指定容器名称哟~
3>.使用yaml文件删除pod
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 7h10m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h38m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
mypod 1/1 Running 0 11m 172.200.1.202 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl delete -f /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
pod "mypod" deleted
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 7h11m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h39m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl delete -f /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
五.配置pod直接使用宿主机网络端口方案二(hostPort)
1>.编写pod的yaml文件
[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
namespace: default
spec:
containers:
- name: mynginx
image: nginx:1.14-alpine
ports:
- protocol: TCP
containerPort: 80
name: http
hostPort: 8080
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
2>.使用声明式对象配置创建pod
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 7h20m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h48m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
pod/mypod created
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 7h20m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h48m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
mypod 1/1 Running 0 2s 10.244.2.3 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/host-pod.yaml
3>.浏览器访问宿主机的IP地址并查看日志
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mynginx-677d85dbd5-gkdb6 1/1 Running 0 7h20m 10.244.1.3 node201.yinzhengjie.org.cn <none> <none>
mynginx-677d85dbd5-vk5p5 1/1 Running 0 7h48m 10.244.2.2 node202.yinzhengjie.org.cn <none> <none>
mypod 1/1 Running 0 2s 10.244.2.3 node202.yinzhengjie.org.cn <none> <none>
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl logs mypod
172.200.0.1 - - [05/Feb/2020:07:34:23 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" "-"
2020/02/05 07:34:23 [error] 6#6: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.200.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "172.200.1.202:8080", referrer: "http://172.200.1.202:8080/"
172.200.0.1 - - [05/Feb/2020:07:34:23 +0000] "GET /favicon.ico HTTP/1.1" 404 571 "http://172.200.1.202:8080/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" "-"
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl logs mypod