Kubernetes Learning 2: Resource Management and Getting Started

This part is continued from Kubernetes Learning 1: https://blog.csdn.net/weixin_43155804/article/details/125831675?spm=1001.2014.3001.5502

3. Resource management

3.1 Introduction to resource management

In kubernetes, all content is abstracted into resources, and users need to manage them by operating resources kubernetes.

Kubernetes is essentially a cluster system. Users can deploy various services in the cluster. The so-called deployment service actually means running containers one by one in the kubernetes cluster and running specified programs in the containers.

The smallest management unit of kubernetes is pod instead of container, so the container can only be placed in Podit. Kubernetes generally does not manage Pod directly, but Pod控制器manages Pod through .

After the Pod can provide services, you must consider how to access the services in the Pod. Kubernetes provides Serviceresources to implement this function.

Of course, if the data of the program in the Pod needs to be persisted, various systems kubernetesare also provided .存储

Insert image description here

The core of learning is to learn how to operate various resources kuberneteson the cluster.Pod、Pod控制器、Service、存储

3.2 YAMLSyntax introduction

YAMLIs a markup language XMLsimilar to . JSONIt emphasizes being data -centric and not focusing on markup language. Therefore, YAMLits definition is relatively simple, and it is known as "a humanized data format language".

<!--XML语法格式-->
<xiaoming>
    <age>15</age>
    <address>Beijing</address>
</heima>
# yaml的语法格式
xiaoming:
  age: 15
  address: Beijing

YAMLThe syntax is relatively simple, mainly including the following:

  • Case Sensitive
  • Use indentation to indicate hierarchical relationships
  • Tabs are not allowed for indentation, only spaces are allowed (lower version restrictions)
  • The number of spaces for indentation does not matter, as long as elements at the same level are left aligned
  • '#' indicates comment

YAML supports the following data types:

  • scalar: a single, indivisible value
  • Object: A collection of key-value pairs, also known as mapping/hash/dictionary
  • Array: A set of values ​​arranged in order, also called a sequence/list
# 纯量, 就是指的一个简单的值,字符串、布尔值、整数、浮点数、Null、时间、日期
# 1 布尔类型
c1: true (或者True)
# 2 整型
c2: 234
# 3 浮点型
c3: 3.14
# 4 null类型 
c4: ~  # 使用~表示null
# 5 日期类型
c5: 2018-02-17    # 日期必须使用ISO 8601格式,即yyyy-MM-dd
# 6 时间类型
c6: 2018-02-17T15:02:31+08:00  # 时间使用ISO 8601格式,时间和日期之间使用T连接,最后使用+代表时区
# 7 字符串类型
c7: heima     # 简单写法,直接写值 , 如果字符串中间有特殊字符,必须使用双引号或者单引号包裹 
c8: line1
    line2     # 字符串过多的情况可以拆成多行,每一行会被转化成一个空格
    
    

# 对象
# 形式一(推荐):
heima:
  age: 15
  address: Beijing
# 形式二(了解):
heima: {
    
    age: 15,address: Beijing}

# 数组
# 形式一(推荐):
address:
  - 顺义
  - 昌平  
# 形式二(了解):
address: [顺义,昌平]


hint:

1 yamlRemember : to add a space after writing

2 If you need to put multiple sections yamlof configuration in one file, use ---separation in between.

3 The following is a yamlforwarded jsonwebsite, which can be used to verify yamlwhether the writing is correct.

https://www.json2yaml.com/convert-yaml-to-json

3.3 Resource management methods

There are three forms of resource management in k8s:

  • Imperative object management: directly use commands to operate kubernetes resources

    [root@master ~]# kubectl run nginx-pod --image=nginx:1.17.1 --port=80
    
  • Imperative object configuration: operate kubernetes resources through command configuration and configuration files

    [root@master ~]# kubectl create/patch -f nginx-pod.yaml
    
  • Declarative object configuration: operate kubernetes resources through apply commands and configuration files

    [root@master ~]# kubectl apply -f nginx-pod.yaml
    
3.3.1 Imperative object management

kubectl command

kubectl is a command line tool for kubernetes clusters. It can manage the cluster itself and install and deploy containerized applications on the cluster. The syntax of the kubectl command is as follows:

kubectl [command] [type] [name] [flags]

comand : Specify the operation to be performed on the resource, such as create, get, delete

type : Specify resource type, such as deployment, pod, service

name : Specify the name of the resource, the name is case sensitive

flags : Specify additional optional parameters

# 查看所有pod
[root@master ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6867cdf567-ppmrj   1/1     Running   2          47h

# 查看某个pod
# kubectl get pod pod_name
[root@master ~]# kubectl get pod nginx-6867cdf567-ppmrj
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6867cdf567-ppmrj   1/1     Running   2          47h

# 查看某个pod,以yaml格式展示结果
[root@master ~]# kubectl get pod nginx-6867cdf567-ppmrj -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2022-07-01T08:00:15Z"
  generateName: nginx-6867cdf567-
  labels:
    app: nginx
    pod-template-hash: 6867cdf567
  name: nginx-6867cdf567-ppmrj
  namespace: default
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: nginx-6867cdf567
    uid: b501215e-964d-482f-a5d7-4d6d11b21e69
  resourceVersion: "4624"
  selfLink: /api/v1/namespaces/default/pods/nginx-6867cdf567-ppmrj
  uid: 10ff65fc-3fc5-40d2-822d-fe0b50eb7e41
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-4fbwq
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: node1
  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-4fbwq
    secret:
      defaultMode: 420
      secretName: default-token-4fbwq
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2022-07-01T08:00:15Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2022-07-03T02:47:06Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2022-07-03T02:47:06Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2022-07-01T08:00:15Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://c26f7b36588d1569569af1ff06368851e0d6dad4f99803fa3bdfa4403b4baf22
    image: nginx:1.14-alpine
    imageID: docker-pullable://nginx@sha256:485b610fefec7ff6c463ced9623314a04ed67e3945b9c08d7e53a47f6d108dc7
    lastState:
      terminated:
        containerID: docker://27c9355f64a8e92aebf671bbd27c5238392f5b7d913727b21f3e5039bea5cd7e
        exitCode: 255
        finishedAt: "2022-07-03T02:46:51Z"
        reason: Error
        startedAt: "2022-07-03T02:34:05Z"
    name: nginx
    ready: true
    restartCount: 2
    started: true
    state:
      running:
        startedAt: "2022-07-03T02:47:05Z"
  hostIP: 192.168.79.101
  phase: Running
  podIP: 10.244.2.4
  podIPs:
  - ip: 10.244.2.4
  qosClass: BestEffort
  startTime: "2022-07-01T08:00:15Z"

Resource Type

All content in kubernetes is abstracted into resources, which can be viewed through the following command:

kubectl api-resources

Insert image description here

Frequently used resources include the following:

Resource classification Resource Name abbreviation resource role
Cluster level resources nodes no cluster components
namespaces ns Isolate Pod
pod resources pods after loading container
pod resource controller replicationcontrollers rc Control pod resources
replicasets rs Control pod resources
deployments deploy Control pod resources
daemonsets ds Control pod resources
jobs Control pod resources
cronjobs cj Control pod resources
horizontalpodautoscalers hpa Control pod resources
statefulsets sts Control pod resources
Service discovery resources services svc Unified pod external interface
ingress ing Unified pod external interface
Storage resources volumeattachments storage
persistentvolumes pv storage
persistentvolumeclaims pvc storage
Configure resources configmaps cm Configuration
secrets Configuration

operate

Kubernetes allows a variety of operations on resources. You can view detailed operation commands through –help.

kubectl --help

Insert image description here

Commonly used operations include the following:

Command classification Order translate Command function
basic commands create create Create a resource
edit edit Edit a resource
get Obtain Get a resource
patch renew update a resource
delete delete Delete a resource
explain explain Display resource documents
Run and debug run run Run a specified image in the cluster
expose exposed Expose resources as Service
describe describe Show resource internal information
logs Log output container’s logs in the pod Output the logs of the container in the pod
attach Wrap into a running container Enter a running container
exec Execute a command in the container Execute a command in the container
cp copy Copy files inside and outside the Pod
rollout first display Manage the release of resources
scale scale Expand (shrink) the number of Pods
autoscale auto-adjust Automatically adjust the number of Pods
Advanced commands apply rc Configure resources through files
label Label Update tags on resources
Other commands cluster-info Cluster information Show cluster information
version Version Display the current Server and Client versions

The following is a simple demonstration of the use of the command by creating and deleting a namespace/pod:

# 创建一个namespace
[root@master ~]# kubectl create namespace test
namespace/test created

# 获取namespace
[root@master ~]# kubectl get namespace
NAME              STATUS   AGE
default           Active   2d
kube-node-lease   Active   2d
kube-public       Active   2d
kube-system       Active   2d
test              Active   32s

# 在此namespace下创建并运行一个nginx的Pod
[root@master ~]# kubectl run pod --image=nginx:latest -n dev
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/pod created

# 查看新创建的pod
[root@master ~]# kubectl get pod -n test
NAME                    READY   STATUS             RESTARTS   AGE
pod-644584df94-45vzt    1/1     Running            0          4m33s

# 删除指定的pod
[root@master ~]# kubectl delete pod pod-644584df94-45vzt -n test
pod "pod-644584df94-45vzt" deleted
# 删除之后 查看pod还存在一个新的,这就是pod控制器新创建的,需要直接删除该命名空间,该空间下的pod就会被删除
[root@master ~]# kubectl get pod -n test
NAME                    READY   STATUS             RESTARTS   AGE
pod-644584df94-tt8c4    1/1     Running            0          19s

# 删除指定的namespace (ns 为namespace的缩写)
[root@master ~]# kubectl delete ns test
namespace "test" deleted


# 练习2
[root@master ~]# kubectl create namespace test2
namespace/test2 created

[root@master ~]# kubectl run pod --image=tomcat:latest -n test2
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/pod created

[root@master ~]# kubectl get pod -n test2
NAME                   READY   STATUS              RESTARTS   AGE
pod-7d6ddcbdcb-kl4lh   0/1     ContainerCreating   0          13s

[root@master ~]# kubectl get pod -n test2
NAME                   READY   STATUS    RESTARTS   AGE
pod-7d6ddcbdcb-kl4lh   1/1     Running   0          25s
[root@master ~]# kubectl delete ns test2
namespace "test" deleted
3.3.2 Imperative object configuration

命令式对象配置就是使用命令配合配置文件一起来操作kubernetes资源。

  1. 创建一个nginx_pod.yaml,内容如下:
[root@master ~]# vim nginx_pod.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: testns

---

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod-new
  namespace: testns
spec:
  containers:
  - name: nginx-containers
    image: nginx:latest
  1. 执行create命令,创建资源:
[root@master ~]# kubectl create -f nginx_pod.yaml
namespace/testns created
pod/nginx-pod-new created

此时发现创建了两个资源对象,分别是namespace和pod

  1. 执行get命令,查看资源:
[root@master ~]# kubectl get -f nginx_pod.yaml
NAME               STATUS   AGE
namespace/testns   Active   21s

NAME            READY   STATUS    RESTARTS   AGE
pod/nginx-pod-new   1/1     Running   0          20s

这样就显示了两个资源对象的信息

  1. 执行delete命令,删除资源:
[root@master ~]# kubectl delete -f nginx_pod.yaml
namespace "testns" deleted
pod "nginx-pod-new" deleted

此时发现两个资源对象被删除了

总结:

​ 上述的所有创建、查看、删除都是根据yaml文件进行的,k8s会根据yaml文件中的资源类型(namespace、pod等)去查找对应namespace中的pod信息,执行对应的新建 删除 查看等操作。

​ 命令式对象配置的方式操作资源,可以简单的认为:命令 + yaml配置文件(里面是命令需要的各种参数)

3.3.3 声明式对象配置

声明式对象配置跟命令式对象配置很相似,但是它只有一个命令apply。

# 第一次执行时,kubectl apply -f yaml文件,发现创建了资源
[root@master ~]# kubectl apply -f nginx_pod.yaml
namespace/testns created
pod/nginx-pod-new created


# 再次执行一次kubectl apply -f yaml文件,发现说资源没有变动
[root@master ~]# kubectl apply -f nginx_pod.yaml
namespace/testns unchanged
pod/pod/nginx-pod-new unchanged

# 修改一下yaml中pod的名字为 nginx-pod,版本1.17.2 再次运行,发下已经对其进行了更新
[root@master ~]# kubectl apply -f nginx_pod.yaml
namespace/testns unchanged
pod/nginx-pod created
[root@master ~]# kubectl get pods -n testns
NAME            READY   STATUS    RESTARTS   AGE
nginx-pod       1/1     Running   0          93s
nginx-pod-new   1/1     Running   0          2m26s
[root@master ~]#

总结:
其实声明式对象配置就是使用apply描述一个资源最终的状态(在yaml中定义状态)
使用apply操作资源:
如果资源不存在,就创建,相当于 kubectl create
如果资源已存在,就更新,相当于 kubectl patch

扩展:kubectl可以在node节点上运行吗 ?

# 在node节点运行,发现运行不了
[root@node1 ~]# kubectl get nodes
The connection to the server localhost:8080 was refused - did you specify the right host or port?

kubectl的运行是需要进行配置的,它的配置文件是$HOME/.kube,如果想要在node节点运行此命令,需要将master上的.kube文件复制到node节点上,即在master节点上执行下面操作:

 scp -r ~/.kube node1:~/

[root@master ~]# scp -r ~/.kube node1:~/
The authenticity of host 'node1 (192.168.79.101)' can't be established.
ECDSA key fingerprint is SHA256:aFKR47V4wpGwAGUWwS547whREBh27Qq4Lt/4dfzGCY0.
ECDSA key fingerprint is MD5:65:4f:1a:b3:fd:56:a2:26:b6:ad:59:5a:25:c6:0c:bb.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'node1,192.168.79.101' (ECDSA) to the list of known hosts.
# 输入node1用户的密码
root@node1's password:
config                                                      100% 5450     5.6MB/s   00:00
6bb6226e0013608a96d9c162c1e451a9                            100%  246   382.3KB/s   00:00
e3ab00888cc1b38eddcc3e7ff4f69c02                            100% 4308     5.7MB/s   00:00
66a573cf55e1acb226464f270aff07f3                            100%  416   378.4KB/s   00:00
aa65089b0b9753f156201b77dd98289a                            100%  619   825.9KB/s   00:00
a9c386f06359d6fce9fcfaa882e51b62                            100%  618   937.2KB/s   00:00
c6d7236cd5a61ae08352f3999c94343c                            100%  506   777.5KB/s   00:00
eccb18774d9d1b514e5035b2ae255f5f                            100%  969     1.5MB/s   00:00
f36e6ad8fd14ec9774f3fe4a9d11f054                            100%  316   512.0KB/s   00:00
d452561615d6c0d95c78e4e5b6156225                            100%  547   849.5KB/s   00:00
3c1eb2d86d97dbfd73ca435f9940fd0d                            100%  700     1.1MB/s   00:00
fdc570b125cc1b45648a376027d8f26d                            100% 1041     1.6MB/s   00:00
8b3900d078bf09454b2ca594bfd01592                                                         ...

# 拷贝完毕之后,在node1的客户端重新输get nodes 命令,即可查看,同理node2可以同样进行配置
[root@node1 ~]# kubectl get nodes
NAME     STATUS   ROLES    AGE    VERSION
master   Ready    master   2d1h   v1.17.4
node1    Ready    <none>   2d     v1.17.4
node2    Ready    <none>   2d     v1.17.4

[root@master ~]# scp -r ~/.kube node2:~/
The authenticity of host 'node2 (192.168.79.102)' can't be established.
ECDSA key fingerprint is SHA256:2jVscd74FOtSxcyvbxekRyzI6l2W+a03UD13UBAibs0.
ECDSA key fingerprint is MD5:25:2c:fc:3d:3d:44:21:28:41:f9:04:23:0d:34:53:73.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'node2,192.168.79.102' (ECDSA) to the list of known hosts.
root@node2's password:
config     												  100% 5450     6.7MB/s   00:00
6bb6226e0013608a96d9c162c1e451a9                          100%  246   367.5KB/s   00:00
66a573cf55e1acb226464f270aff07f3                          100%  416   691.4KB/s   00:00
aa65089b0b9753f156201b77dd98289a                          100%  619   877.2KB/s   00:00
a9c386f06359d6fce9fcfaa882e51b62                          100%  618   982.3KB/s   00:00
c6d7236cd5a61ae08352f3999c94343c                          100%  506   901.6KB/s   00:00
eccb18774d9d1b514e5035b2ae255f5f                          100%  969     1.4MB/s   00:00
...
# 拷贝完毕,在node2节点命令行输入
[root@node2 ~]# kubectl get nodes
NAME     STATUS   ROLES    AGE    VERSION
master   Ready    master   2d1h   v1.17.4
node1    Ready    <none>   2d     v1.17.4
node2    Ready    <none>   2d     v1.17.4

问题:三种方式应该怎么用 ?

  • 创建/更新资源 使用声明式对象配置 kubectl apply -f XXX.yaml

  • 删除资源 使用命令式对象配置 kubectl delete -f XXX.yaml

  • 查询资源 使用命令式对象管理 kubectl get(describe) 资源名称

4、实战入门

主要介绍如何在kubernetes集群中部署一个nginx服务,服务相关的名词介绍,能够对其进行访问

4.1 Namespace

Namespace是kubernetes系统中的一种非常重要资源,它的主要作用是用来实现多套环境的资源隔离或者多租户的资源隔离

默认情况下,kubernetes集群中的所有的Pod都是可以相互访问的。但是在实际中,可能不想让两个Pod之间进行互相的访问,那此时就可以将两个Pod划分到不同的namespace下。kubernetes通过将集群内部的资源分配到不同的Namespace中,可以形成逻辑上的"组",以方便不同的组的资源进行隔离使用和管理。

可以通过kubernetes的授权机制,将不同的namespace交给不同租户进行管理,这样就实现了多租户的资源隔离。此时还能结合kubernetes的资源配额机制,限定不同租户能占用的资源,例如CPU使用量、内存使用量等等,来实现租户可用资源的管理。

Insert image description here

kubernetes在集群启动之后,会默认创建4个namespace:

[root@master ~]# kubectl get namespace
NAME              STATUS   AGE
default           Active   6d6h		 #  所有未指定Namespace的对象都会被分配在default命名空间
kube-node-lease   Active   6d6h		 #  集群节点之间的心跳维护,v1.13开始引入
kube-public       Active   6d6h		 #  此命名空间下的资源可以被所有人访问(包括未认证用户)
kube-system       Active   6d6h		 #  所有由Kubernetes系统创建的资源都处于这个命名空间
[root@master ~]#

对namespace的查看,创建删除操作命令:

  1. 查看

1. 查看集群下所有的namespace: kubectl get namespace(可简写为ns)

[root@master ~]# kubectl get namespace
NAME STATUS AGE
default Active 6d6h
kube-node-lease Active 6d6h
kube-public Active 6d6h
kube-system Active 6d6h
[root@master ~]# kubectl get ns
NAME STATUS AGE
default Active 6d6h
kube-node-lease Active 6d6h
kube-public Active 6d6h
kube-system Active 6d6h

2. 查看指定的namespace kubectl get namespace 名字 -o 参数

指定输出格式:支持的参数格式包括:yaml json,wide等

[root@master ~]# kubectl get ns default -o wide
[root@master ~]# kubectl get ns default -o yaml
[root@master ~]# kubectl get ns default -o json
```
Insert image description here

# 3. 查看指定命名空间的具体信息
[root@master ~]# kubectl describe ns kube-system
Name:         kube-system
Labels:       <none>
Annotations:  <none>
Status:       Active	# Active 命名空间正在使用中  Terminating 正在删除命名空间

No resource quota.		# ResourceQuota 针对namespace做的资源限制

No LimitRange resource.	# LimitRange针对namespace中的每个组件做的资源限制
  1. 创建

    # 创建 kubectl create ns 名字
    [root@master ~]# kubectl create ns dev1
    namespace/dev1 created
    [root@master ~]# kubectl get ns dev1
    NAME   STATUS   AGE
    dev1   Active   18s
    
  2. 删除

    # 删除命名空间 kubectl delete ns 名字
    [root@master ~]# kubectl delete ns dev1
    namespace "dev1" deleted
    [root@master ~]# kubectl get ns dev1
    Error from server (NotFound): namespaces "dev1" not found
    [root@master ~]#
    

通过配置文件的方式进行创建和删除:

首先准备一个yaml文件:ns-dev1.yaml

apiVersion: v1
kind: Namespace
metadata:
  name: dev1
# 创建
[root@master ~]# kubectl create -f ns-dev1.yaml
namespace/dev1 created
[root@master ~]# kubectl get ns dev1
NAME   STATUS   AGE
dev1   Active   8s
# 删除
[root@master ~]# kubectl delete -f ns-dev1.yaml
namespace "dev1" deleted
[root@master ~]# kubectl get ns dev1
Error from server (NotFound): namespaces "dev1" not found
[root@master ~]#

Insert image description here

4.2 Pod

Pod是kubernetes集群进行管理的最小单元,程序要运行必须部署在容器中,而容器必须存在于Pod中。一个Pod中可以存在一个或者多个容器。

Insert image description here

kubernetes在集群启动之后,集群中的各个组件也都是以Pod方式运行的。对于pod的一些列操作命令:

  1. 查看
[root@master ~]# kubectl get pod -n kube-system
NAME                             READY   STATUS    RESTARTS   AGE
coredns-9d85f5447-4r5vf          1/1     Running   2          6d6h
coredns-9d85f5447-r9k4g          1/1     Running   2          6d6h
etcd-master                      1/1     Running   4          6d6h
kube-apiserver-master            1/1     Running   4          6d6h
kube-controller-manager-master   1/1     Running   4          6d6h
kube-flannel-ds-298ct            1/1     Running   4          6d6h
kube-flannel-ds-z6whb            1/1     Running   3          6d6h
kube-flannel-ds-zl4mx            1/1     Running   2          6d6h
kube-proxy-9m6xw                 1/1     Running   4          6d6h
kube-proxy-mhssb                 1/1     Running   2          6d6h
kube-proxy-mnn62                 1/1     Running   3          6d6h
kube-scheduler-master            1/1     Running   4          6d6h
[root@master ~]#

  1. 创建并运行pod
#1. 先创建一个命名空间:dev

[root@master ~]# kubectl create ns dev1
namespace/dev1 created
# 2.创建并运行pod

# 命令格式: kubectl run (pod控制器名称) [参数] 
# --image  指定Pod的镜像
# --port   指定端口
# --namespace  指定namespace
[root@master ~]# kubectl run nginx --image=nginx:latest --port=80 --namespace dev1
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx created

Insert image description here

  1. 查看pod信息
# 查看pod信息
[root@master ~]# kubectl get pods -n dev1
NAME                    READY   STATUS    RESTARTS   AGE
nginx-dd6b5d745-qfknr   1/1     Running   0          100s

# 查看pod的详细信息
[root@master ~]# kubectl describe pod nginx -n dev1
Name:         nginx-dd6b5d745-qfknr
Namespace:    dev1
Priority:     0
Node:         node2/192.168.79.102
Start Time:   Thu, 07 Jul 2022 22:27:16 +0800
Labels:       pod-template-hash=dd6b5d745
              run=nginx
Annotations:  <none>
Status:       Running
IP:           10.244.1.16
IPs:
  IP:           10.244.1.16
Controlled By:  ReplicaSet/nginx-dd6b5d745
Containers:
  nginx:
    Container ID:   docker://5a4558ea6b802d5380c6aa51ef396541bff6a41d712b02dddd1109b1eb919592
    Image:          nginx:latest
    Image ID:       docker-pullable://nginx@sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Thu, 07 Jul 2022 22:27:18 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-mnmkq (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-mnmkq:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-mnmkq
    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  3m37s  default-scheduler  Successfully assigned dev1/nginx-dd6b5d745-qfknr to node2
  Normal  Pulling    3m36s  kubelet, node2     Pulling image "nginx:latest"
  Normal  Pulled     3m35s  kubelet, node2     Successfully pulled image "nginx:latest"
  Normal  Created    3m35s  kubelet, node2     Created container nginx
  Normal  Started    3m35s  kubelet, node2     Started container nginx

Insert image description here

  1. 获取pod的ip进行访问
# 获取pods的格式化展示
[root@master ~]# kubectl get pods -n dev1 -o wide
NAME                    READY   STATUS    RESTARTS   AGE    IP            NODE    NOMINATED NODE   READINESS GATES
nginx-dd6b5d745-qfknr   1/1     Running   0          8m9s   10.244.1.16   node2   
# 访问 curl http://10.244.1.16:80
[root@master ~]# curl http://10.244.1.16:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html {
    
     color-scheme: light dark; }
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@master ~]#

Insert image description here

  1. 删除pod

    # 删除指定Pod
    [root@master ~]# kubectl delete pod nginx -n dev1
    Error from server (NotFound): pods "nginx" not found
    [root@master ~]# kubectl get pods -n dev1
    NAME                    READY   STATUS    RESTARTS   AGE
    nginx-dd6b5d745-qfknr   1/1     Running   0          12m
    [root@master ~]# kubectl delete pod nginx-dd6b5d745-qfknr -n dev1
    pod "nginx-dd6b5d745-qfknr" deleted
    
    # 此时,显示删除Pod成功,但是再查询,发现又新产生了一个 
    [root@master ~]# kubectl get pods -n dev1
    NAME                    READY   STATUS    RESTARTS   AGE
    nginx-dd6b5d745-tqlt8   1/1     Running   0          19s
    
    # 这是因为当前Pod是由Pod控制器创建的,控制器会监控Pod状况,一旦发现Pod死亡,会立即重建
    # 此时要想删除Pod,必须删除Pod控制器(控制器内容稍后学习)
    
    # 先来查询一下当前namespace下的Pod控制器
    [root@master ~]# kubectl get deploy -n  dev1
    NAME    READY   UP-TO-DATE   AVAILABLE   AGE
    nginx   1/1     1            1           13m
    # 接下来,删除此PodPod控制器
    [root@master ~]# kubectl delete deploy nginx -n dev1
    deployment.apps "nginx" deleted
    # 稍等片刻,再查询Pod,发现Pod被删除了(控制器被删除了,所控制的pod自然就被删除干净了)
    [root@master ~]# kubectl get pods -n dev
    No resources found in dev namespace.
    [root@master ~]#
    
    

Insert image description here

通过配置文件进行操作:

创建一个pod-nginx1.yaml,内容如下:

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  namespace: dev1
spec:
  containers:
  - image: nginx:latest
    name: pod
    ports:
    - name: nginx-port
      containerPort: 80
      protocol: TCP
[root@master ~]# vim pod-nginx1.yaml
[root@master ~]# cat pod-nginx1.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  namespace: dev1
spec:
  containers:
  - image: nginx:latest
    name: pod
    ports:
    - name: nginx-port
      containerPort: 80
      protocol: TCP
[root@master ~]# kubectl create -f pod-nginx1.yaml
pod/nginx created
[root@master ~]# kubectl get pods -n dev1
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          21s
[root@master ~]# kubectl delete -f pod-nginx1.yaml
pod "nginx" deleted
[root@master ~]# kubectl get pods -n dev1
No resources found in dev1 namespace.
[root@master ~]#

Insert image description here

4.3 Label

Label是kubernetes系统中的一个重要概念。它的作用就是在资源上添加标识,用来对它们进行区分和选择。

Label的特点:

  • 一个Label会以key/value键值对的形式附加到各种对象上,如Node、Pod、Service等等
  • 一个资源对象可以定义任意数量的Label ,同一个Label也可以被添加到任意数量的资源对象上去
  • Label通常在资源对象定义时确定,当然也可以在对象创建后动态添加或者删除

可以通过Label实现资源的多维度分组,以便灵活、方便地进行资源分配、调度、配置、部署等管理工作。

一些常用的Label 示例如下:

  • 版本标签:“version”:“release”, “version”:“stable”…
  • 环境标签:“environment”:“dev”,“environment”:“test”,“environment”:“prod”
  • 架构标签:“tier”:“frontend”,“tier”:“backend”

标签定义完毕之后,还要考虑到标签的选择,这就要使用到Label Selector,即:

Label用于给某个资源对象定义标识

Label Selector用于查询和筛选拥有某些标签的资源对象

当前有两种Label Selector:

  • 基于等式的Label Selector

    name = slave: 选择所有包含Label中key="name"且value="slave"的对象

    env != production: 选择所有包括Label中的key="env"且value不等于"production"的对象

  • 基于集合的Label Selector

    name in (master, slave): 选择所有包含Label中的key="name"且value="master"或"slave"的对象

    name not in (frontend): 选择所有包含Label中的key="name"且value不等于"frontend"的对象

标签的选择条件可以使用多个,此时将多个Label Selector进行组合,使用逗号","进行分隔即可。例如:

name=slave,env!=prod

name not in (frontend),env!=prod

具体命令:

# 1. 查看dev1命名空间下的pod 
[root@master ~]# kubectl get pods -n dev1
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          31s
# 2. 为pod资源打标签 kubectl label pod pod名字 version=1.0(标签内容) -n dev
[root@master ~]# kubectl label pod nginx version=1.0 -n dev1
pod/nginx labeled

# 3. 查看标签
[root@master ~]#  kubectl get pod nginx  -n dev1 --show-labels
NAME    READY   STATUS    RESTARTS   AGE     LABELS
nginx   1/1     Running   0          5m13s   version=1.0

# 4. 为pod资源更新标签 用--overwrite进行覆盖
[root@master ~]# kubectl label pod nginx version=2.0 -n dev1
error: 'version' already has a value (1.0), and --overwrite is false
[root@master ~]# kubectl label pod nginx version=2.0 -n dev1 --overwrite
pod/nginx labeled
# 5.再次查看标签,已经被修改成功
[root@master ~]#  kubectl get pod nginx  -n dev1 --show-labels
NAME    READY   STATUS    RESTARTS   AGE     LABELS
nginx   1/1     Running   0          5m58s   version=2.0
[root@master ~]#
#创建新的pod:nginx1
[root@master ~]# vim pod-nginx1.yaml
[root@master ~]# kubectl create -f pod-nginx1.yaml
pod/nginx1 created
# 查看pod标签信息
[root@master ~]# kubectl get pods -n dev1 --show-labels
NAME     READY   STATUS    RESTARTS   AGE     LABELS
nginx    1/1     Running   0          9m48s   version=2.0
nginx1   1/1     Running   0          54s     <none>
# 给nginx1添加标签
[root@master ~]# kubectl label pod nginx1 version=1.1,tired=front -n dev1
error: invalid label spec: version=1.1,tired=front
[root@master ~]# kubectl label pod nginx1 version=1.1  -n dev1
pod/nginx1 labeled
[root@master ~]# kubectl label pod nginx1 tired=front  -n dev1
pod/nginx1 labeled
[root@master ~]# kubectl get pods -n dev1 --show-labels
NAME     READY   STATUS    RESTARTS   AGE    LABELS
nginx    1/1     Running   0          12m    version=2.0
nginx1   1/1     Running   0          3m9s   tired=front,version=1.1
# 根据标签筛选pod
[root@master ~]# kubectl get pods -l version!=2.0  -n dev1 --show-labels
NAME     READY   STATUS    RESTARTS   AGE    LABELS
nginx1   1/1     Running   0          4m1s   tired=front,version=1.1
[root@master ~]#

#删除标签
[root@master ~]#  kubectl label pod nginx1 tired- -n dev1
pod/nginx1 labeled
# 标签删除成功
[root@master ~]# kubectl get pods -n dev1 --show-labels
NAME     READY   STATUS    RESTARTS   AGE    LABELS
nginx    1/1     Running   0          18m    version=2.0
nginx1   1/1     Running   0          9m8s   version=1.1
[root@master ~]#

Insert image description here
Insert image description here
Insert image description here

配置文件的方式实现:

pod-label.yaml文件

apiVersion: v1
kind: Pod
metadata:
  name: nginx3
  namespace: dev1
  labels:
    version: "3.0" 
    env: "test"
spec:
  containers:
  - image: nginx:latest
    name: pod
    ports:
    - name: nginx-port
      containerPort: 80
      protocol: TCP
[root@master ~]# vim pod-label.yaml
[root@master ~]# kubectl create -f pod-label.yaml
pod/nginx3 created
[root@master ~]# kubectl get pods -n dev1 --show-labels
NAME     READY   STATUS    RESTARTS   AGE   LABELS
nginx    1/1     Running   0          28m   version=2.0
nginx1   1/1     Running   0          19m   version=1.1
nginx3   1/1     Running   0          10s   env=test,version=3.0
[root@master ~]#

Insert image description here

4.4 Deployment

在kubernetes中,Pod是最小的控制单元,但是kubernetes很少直接控制Pod,一般都是通过Pod控制器来完成的。Pod控制器用于pod的管理,确保pod资源符合预期的状态,当pod的资源出现故障时,会尝试进行重启或重建pod。

在kubernetes中Pod控制器的种类有很多,着重介绍Deployment。

Insert image description here

Deployment的操作命令

![4.4-2](E:\02-学习笔记\笔记图片\k8s\4.4-2.png)# 创建命名空间
[root@master ~]# kubectl create ns test
namespace/test created
# 创建deployment
[root@master ~]# kubectl run nginx-deployment --image=nginx:latest --port=80 --replicas=3 -n test
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx-deployment created
# 查看deployment
[root@master ~]# kubectl get deployment nginx-deployment -n test
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           40s
# 查看pods
[root@master ~]# kubectl get pods -n test
NAME                               READY   STATUS    RESTARTS   AGE
nginx-deployment-68975cbb9-jtm4c   1/1     Running   0          109s
nginx-deployment-68975cbb9-jw2dq   1/1     Running   0          109s
nginx-deployment-68975cbb9-q6ddq   1/1     Running   0          109s
[root@master ~]# kubectl get deployment, pods -n test
error: arguments in resource/name form must have a single resource and name
[root@master ~]# kubectl get deployment -n test
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           2m14s

[root@master ~]# kubectl get deploy -n test -o wide
NAME               READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS         IMAGES         SELECTOR
nginx-deployment   3/3     3            3           3m51s   nginx-deployment   nginx:latest   run=nginx-deployment

# 删除 
[root@master ~]#  kubectl delete deploy nginx-deployment -n test
deployment.apps "nginx-deployment" deleted
[root@master ~]# kubectl delete ns test
namespace "test" deleted
[root@master ~]#


# 命令格式: kubectl create deployment 名称  [参数] 
# --image  指定pod的镜像
# --port   指定端口
# --replicas  指定创建pod数量
# --namespace  指定namespace
[root@master ~]# kubectl create deployment nginx --image=nginx:latest --port=80 --replicas=3 -n test
deployment.apps/nginx created

Insert image description here

通过配置文件操作

创建一个deploy-nginx.yaml,内容如下:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: test
spec:
  replicas: 3
  selector:
    matchLabels:
      run: nginx
  template:
    metadata:
      labels:
        run: nginx
    spec:
      containers:
      - image: nginx:latest
        name: nginx
        ports:
        - containerPort: 80
          protocol: TCP

deployment的创建通过yaml文件的方式十分方便

[root@master ~]# kubectl create ns test
namespace/test created
[root@master ~]# vim deploy-nginx.yaml
[root@master ~]# kubectl create -f deploy-nginx.yaml
deployment.apps/nginx created
[root@master ~]# kubectl get deploy -n test
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   0/3     3            0           15s
[root@master ~]# kubectl get deploy -n test -o wide
NAME    READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES         SELECTOR
nginx   3/3     3            3           33s   nginx        nginx:latest   run=nginx

Insert image description here

4.5 Service

通过上节课的学习,已经能够利用Deployment来创建一组Pod来提供具有高可用性的服务。

虽然每个Pod都会分配一个单独的Pod IP,然而却存在如下两问题:

  • Pod IP 会随着Pod的重建产生变化
  • Pod IP 仅仅是集群内可见的虚拟IP,外部无法访问

这样对于访问这个服务带来了难度。因此,kubernetes设计了Service来解决这个问题。

Service can be regarded as the external access interface of a group of similar Pods . With Service, applications can easily implement service discovery and load balancing.

Insert image description here

1. Create a service accessible within the cluster

# 1. 暴露Service
[root@master ~]# kubectl expose deploy nginx --name=svc-nginx1 --type=ClusterIP --port=80 --target-port=80 -n test
service/svc-nginx1 exposed

# 2. 查看service
[root@master ~]# kubectl get svc svc-nginx1 -n test -o wide
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE   SELECTOR
svc-nginx1   ClusterIP   10.107.107.241   <none>        80/TCP    23s   run=nginx


# 这里产生了一个CLUSTER-IP,这就是service的IP,在Service的生命周期中,这个地址是不会变动的
# 可以通过这个IP访问当前service对应的POD
[root@master ~]# curl 10.107.107.241:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html {
    
     color-scheme: light dark; }
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@master ~]#

Insert image description here

2. Create a service that can be accessed outside the cluster

# 上面创建的Service的type类型为ClusterIP,这个ip地址只用集群内部可访问
# 如果需要创建外部也可以访问的Service,需要修改type为NodePort
[root@master ~]# kubectl expose deploy nginx --name=svc-nginx2 --type=NodePort --port=80 --target-port=80 -n test
service/svc-nginx2 exposed

# 此时查看,会发现出现了NodePort类型的Service,而且有一对Port(80:30186/TC)
[root@master ~]# kubectl get svc  svc-nginx2  -n test -o wide
NAME         TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE   SELECTOR
svc-nginx2   NodePort   10.105.190.253   <none>        80:30186/TCP   19s   run=nginx
# 接下来就可以通过集群外的主机访问 节点IP:31928访问服务了
# 例如在的电脑主机上通过浏览器访问下面的地址 
#  http://192.168.79.100:30186
#  http://192.168.79.101:30186
#  http://192.168.79.102:30186

# 删除service
[root@master ~]# kubectl delete svc svc-nginx1 -n test
service "svc-nginx1" deleted

Insert image description here

Insert image description here

Insert image description here

Through configuration files

Create a svc-nginx.yaml with the following content:

apiVersion: v1
kind: Service
metadata:
  name: svc-nginx
  namespace: test
spec:
  clusterIP: 10.107.108.109 #固定svc的内网ip 不固定的话,会自动生成
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    run: nginx
  type: ClusterIP
[root@master ~]# vim svc-nginx.yaml
[root@master ~]# cat svc-nginx.yaml
apiVersion: v1
kind: Service
metadata:
  name: svc-nginx
  namespace: test
spec:
  clusterIP: 10.107.108.109 #固定svc的内网ip 不固定的话,会自动生成
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    run: nginx
  type: ClusterIP
[root@master ~]# kubectl create -f svc-nginx.yaml
service/svc-nginx created
# 文件中有IP时,采用固定IP
[root@master ~]# kubectl get svc  svc-nginx  -n test -o wide
NAME        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE   SELECTOR
svc-nginx   ClusterIP   10.107.108.109   <none>        80/TCP    24s   run=nginx
[root@master ~]# curl 10.107.108.109:80



[root@master ~]# kubectl delete -f svc-nginx.yaml
service "svc-nginx" deleted
[root@master ~]# vim svc-nginx.yaml
[root@master ~]# kubectl create -f svc-nginx.yaml
service/svc-nginx created
# 不固定时自动生成IP
[root@master ~]# kubectl get svc  svc-nginx  -n test -o wide
NAME        TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE   SELECTOR
svc-nginx   ClusterIP   10.98.154.253   <none>        80/TCP    7s    run=nginx
[root@master ~]# curl 10.98.154.253:80

[root@master ~]# cat svc-nginx.yaml
apiVersion: v1
kind: Service
metadata:
  name: svc-nginx
  namespace: test
spec:
  clusterIP:  #固定svc的内网ip 不固定的话,会自动生成
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    run: nginx
  type: ClusterIP
[root@master ~]#

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43155804/article/details/125832315