Kubernetes资源详解

1.Kubernetes中的资源

1.1资源管理介绍

在这里插入图片描述

  • kubernetes中,所有的内容都抽象为资源,用户需要通过操作资源来管理kubernetes
  • kubernetes 本质上就是一个集群系统,用户可以在集群部署各种服务
  • 所谓的部署服务,其实就是在kubernetes集群中运行一个个的容器,并将指定的程序跑在容器
  • kubernetes最小管理单元pod不是容器只能容器放在pod
  • kubernetes一般也不会直接管理pod,而是通过pod控制器来管理pod
  • pod容器服务访问是由kubernetes提供的service资源来实现的。pod中的容器不能直接被访问,需要通过service微服务端口进行暴露,最终我们通过微服务来访问pod中的容器
  • pod中程序的数据需要持久化是由kubernetes提供的各种存储系统来实现的

1.2资源管理方式

  • 命令式对象管理:直接使用命令去操作kubernetes资源
[root@k8s-master ~]# kubectl run nginx-pod --image=nginx:latest --port=80

#nginx-pod是pod名
  • 命令式对象配置:通过命令配置配置文件去操作kubernetes资源
    • 不能对yaml中的内容做更新k8s不允许对create创建的yaml文件进行修改
[root@k8s-master ~]# kubectl  create/patch  -f  nginx-pod.yml
  • 声明式对象配置:通过apply命令和配置文件去操作kubernetes资源
    • 可以对yaml中的内容做更新(修改完yaml文件的内容后,可以使用apply对其进行应用
[root@k8s-master ~]# kubectl  apply  -f  nginx-pod.yml
类型适用环境优点缺点
命令式对象管理测试简单只能操作活动对象,无法审计,跟踪
命令式对象配置开发可以审计,跟踪项目大时,配置文件多,操作麻烦
声明式对象配置开发支持目录操作意外情况下难以调试

1.2.1命令式对象管理

  • kubectlkubernetes集群的命令行工具,通过它能够对集群本身进行管理,并能够在集群上进行容器化应用的安装部署
  • kubectl命令的语法如下:
[root@k8s-master ~]# kubectl  [command]  [type]  [name]  [flags]
  • command:指定要对资源执行的操作,例如creategetdelete
  • type:指定资源类型,比如deploymentpodservice
  • name:指定资源名称名称大小写敏感
  • flags:指定额外可选参数

查看所有pod

[root@k8s-master ~]# kubectl get pods 

查看某一个pod

[root@k8s-master ~]# kubectl get pods pod名

查看某个pod,以yaml格式显示

[root@k8s-master ~]# kubectl get pods pod名 -o yaml

创建两个名为webserver1webserver2pod

  • 其中myapp是一个nginx服务
[root@k8s-master ~]# kubectl run webserver1 --image myapp:v1
pod/webserver1 created
[root@k8s-master ~]# kubectl run webserver2 --image myapp:v2
pod/webserver2 created


[root@k8s-master ~]# kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
webserver1   1/1     Running   0          8m27s
webserver2   1/1     Running   0          6m37s


[root@k8s-master ~]# kubectl get pods -o wide
NAME         READY   STATUS    RESTARTS   AGE   IP           NODE            NOMINATED NODE   READINESS GATES
webserver1   1/1     Running   0          2m    10.244.1.2   k8s-node1.org   <none>           <none>
webserver2   1/1     Running   0          10s   10.244.2.6   k8s-node2.org   <none>           <none>


[root@k8s-master ~]# kubectl get pods -o name
pod/webserver1
pod/webserver2

1.2.2kubectl常见command命令

命令分类命令翻译命令作用
基本命令create创建创建一个资源
edit编辑编辑一个资源
get获取获取一个资源
patch补丁更新更新一个资源
delete删除删除一个资源
explain解释展示资源文档
运行和调试run运行集群运行一个指定的镜像
expose暴露暴露资源为service
describe描述显示资源内部信息
logs日志输出容器pod中的日志
attach缠绕进入运行中的容器
exec执行执行容器中的一个命令
cp复制pod内外复制文件
rollout首次展示管理资源的发布
scale规模扩(缩)容pod的数量
autoscale自动调整自动调整pod数量
高级命令apply应用通过文件资源进行配置
label标签更新资源上的标签
其他命令cluster-info集群信息显示集群信息
version版本显示当前serverclient版本

1.2.3资源类型

kubernetes所有的内容都抽象为资源

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

1.2.4常用资源类型

资源分类资源名称缩写资源作用
集群级别资源nodesno集群组成部分
namespacesns隔离pod
pod资源podspo装载容器
pod资源控制器replicationcontrollersrc控制pod资源
replicasetsrs控制pod资源
deploymentsdeploy控制pod资源
daemonsetsds控制pod资源
jobs控制pod资源
cronjobscj控制pod资源
horizontalpodautoscalershpa控制pod资源
statefulsetssts控制pod资源
服务发现资源servicessvc统一pod对外接口
ingressing统一pod对外接口
存储资源volumeattachments存储
persistentvolumespv存储
persistentvolumeclaimspvc存储
配置资源configmapscm配置
secrets配置

基本命令示例

kubectl的详细说明地址:https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands

  • 显示集群版本
[root@k8s-master ~]# kubectl version
Client Version: v1.30.0
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.30.0
  • 显示集群信息
[root@k8s-master ~]# kubectl cluster-info
Kubernetes control plane is running at https://172.25.254.100:6443
CoreDNS is running at https://172.25.254.100:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
  • 创建一个名为webclusterdeployment控制器,控制器中pod数量为2
#先删除之前的pod
[root@k8s-master ~]# kubectl get pods -o wide
NAME         READY   STATUS    RESTARTS   AGE   IP           NODE            NOMINATE
webserver1   1/1     Running   0          16h   10.244.1.2   k8s-node1.org   <none>
webserver2   1/1     Running   0          16h   10.244.2.6   k8s-node2.org   <none>



[root@k8s-master ~]# kubectl delete pods webserver1 --force
[root@k8s-master ~]# kubectl delete pods webserver2 --force


[root@k8s-master ~]# kubectl get pods
No resources found in default namespace.
#创建一个名为`webcluster`的`deployment`控制器,控制器中`pod`数量为`2`
[root@k8s-master ~]# kubectl create deployment webcluster --image nginx --replicas 2
deployment.apps/webcluster created


[root@k8s-master ~]# kubectl get pods -o name
pod/webcluster-7c584f774b-9b67l
pod/webcluster-7c584f774b-d8xws


[root@k8s-master ~]# kubectl get pods -o wide
NAME                          READY   STATUS    RESTARTS   AGE   IP           NODE            NOMINATED NODE   READINESS GATES
webcluster-7c584f774b-9b67l   1/1     Running   0          79s   10.244.2.7   k8s-node2.org   <none>           <none>
webcluster-7c584f774b-d8xws   1/1     Running   0          79s   10.244.1.3   k8s-node1.org   <none>           <none>


#查看deployment控制器
[root@k8s-master ~]# kubectl get deployments.apps
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
webcluster   2/2     2            2           50s
  • 查看资源帮助explain
#等级式查看
[root@k8s-master ~]# kubectl explain deployment
GROUP:      apps
KIND:       Deployment
VERSION:    v1

DESCRIPTION:
    Deployment enables declarative updates for Pods and ReplicaSets.

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      <ObjectMeta>
    Standard object's metadata. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

  spec  <DeploymentSpec>
    Specification of the desired behavior of the Deployment.

  status        <DeploymentStatus>
    Most recently observed status of the Deployment.



[root@k8s-master ~]# kubectl explain deployment.metadata



[root@k8s-master ~]# kubectl explain deployment.spec
  • 编辑名为webclusterdeployment控制器,将pod数量改为3
#编辑名为webcluster的deployment控制器
[root@k8s-master ~]# kubectl edit deployments.apps webcluster
#会进入编辑状态
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2024-10-05T03:47:39Z"
  generation: 1
  labels:
    app: webcluster
  name: webcluster
  namespace: default
  resourceVersion: "27001"
  uid: a8bf27c5-c6bb-46d4-b4f7-4accfbb60e71
spec:
  progressDeadlineSeconds: 600
  replicas: 3     #将原来的2个pod改为3个pod
......
......
......
:wq
  • 发现改完立即生效
[root@k8s-master ~]# kubectl get deployments.apps webcluster
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
webcluster   3/3     3            3           18m


[root@k8s-master ~]# kubectl get pods -o name
pod/webcluster-7c584f774b-9b67l
pod/webcluster-7c584f774b-d8xws
pod/webcluster-7c584f774b-r48fd


[root@k8s-master ~]# kubectl get pods -o wide
NAME                          READY   STATUS    RESTARTS   AGE    IP           NODE            NOMINATED NODE   READINESS GATES
webcluster-7c584f774b-9b67l   1/1     Running   0          20m    10.244.2.7   k8s-node2.org   <none>           <none>
webcluster-7c584f774b-d8xws   1/1     Running   0          20m    10.244.1.3   k8s-node1.org   <none>           <none>
webcluster-7c584f774b-r48fd   1/1     Running   0          114s   10.244.2.8   k8s-node2.org   <none>           <none>
  • 利用补丁 patch更改控制器配置(编辑名为webclusterdeployment控制器,将pod数量改为4
[root@k8s-master ~]# kubectl patch deployments.apps webcluster -p '{"spec":{"replicas":4}}'
deployment.apps/webcluster patched


[root@k8s-master ~]# kubectl get deployments.apps
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
webcluster   4/4     4            4           26m


[root@k8s-master ~]# kubectl get pods -o name
pod/webcluster-7c584f774b-9b67l
pod/webcluster-7c584f774b-d8xws
pod/webcluster-7c584f774b-r48fd
pod/webcluster-7c584f774b-swst6


[root@k8s-master ~]# kubectl get pods -o wide
NAME                          READY   STATUS    RESTARTS   AGE    IP           NODE            NOMINATED NODE   READINESS GATES
webcluster-7c584f774b-9b67l   1/1     Running   0          27m    10.244.2.7   k8s-node2.org   <none>           <none>
webcluster-7c584f774b-d8xws   1/1     Running   0          27m    10.244.1.3   k8s-node1.org   <none>           <none>
webcluster-7c584f774b-r48fd   1/1     Running   0          9m7s   10.244.2.8   k8s-node2.org   <none>           <none>
webcluster-7c584f774b-swst6   1/1     Running   0          92s    10.244.1.4   k8s-node1.org   <none>           <none>
  • 控制器中删除pod

控制器删除一个pod后,k8s会根据数量再开一个pod

[root@k8s-master ~]# kubectl get pods -o wide
NAME                          READY   STATUS    RESTARTS   AGE    IP           NODE            NOMINATED NODE   READINESS GATES
webcluster-7c584f774b-9b67l   1/1     Running   0          27m    10.244.2.7   k8s-node2.org   <none>           <none>
webcluster-7c584f774b-d8xws   1/1     Running   0          27m    10.244.1.3   k8s-node1.org   <none>           <none>
webcluster-7c584f774b-r48fd   1/1     Running   0          9m7s   10.244.2.8   k8s-node2.org   <none>           <none>
webcluster-7c584f774b-swst6   1/1     Running   0          92s    10.244.1.4   k8s-node1.org   <none>           <none>
[root@k8s-master ~]# kubectl delete pods webcluster-7c584f774b-9b67l
pod "webcluster-7c584f774b-9b67l" deleted
[root@k8s-master ~]# kubectl get pods -o wide
NAME                          READY   STATUS    RESTARTS   AGE     IP           NODE            NOMINATED NODE   READINESS GATES
webcluster-7c584f774b-d8xws   1/1     Running   0          31m     10.244.1.3   k8s-node1.org   <none>           <none>
webcluster-7c584f774b-r48fd   1/1     Running   0          13m     10.244.2.8   k8s-node2.org   <none>           <none>
webcluster-7c584f774b-swst6   1/1     Running   0          5m25s   10.244.1.4   k8s-node1.org   <none>           <none>
webcluster-7c584f774b-tx55p   1/1     Running   0          5s      10.244.2.9   k8s-node2.org   <none>           <none>
  • 直接删除控制器控制器控制的所有pod都会被删除
[root@k8s-master ~]# kubectl delete deployments.apps webcluster
deployment.apps "webcluster" deleted

[root@k8s-master ~]# kubectl get deployments.apps
No resources found in default namespace.

[root@k8s-master ~]# kubectl get pods -o wide
No resources found in default namespace.

运行和调试命令示例

  • 首先要保证一个纯净的实验环境
#发现没有pod
[root@k8s-master ~]# kubectl get pods
No resources found in default namespace.
  • 运行一个名为testpodpod,该pod不属于任何控制器
[root@k8s-master ~]# kubectl run testpod --image nginx
pod/testpod created


[root@k8s-master ~]# kubectl get pods -o name
pod/testpod


[root@k8s-master ~]# kubectl get pods -o wide
NAME      READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE   READINESS GATES
testpod   1/1     Running   0          9s    10.244.2.10   k8s-node2.org   <none>           <none>
  • 端口暴露
[root@k8s-master ~]# kubectl get services
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP    18h


#--port指定pod中的端口,--target-port指定容器中的服务端口
[root@k8s-master ~]# kubectl expose pod testpod --port 8080 --target-port 80
service/testpod exposed


[root@k8s-master ~]# kubectl get services
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP    18h
testpod      ClusterIP   10.99.119.189   <none>        8080/TCP   8s
#访问10.244.2.12
[root@k8s-master ~]# curl 10.244.2.12
<!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>


#访问10.99.119.189:8080
[root@k8s-master ~]# curl 10.99.119.189:8080
<!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>
  • 查看运行中pod详细信息
[root@k8s-master ~]# kubectl get pods -o wide
NAME      READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE   READINESS GATES
testpod   1/1     Running   0          10m   10.244.2.12   k8s-node2.org   <none>           <none>


[root@k8s-master ~]# kubectl describe pods testpod
Name:             testpod
Namespace:        default
Priority:         0
Service Account:  default
Node:             k8s-node2.org/172.25.254.20
Start Time:       Sat, 05 Oct 2024 00:45:53 -0400
Labels:           run=testpod
Annotations:      <none>
Status:           Running
IP:               10.244.2.12
IPs:
  IP:  10.244.2.12
Containers:
  testpod:
    Container ID:   docker://13361a3a29b394fa0049c28405a76a686a26a7c9a1e1fddbcdc4312f2698156a
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:127262f8c4c716652d0e7863bba3b8c45bc9214a57d13786c854272102f7c945
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sat, 05 Oct 2024 00:45:54 -0400
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-tzfw6 (ro)
Conditions:
  Type                        Status
  PodReadyToStartContainers   True
  Initialized                 True
  Ready                       True
  ContainersReady             True
  PodScheduled                True
Volumes:
  kube-api-access-tzfw6:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  10m   default-scheduler  Successfully assigned default/testpod to k8s-node2.org
  Normal  Pulling    10m   kubelet            Pulling image "nginx"
  Normal  Pulled     10m   kubelet            Successfully pulled image "nginx" in 281ms (281ms including waiting). Image size: 187694648 bytes.
  Normal  Created    10m   kubelet            Created container testpod
  Normal  Started    10m   kubelet            Started container testpod
  • 查看资源日志
[root@k8s-master ~]# kubectl logs
daemonsets/              pods/                    services/
deployments/             replicasets/             statefulsets/
jobs/                    replicationcontrollers/  testpod
[root@k8s-master ~]# kubectl logs pods/testpod
......
......
......
  • 运行交互pod
[root@k8s-master ~]# kubectl run -it testpod1 --image busybox
If you don't see a command prompt, try pressing enter.
/ #
/ #
/ # ls
bin    dev    etc    home   lib    lib64  proc   root   sys    tmp    usr    var
/ # exit      #退出交互式,不停止pod


[root@k8s-master ~]# kubectl get pods -o wide
NAME       READY   STATUS    RESTARTS      AGE   IP            NODE            NOMINATED NODE   READINESS GATES
testpod    1/1     Running   0             20m   10.244.2.12   k8s-node2.org   <none>           <none>
testpod1   1/1     Running   1 (24s ago)   36s   10.244.1.6    k8s-node1.org   <none>           <none>


#再次进入容器
[root@k8s-master ~]# kubectl attach -it  pods/testpod1
If you don't see a command prompt, try pressing enter.
/ #
/ #
/ # ls
bin    dev    etc    home   lib    lib64  proc   root   sys    tmp    usr    var
/ # exit 或  ctrl+p+q退出不停止pod


[root@k8s-master ~]# kubectl get pods -o wide
NAME       READY   STATUS    RESTARTS       AGE     IP            NODE            NOMINATED NODE   READINESS GATES
testpod    1/1     Running   0              24m     10.244.2.12   k8s-node2.org   <none>           <none>
testpod1   1/1     Running   2 (3m9s ago)   4m30s   10.244.1.6    k8s-node1.org   <none>           <none>
  • 在已经运行的pod中运行容器中的指定命令
[root@k8s-master ~]# kubectl exec -it pods/testpod1 ifconfig
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
eth0      Link encap:Ethernet  HWaddr 12:C1:23:80:08:BA
          inet addr:10.244.1.6  Bcast:10.244.1.255  Mask:255.255.255.0
          inet6 addr: fe80::10c1:23ff:fe80:8ba/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1450  Metric:1
          RX packets:15 errors:0 dropped:0 overruns:0 frame:0
          TX packets:13 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:2148 (2.0 KiB)  TX bytes:962 (962.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          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)
  • 复制master宿主机文件到pod中的容器中
[root@k8s-master ~]# kubectl cp anaconda-ks.cfg   testpod1:/


[root@k8s-master ~]# kubectl  exec  -it  pods/testpod1  /bin/sh
/ # ls
anaconda-ks.cfg  home             root             var
bin              lib              sys
dev              lib64            tmp
etc              proc             usr
/ # touch file1
/ # ls
anaconda-ks.cfg  file1            proc             usr
bin              home             root             var
dev              lib              sys
etc              lib64            tmp
/ # echo hello world > file1
/ # cat file1
hello world111
  • 复制pod容器中的文件master宿主机中
[root@k8s-master ~]# kubectl cp  testpod1:/file1   /mnt/file
tar: removing leading '/' from member names
[root@k8s-master ~]# cd /mnt/
[root@k8s-master mnt]# ls
file
[root@k8s-master mnt]# cat file
hello world111

高级命令示例

  • 利用命令生成yaml格式文件
[root@k8s-master ~]# mkdir huazi
[root@k8s-master ~]# cd huazi/
[root@k8s-master huazi]#

首先要确保一个纯净的实验环境

[root@k8s-master huazi]# kubectl get pods
NAME       READY   STATUS    RESTARTS      AGE
testpod    1/1     Running   0             43m
testpod1   1/1     Running   2 (22m ago)   23m


[root@k8s-master huazi]# kubectl delete pods testpod
pod "testpod" deleted
[root@k8s-master huazi]# kubectl delete pods testpod1 --force
pod "testpod1" deleted
  • --drg-run=client仅尝试不运行,是一个固定写法
#仅尝试,不运行
[root@k8s-master huazi]# kubectl create deployment webserver --image nginx --dry-run=client -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: webserver
  name: webserver
spec:
  replicas: 1
  selector:
    matchLabels:
      app: webserver
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: webserver
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}
  • 导入文件
#创建一个控制器文件
[root@k8s-master huazi]# kubectl create deployment webserver --image nginx --dry-run=client -o yaml > webserver.yml
[root@k8s-master huazi]# ls
webserver.yml
#对文件进行简单的修改
[root@k8s-master huazi]# vim  webserver.yml
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: webserver
  name: webserver
spec:
  replicas: 2    #修改为2个pod
  selector:
    matchLabels:
      app: webserver
  template:
    metadata:
      labels:
        app: webserver
    spec:
      containers:
      - image: nginx
        name: nginx
  • 应用文件
#这个文件是一个控制器文件
[root@k8s-master huazi]# kubectl apply -f webserver.yml
deployment.apps/webserver created


[root@k8s-master huazi]# kubectl get deployments.apps
NAME        READY   UP-TO-DATE   AVAILABLE   AGE
webserver   2/2     2            2           27s


[root@k8s-master huazi]# kubectl get pods -o name
pod/webserver-7bc769cd4c-mg9kl
pod/webserver-7bc769cd4c-nl7q2


[root@k8s-master huazi]# kubectl get pods -o wide
NAME                         READY   STATUS    RESTARTS   AGE     IP            NODE            NOMINATED NODE   READINESS GATES
webserver-7bc769cd4c-mg9kl   1/1     Running   0          2m10s   10.244.2.13   k8s-node2.org   <none>           <none>
webserver-7bc769cd4c-nl7q2   1/1     Running   0          2m10s   10.244.1.7    k8s-node1.org   <none>           <none>
  • 删除控制器文件
[root@k8s-master huazi]# kubectl delete -f webserver.yml
deployment.apps "webserver" deleted


[root@k8s-master huazi]# kubectl get deployments.apps
No resources found in default namespace.


[root@k8s-master huazi]# kubectl get pods -o wide
No resources found in default namespace.
  • 管理资源标签
#这个是没有控制的pod
[root@k8s-master huazi]# kubectl run webserver --image nginx
pod/webserver created


[root@k8s-master huazi]# kubectl get pods -o wide
NAME        READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE   READINESS GATES
webserver   1/1     Running   0          12s   10.244.2.15   k8s-node2.org   <none>           <none>


[root@k8s-master huazi]# kubectl get pods --show-labels
NAME        READY   STATUS    RESTARTS   AGE   LABELS
webserver   1/1     Running   0          50s   run=webserver
  • 更改标签
  • --overwrite覆盖
[root@k8s-master huazi]# kubectl label pods webserver run=web --overwrite
pod/webserver labeled


[root@k8s-master huazi]# kubectl get pods --show-labels
NAME        READY   STATUS    RESTARTS   AGE     LABELS
webserver   1/1     Running   0          3m48s   run=web
  • 添加标签
  • 通过键值对添加即可
[root@k8s-master huazi]# kubectl label pods webserver app=web1
pod/webserver labeled


[root@k8s-master huazi]# kubectl get pods --show-labels
NAME        READY   STATUS    RESTARTS   AGE     LABELS
webserver   1/1     Running   0          5m33s   app=web1,run=web
  • 删除标签
[root@k8s-master huazi]# kubectl label pods webserver app-
pod/webserver unlabeled


[root@k8s-master huazi]# kubectl get pods --show-labels
NAME        READY   STATUS    RESTARTS   AGE     LABELS
webserver   1/1     Running   0          6m48s   run=web
  • 创建一个控制器pod
#先删除之前的pod
[root@k8s-master huazi]# kubectl delete pods webserver
pod "webserver" deleted
[root@k8s-master huazi]# kubectl get pods
No resources found in default namespace.
[root@k8s-master huazi]# kubectl create deployment webserver --image nginx --dry-run=client -o yaml > web-label.yaml
[root@k8s-master huazi]# ls
web-label.yaml  webserver.yml

[root@k8s-master huazi]# vim web-label.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: webserver
  name: webserver
spec:
  replicas: 2   #修改为2个pod
  selector:
    matchLabels:
      app: webserver
  template:
    metadata:
      labels:
        app: webserver
    spec:
      containers:
      - image: nginx
        name: nginx
[root@k8s-master huazi]# kubectl apply -f web-label.yaml
deployment.apps/webserver created


[root@k8s-master huazi]# kubectl get deployments.apps
NAME        READY   UP-TO-DATE   AVAILABLE   AGE
webserver   2/2     2            2           7s


[root@k8s-master huazi]# kubectl get pods --show-labels
NAME                         READY   STATUS    RESTARTS   AGE   LABELS
webserver-7bc769cd4c-bnklx   1/1     Running   0          44s   app=webserver,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f   1/1     Running   0          44s   app=webserver,pod-template-hash=7bc769cd4c

修改一个控制器pod上的一个标签

[root@k8s-master huazi]# kubectl get pods --show-labels
NAME                         READY   STATUS    RESTARTS   AGE   LABELS
webserver-7bc769cd4c-bnklx   1/1     Running   0          44s   app=webserver,pod-tem                                                                                                       plate-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f   1/1     Running   0          44s   app=webserver,pod-tem                                                                                                       plate-hash=7bc769cd4c


[root@k8s-master huazi]# kubectl label pods webserver-7bc769cd4c-bnklx app=lee --over                                                                                                       write
pod/webserver-7bc769cd4c-bnklx labeled
[root@k8s-master huazi]# kubectl get pods --show-labels                                                                                                                                     NAME                         READY   STATUS    RESTARTS   AGE     LABELS
webserver-7bc769cd4c-bnklx   1/1     Running   0          3m14s   app=lee,pod-templat                                                                                                       e-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f   1/1     Running   0          3m14s   app=webserver,pod-t                                                                                                       emplate-hash=7bc769cd4c
webserver-7bc769cd4c-cgzcq   1/1     Running   0          3s      app=webserver,pod-t                                                                                                       emplate-hash=7bc769cd4c

我们发现k8s又起了一个新的pod

当我们删除另一个标签后,k8s又起了一个新的pod

[root@k8s-master huazi]# kubectl label pods webserver-7bc769cd4c-cdj8f pod-template-hash-
pod/webserver-7bc769cd4c-cdj8f unlabeled
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME                         READY   STATUS    RESTARTS   AGE     LABELS
webserver-7bc769cd4c-bnklx   1/1     Running   0          5m22s   app=lee,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f   1/1     Running   0          5m22s   app=webserver
webserver-7bc769cd4c-cgzcq   1/1     Running   0          2m11s   app=webserver,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-zq5mw   1/1     Running   0          5s      app=webserver,pod-template-hash=7bc769cd4c

当我们修改回来原来的标签后,k8s又把之前新的pod删除

[root@k8s-master huazi]# kubectl label pods webserver-7bc769cd4c-bnklx app=webserver --overwrite
pod/webserver-7bc769cd4c-bnklx labeled
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME                         READY   STATUS    RESTARTS   AGE     LABELS
webserver-7bc769cd4c-cdj8f   1/1     Running   0          8m45s   app=webserver
webserver-7bc769cd4c-cgzcq   1/1     Running   0          5m34s   app=webserver,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-zq5mw   1/1     Running   0          3m28s   app=webserver,pod-template-hash=7bc769cd4c

总结

所以我们发现,k8s是通过标签去记录pod的数量,如果有多个标签,且多个标签必须一致。如果不一致,则k8s会根据pod的数量重新启动相应pod

其他命令示例

[root@k8s-master huazi]# kubectl cluster-info
Kubernetes control plane is running at https://172.25.254.100:6443
CoreDNS is running at https://172.25.254.100:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
[root@k8s-master huazi]# kubectl version
Client Version: v1.30.0
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.30.0

createapply区别案例

[root@k8s-master huazi]# kubectl run testpod1 --image myapp:v1 --dry-run=client -o yaml > testpod1.yml

[root@k8s-master huazi]# ls
testpod1.yml

[root@k8s-master huazi]# vim testpod1.yml
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: testpod1
  name: testpod1
spec:
  containers:
  - image: myapp:v1
    name: testpod1



[root@k8s-master huazi]# kubectl create -f testpod1.yml
pod/testpod1 created
[root@k8s-master huazi]# kubectl get pods -o wide
NAME       READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE   READINESS GATES
testpod1   1/1     Running   0          8s    10.244.1.10   k8s-node1.org   <none>           <none>

[root@k8s-master huazi]# curl 10.244.1.10
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>

[root@k8s-master huazi]# vim testpod1.yml
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: testpod1
  name: testpod1
spec:
  containers:
  - image: myapp:v2   #将版本改为v2
    name: testpod1


#发现使用create更新不了
[root@k8s-master huazi]# kubectl create -f testpod1.yml
Error from server (AlreadyExists): error when creating "testpod1.yml": pods "testpod1" already exists


#使用apply可以更新
[root@k8s-master huazi]# kubectl apply -f testpod1.yml

[root@k8s-master huazi]# kubectl get pods -o wide
NAME       READY   STATUS    RESTARTS      AGE     IP            NODE            NOMINATED NODE   READINESS GATES
testpod1   1/1     Running   1 (23s ago)   3m13s   10.244.1.10   k8s-node1.org   <none>           <none>


[root@k8s-master huazi]# curl 10.244.1.10
Hello MyApp | Version: v2 | <a href="hostname.html">Pod Name</a>
  • 所以create只能建立,不能更新apply可以更新

显示命名空间

[root@k8s-master huazi]# kubectl -n
default          kube-node-lease  kube-system
kube-flannel     kube-public

查看命名空间中的pod

  • 查看所有命名空间中的pod
  • --all-namespaces
[root@k8s-master huazi]# kubectl get pods --all-namespaces
NAMESPACE      NAME                                     READY   STATUS    RESTARTS        AGE
default        testpod1                                 1/1     Running   1 (4m54s ago)   7m44s
kube-flannel   kube-flannel-ds-m7ksl                    1/1     Running   0               22h
kube-flannel   kube-flannel-ds-q55gr                    1/1     Running   0               22h
kube-flannel   kube-flannel-ds-twvv4                    1/1     Running   1 (21h ago)     22h
kube-system    coredns-6c7f6478d8-gplcq                 1/1     Running   0               23h
kube-system    coredns-6c7f6478d8-vcqg9                 1/1     Running   0               23h
kube-system    etcd-k8s-master.org                      1/1     Running   0               23h
kube-system    kube-apiserver-k8s-master.org            1/1     Running   0               23h
kube-system    kube-controller-manager-k8s-master.org   1/1     Running   0               23h
kube-system    kube-proxy-2dbz2                         1/1     Running   1 (21h ago)     22h
kube-system    kube-proxy-fcnpc                         1/1     Running   0               23h
kube-system    kube-proxy-jwn8w                         1/1     Running   0               22h
kube-system    kube-scheduler-k8s-master.org            1/1     Running   0               23h
  • 查看默认命名空间中的pod
[root@k8s-master huazi]# kubectl get pods
NAME       READY   STATUS    RESTARTS       AGE
testpod1   1/1     Running   1 (7m4s ago)   9m54s
[root@k8s-master huazi]# kubectl -n
default          kube-node-lease  kube-system
kube-flannel     kube-public
[root@k8s-master huazi]# kubectl -n default get pods
NAME       READY   STATUS    RESTARTS        AGE
testpod1   1/1     Running   1 (7m58s ago)   10m

如何对外暴露端口

[root@k8s-master huazi]# kubectl run web --image myapp:v1
pod/web created

[root@k8s-master huazi]# kubectl get pods -o wide
NAME   READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE   READINESS GATES
web    1/1     Running   0          32s   10.244.1.11   k8s-node1.org   <none>           <none>
#10.244.1.11是pod的ip地址


[root@k8s-master huazi]# curl 10.244.1.11
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
[root@k8s-master huazi]# kubectl expose pod web --port 8080 --target-port 80
service/web exposed
#--port指定pod中的端口,
#--target-port指定容器中的服务端口

[root@k8s-master huazi]# kubectl get services
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP    23h
web          ClusterIP   10.108.123.93   <none>        8080/TCP   19s
#10.108.123.93这个ip是service的ip地址
#当访问10.108.123.93:8080端口时,转到10.244.1.11的80端口

[root@k8s-master huazi]# curl 10.108.123.93:8080
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
[root@k8s-master huazi]# kubectl edit services web
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2024-10-05T09:21:02Z"
  labels:
    run: web
  name: web
  namespace: default
  resourceVersion: "57432"
  uid: 33ea0201-e8b2-42ea-874d-2aa2b8e20455
spec:
  clusterIP: 10.108.123.93
  clusterIPs:
  - 10.108.123.93
  internalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 80
  selector:
    run: web
  sessionAffinity: None
  type: NodePort   #修改类型为NodePort
status:
  loadBalancer: {}


[root@k8s-master huazi]# kubectl get services
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP          23h
web          NodePort    10.108.123.93   <none>        8080:31340/TCP   9m51s


[root@k8s-master huazi]# kubectl get pods -o wide
NAME   READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE   READINESS GATES
web    1/1     Running   0          14m   10.244.1.11   k8s-node1.org   <none>           <none>


[root@k8s-master huazi]# curl k8s-node1.org:31340
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>


[root@k8s-master huazi]# curl 172.25.254.10:31340
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>

在这里插入图片描述
发现可以对外访问

[root@k8s-master huazi]# kubectl explain service.spec
......
......
......
    Possible enum values:
     - `"ClusterIP"` means a service will only be accessible inside the cluster,
    via the cluster IP.
     - `"ExternalName"` means a service consists of only a reference to an
    external name that kubedns or equivalent will return as a CNAME record, with
    no exposing or proxying of any pods involved.
     - `"LoadBalancer"` means a service will be exposed via an external load
    balancer (if the cloud provider supports it), in addition to 'NodePort'
    type.
     - `"NodePort"` means a service will be exposed on one port of every node,
    in addition to 'ClusterIP' type.

查看某一个pod的详细信息

[root@k8s-master huazi]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
web    1/1     Running   0          20m
[root@k8s-master huazi]# kubectl describe pods web
Name:             web
Namespace:        default
Priority:         0
Service Account:  default
Node:             k8s-node1.org/172.25.254.10
Start Time:       Sat, 05 Oct 2024 05:17:53 -0400
Labels:           run=web
Annotations:      <none>
Status:           Running
IP:               10.244.1.11
IPs:
  IP:  10.244.1.11
Containers:
  web:
    Container ID:   docker://d1f4ea79ffe996f292f2b0af787afdf7e235496b4b4a89878005a3fed662426f
    Image:          myapp:v1
    Image ID:       docker-pullable://myapp@sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sat, 05 Oct 2024 05:17:54 -0400
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-mv6b4 (ro)
Conditions:
  Type                        Status
  PodReadyToStartContainers   True
  Initialized                 True
  Ready                       True
  ContainersReady             True
  PodScheduled                True
Volumes:
  kube-api-access-mv6b4:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  20m   default-scheduler  Successfully assigned default/web to k8s-node1.org
  Normal  Pulled     20m   kubelet            Container image "myapp:v1" already present on machine
  Normal  Created    20m   kubelet            Created container web
  Normal  Started    20m   kubelet            Started container web
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

^~^前行者~~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值