Kubernetes Controllers

replicaSet

[root@master30 ~ 10:34:51]# kubectl create ns controllers
namespace/controllers created
[root@master30 ~ 10:34:58]# kubectl config set-context --current --namespace controllers
Context "kubernetes-admin@kubernetes" modified.
[root@master30 ~ 10:35:04]# vim rs.yaml
[root@master30 ~ 10:35:12]# kubectl apply -f rs.yaml
replicaset.apps/nginx created
[root@master30 ~ 10:35:20]# kubectl get rs
NAME    DESIRED   CURRENT   READY   AGE
nginx   3         3         3       5s
[root@master30 ~ 10:35:25]# kubectl get pods
NAME          READY   STATUS    RESTARTS   AGE
nginx-mkq4z   1/1     Running   0          14s
nginx-qqfnk   1/1     Running   0          14s
nginx-t75zb   1/1     Running   0          14s
[root@master30 ~ 10:35:41]# kubectl describe pod nginx-mkq4z |grep Controlled
Controlled By:  ReplicaSet/nginx
[root@master30 ~ 10:36:00]# kubectl delete rs nginx --cascade=orphan#只删rs不删pod
replicaset.apps "nginx" deleted
[root@master30 ~ 10:37:20]# kubectl delete pod -l app-nginx
No resources found

Deployment管理

[root@master30 ~ 10:37:38]# kubectl create deployment web --image=docker.io/library/nginx:1.27 --replicas=2
deployment.apps/web created
[root@master30 ~ 11:11:59]# kubectl get all
NAME                       READY   STATUS              RESTARTS   AGE
pod/nginx-mkq4z            1/1     Running             0          37m
pod/nginx-qqfnk            1/1     Running             0          37m
pod/nginx-t75zb            1/1     Running             0          37m
pod/web-768f99776c-b7w4j   0/1     ContainerCreating   0          29s
pod/web-768f99776c-wfssh   0/1     ContainerCreating   0          29s

NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/web   0/2     2            0           29s

NAME                             DESIRED   CURRENT   READY   AGE
replicaset.apps/web-768f99776c   2         2         0       29s
[root@master30 ~ 11:12:28]# kubectl get all
NAME                       READY   STATUS    RESTARTS   AGE
pod/nginx-mkq4z            1/1     Running   0          37m
pod/nginx-qqfnk            1/1     Running   0          37m
pod/nginx-t75zb            1/1     Running   0          37m
pod/web-768f99776c-b7w4j   1/1     Running   0          71s
pod/web-768f99776c-wfssh   1/1     Running   0          71s

NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/web   2/2     2            2           71s

NAME                             DESIRED   CURRENT   READY   AGE
replicaset.apps/web-768f99776c   2         2         2       71s
[root@master30 ~ 11:13:11]# kubectl describe replicasets.apps web-768f99776c |grep Controlled
Controlled By:  Deployment/web
[root@master30 ~ 11:14:52]# kubectl describe pod web-768f99776c-b7w4j |grep Controlled
Controlled By:  ReplicaSet/web-768f99776c
[root@master30 ~ 11:16:15]# kubectl create deployment web --image=docker.io/library/nginx:1.27 --replicas=2 --dry-run=client -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: web
  name: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: web
    spec:
      containers:
      - image: docker.io/library/nginx:1.27
        name: nginx
        resources: {}
status: {}
[root@master30 ~ 11:18:07]# vim deployment-web.yaml
[root@master30 ~ 11:19:24]# vim deployment-web.yaml
[root@master30 ~ 11:19:52]# vim deployment-web.yaml
[root@master30 ~ 11:19:59]# kubectl apply -f deployment-web.yaml
Warning: resource deployments/web is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically.
deployment.apps/web configured
[root@master30 ~ 11:20:18]# kubectl edit deployments.apps web
Edit cancelled, no changes made.
[root@master30 ~ 11:21:19]# kubectl delete deployments.apps web
deployment.apps "web" deleted
[root@master30 ~ 11:22:19]# kubectl apply -f deployment-web.yaml
deployment.apps/web created
[root@master30 ~ 11:22:28]# kubectl delete deployments.apps web --cascade=orphan
deployment.apps "web" deleted
[root@master30 ~ 11:23:10]# kubectl delete all -l app=web
pod "web-84f8fcb58b-dhps6" deleted
pod "web-84f8fcb58b-ldhtj" deleted
replicaset.apps "web-84f8fcb58b" deleted
[root@master30 ~ 11:24:57]# kubectl get all -l app=web
No resources found in controllers namespace.

水平伸缩

[root@master30 ~ 11:25:04]# kubectl create deployment web --image=docker.io/library/nginx:1.27 --replicas=2
deployment.apps/web created
[root@master30 ~ 11:27:34]# kubectl scale deployment web --replicas=3
deployment.apps/web scaled
[root@master30 ~ 11:28:11]# kubectl get pod
NAME                   READY   STATUS    RESTARTS   AGE
nginx-mkq4z            1/1     Running   0          53m
nginx-qqfnk            1/1     Running   0          53m
nginx-t75zb            1/1     Running   0          53m
web-768f99776c-4f2pp   1/1     Running   0          53s
web-768f99776c-5nq62   1/1     Running   0          16s
web-768f99776c-wqbm5   1/1     Running   0          53s

健壮性测试

[root@master30 ~ 11:25:04]# kubectl create deployment web --image=docker.io/library/nginx:1.27 --replicas=2
deployment.apps/web created
[root@master30 ~ 11:27:34]# kubectl scale deployment web --replicas=3
deployment.apps/web scaled
[root@master30 ~ 11:28:11]# kubectl get pod
NAME                   READY   STATUS    RESTARTS   AGE
nginx-mkq4z            1/1     Running   0          53m
nginx-qqfnk            1/1     Running   0          53m
nginx-t75zb            1/1     Running   0          53m
web-768f99776c-4f2pp   1/1     Running   0          53s
web-768f99776c-5nq62   1/1     Running   0          16s
web-768f99776c-wqbm5   1/1     Running   0          53s

版本控制

[root@master30 ~ 11:43:05]# kubectl set image deployment/web nginx=docker.io/library/nginx:1.28 --record
Flag --record has been deprecated, --record will be removed in the future
deployment.apps/web image updated
[root@master30 ~ 11:44:51]# kubectl rollout history deployment web
deployment.apps/web
REVISION  CHANGE-CAUSE
1         <none>
2         kubectl set image deployment/web nginx=docker.io/library/nginx:1.28 --record=true

[root@master30 ~ 11:45:46]# kubectl rollout undo deployment web --to-revision=1
deployment.apps/web rolled back

日志记录

[root@master30 ~ 11:45:46]# kubectl rollout undo deployment web --to-revision=1
deployment.apps/web rolled back
[root@master30 ~ 11:45:54]# vim monitor_pod_numbers
[root@master30 ~ 11:47:29]# chmod +x monitor_pod_numbers
[root@master30 ~ 11:48:39]# ./monitor_pod_numbers

[root@master30 ~ 11:13:54]# tail -f output.log
6 Running
===================
6 Running
===================
6 Running
===================
6 Running
===================
6 Running
===================
6 Running
===================
6 Running
===================
6 Running

DaemonSet

[root@master30 ~ 13:35:21]# vim daemonset.yaml
[root@master30 ~ 13:54:21]# kubectl apply -f daemonset.yaml
daemonset.apps/busybox created
[root@master30 ~ 13:54:35]# kubectl get pod -o wide
NAME                   READY   STATUS             RESTARTS   AGE     IP               NODE                NOMINATED NODE   READINESS GATES
busybox-scv94          0/1     ImagePullBackOff   0          17s     10.224.125.144   worker32.my.cloud   <none>           <none>
busybox-xnxb7          0/1     ErrImagePull       0          17s     10.224.15.81     worker31.my.cloud   <none>           <none>
nginx-mkq4z            1/1     Running            0          3h19m   10.224.125.138   worker32.my.cloud   <none>           <none>
nginx-qqfnk            1/1     Running            0          3h19m   10.224.125.139   worker32.my.cloud   <none>           <none>
nginx-t75zb            1/1     Running            0          3h19m   10.224.15.74     worker31.my.cloud   <none>           <none>
web-768f99776c-4f2pp   1/1     Running            0          147m    10.224.15.78     worker31.my.cloud   <none>           <none>
web-768f99776c-5nq62   1/1     Running            0          146m    10.224.15.79     worker31.my.cloud   <none>           <none>
web-768f99776c-wqbm5   1/1     Running            0          147m    10.224.125.143   worker32.my.cloud   <none>           <none>
[root@master30 ~ 13:54:52]# kubectl describe pod busybox-scv94 | grep -A 5 "Failed to pull"
  Warning  Failed     37s (x3 over 82s)  kubelet            Failed to pull image "hub.laoma.cloud/library/busybox": failed to pull and unpack image "hub.laoma.cloud/library/busybox:latest": failed to resolve reference "hub.laoma.cloud/library/busybox:latest": failed to do request: Head "https://hub.laoma.cloud/v2/library/busybox/manifests/latest": dial tcp 192.168.42.201:443: connect: connection refused
  Warning  Failed     37s (x3 over 82s)  kubelet            Error: ErrImagePull
  Normal   BackOff    9s (x4 over 81s)   kubelet            Back-off pulling image "hub.laoma.cloud/library/busybox"
  Warning  Failed     9s (x4 over 81s)   kubelet            Error: ImagePullBackOff
[root@master30 ~ 13:56:00]# scp /etc/containerd/config.toml root@10.1.8.31:/etc/containerd/
scp /etc/containerd/config.toml root@10.1.8.32:/etc/containerd/
config.toml                                                             100% 9009     3.1MB/s   00:00
config.toml                                                             100% 9009     3.5MB/s   00:00
[root@master30 ~ 13:59:15]# ssh root@10.1.8.31 "systemctl restart containerd"
ssh root@10.1.8.32 "systemctl restart containerd"
[root@master30 ~ 13:59:25]# kubectl delete pod busybox-scv94 busybox-xnxb7
pod "busybox-scv94" deleted
pod "busybox-xnxb7" deleted
[root@master30 ~ 13:59:36]# kubectl get pods -o wide | grep busybox
busybox-7gzlb          1/1     Running   0          9s      10.224.15.82     worker31.my.cloud   <none>           <none>
busybox-x2qtc          1/1     Running   0          8s      10.224.125.145   worker32.my.cloud   <none>           <none>
[root@master30 ~ 13:59:44]# kubectl get ds
NAME      DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
busybox   2         2         2       2            2           <none>          5m38s
[root@master30 ~ 14:00:45]# kubectl describe node master30.my.cloud |grep Taints
Taints:             node-role.kubernetes.io/control-plane:NoSchedule
[root@master30 ~ 14:01:49]# kubectl apply -f daemonset.yaml
daemonset.apps/busybox unchanged
[root@master30 ~ 14:02:03]# kubectl get pod -o wide
NAME                   READY   STATUS    RESTARTS   AGE     IP               NODE                NOMINATED NODE   READINESS GATES
busybox-7gzlb          1/1     Running   0          2m38s   10.224.15.82     worker31.my.cloud   <none>           <none>
busybox-x2qtc          1/1     Running   0          2m37s   10.224.125.145   worker32.my.cloud   <none>           <none>
nginx-mkq4z            1/1     Running   0          3h26m   10.224.125.138   worker32.my.cloud   <none>           <none>
nginx-qqfnk            1/1     Running   0          3h26m   10.224.125.139   worker32.my.cloud   <none>           <none>
nginx-t75zb            1/1     Running   0          3h26m   10.224.15.74     worker31.my.cloud   <none>           <none>
web-768f99776c-4f2pp   1/1     Running   0          154m    10.224.15.78     worker31.my.cloud   <none>           <none>
web-768f99776c-5nq62   1/1     Running   0          154m    10.224.15.79     worker31.my.cloud   <none>           <none>
web-768f99776c-wqbm5   1/1     Running   0          154m    10.224.125.143   worker32.my.cloud   <none>           <none>
[root@master30 ~ 14:02:13]# kubectl get ds
NAME      DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
busybox   2         2         2       2            2           <none>          7m46s
[root@master30 ~ 14:02:21]# kubectl taint node master30.my.cloud node-role.kubernetes.io/control-plane-   node/master30.my.cloud untainted
[root@master30 ~ 14:03:13]# kubectl get ds
NAME      DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
busybox   3         3         3       3            3           <none>          8m44s
[root@master30 ~ 14:03:19]# kubectl taint node master30.my.cloud node-role.kubernetes.io/control-plane:NoSchedule
node/master30.my.cloud tainted
[root@master30 ~ 14:03:40]# kubectl get ds
NAME      DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
busybox   2         2         2       2            2           <none>          9m16s
[root@master30 ~ 14:03:51]# kubectl delete pod busybox-x2qtc
pod "busybox-x2qtc" deleted
[root@master30 ~ 14:04:59]# kubectl get pod -o wide
NAME                   READY   STATUS    RESTARTS   AGE     IP               NODE                NOMINATED NODE   READINESS GATES
busybox-2qb9l          1/1     Running   0          119s    10.224.104.88    master30.my.cloud   <none>           <none>
busybox-7gzlb          1/1     Running   0          5m37s   10.224.15.82     worker31.my.cloud   <none>           <none>
busybox-j9d9f          1/1     Running   0          14s     10.224.125.146   worker32.my.cloud   <none>           <none>
nginx-mkq4z            1/1     Running   0          3h29m   10.224.125.138   worker32.my.cloud   <none>           <none>
nginx-qqfnk            1/1     Running   0          3h29m   10.224.125.139   worker32.my.cloud   <none>           <none>
nginx-t75zb            1/1     Running   0          3h29m   10.224.15.74     worker31.my.cloud   <none>           <none>
web-768f99776c-4f2pp   1/1     Running   0          157m    10.224.15.78     worker31.my.cloud   <none>           <none>
web-768f99776c-5nq62   1/1     Running   0          157m    10.224.15.79     worker31.my.cloud   <none>           <none>
web-768f99776c-wqbm5   1/1     Running   0          157m    10.224.125.143   worker32.my.cloud   <none>           <none>
[root@master30 ~ 14:05:12]# kubectl delete daemonsets.apps busybox
daemonset.apps "busybox" deleted

Job

[root@master30 ~ 14:31:20]# kubectl create job myjob --image=hub.laoma.cloud/library/busybox --echo hello k8s job!
error: unknown flag: --echo
See 'kubectl create job --help' for usage.
[root@master30 ~ 14:32:22]# kubectl create job myjob --image=hub.laoma.cloud/library/busybox -- echo hello k8s job!
job.batch/myjob created
[root@master30 ~ 14:34:35]# kubectl get all
NAME              READY   STATUS      RESTARTS   AGE
pod/myjob-rqhf2   0/1     Completed   0          95s

NAME              STATUS     COMPLETIONS   DURATION   AGE
job.batch/myjob   Complete   1/1           3s         95s
[root@master30 ~ 14:35:38]# kubectl logs myjob-rqhf2
hello k8s job!
[root@master30 ~ 14:36:28]# kubectl delete jobs.batch myjob
job.batch "myjob" deleted
[root@master30 ~ 14:36:50]# vim job.yaml
[root@master30 ~ 14:37:10]# kubectl apply -f job.yaml
job.batch/myjob created
[root@master30 ~ 14:37:22]# vim job-pi.yaml
[root@master30 ~ 14:37:41]# kubectl apply -f job-pi.yaml
job.batch/pi created
[root@master30 ~ 14:41:23]# kubectl get all
NAME           READY   STATUS      RESTARTS   AGE
pod/pi-ncmg7   0/1     Completed   0          3m34s

NAME           STATUS     COMPLETIONS   DURATION   AGE
job.batch/pi   Complete   1/1           112s       3m34s
[root@master30 ~ 14:41:28]# kubectl logs pi-ncmg7
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303820
restartPolicy

restart 策略只能是:

  • Nerver:只要任务没有完成,就会创建新的 pod,直到 job 完成,所以有可能会产生多个pod。
  • OnFailure:只要任务没有完成,就会重启 pod,直到job完成。

我们做个试验, 修改job.yaml, 故意引入一个错误 :echo 修改为 echoxxx。

root@master30:~# vim job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: myjob
spec:
  template:
    metadata:
      name: myjob
    spec:
      containers:
      - name: hello
        image: hub.laoma.cloud/library/busybox
        imagePullPolicy: IfNotPresent
        command: ["echoxxx", "hello k8s job! "]
      restartPolicy: Never

再次应用,验证。

root@master30:~# kubectl apply -f job.yaml
root@master30:~# kubectl get all
NAME              READY   STATUS       RESTARTS   AGE
pod/myjob-6hp5t   0/1     StartError   0          33s
pod/myjob-gczbz   0/1     StartError   0          2s
pod/myjob-n4bpv   0/1     StartError   0          22s

NAME              COMPLETIONS   DURATION   AGE
job.batch/myjob   0/1           33s        33s

# 可以看到有多个Pod, 状态均不正常。 

# 查看某个 pod 详细信息
root@master30:~# kubectl describe pod myjob-6hp5t
......
Events:
  Type     Reason     Age   From               Message
  ----     ------     ----  ----               -------
  Normal   Scheduled  50s   default-scheduler  Successfully assigned laoma/myjob-6hp5t to worker32.laoma.cloud
  Normal   Pulled     50s   kubelet            Container image "busybox" already present on machine
  Normal   Created    50s   kubelet            Created container hello
  Warning  Failed     50s   kubelet            Error: failed to create containerd task: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "echoxxx": executable file not found in $PATH: unknown

日志显示没有可执行程序, 符合我们的预期。

问题现象: 为什么会看到这么多失败的Pod?

解释: 当第一个Pod启动时, 容器失败退出, 根据 restartPolicy: Never, 此失败容器不会被重启, 但 Job 默认预期完成的Pod数量是1, 目前COMPLETIONS为0, 不满足, 所以 Job 会创建新的Pod, 直到 COMPLETIONS 为1。 对于我们这个例子, SUCCESSFUL 永远也到不了1, 所以Job 会一直创建新的Pod。 为了终止这个行为, 我们删除Job 。

CronJob

[root@master30 ~ 15:14:26]# kubectl create cronjob mycronjob --image=hub.laoma.cloud/library/busybox --schedule='*/2 * * * *' -- echo hello k8s job!
cronjob.batch/mycronjob created
[root@master30 ~ 15:15:13]# kubectl get all
NAME                      SCHEDULE      TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob.batch/mycronjob   */2 * * * *   <none>     False     0        <none>          12s
[root@master30 ~ 15:15:25]# kubectl get all
NAME                      SCHEDULE      TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob.batch/mycronjob   */2 * * * *   <none>     False     0        <none>          38s
[root@master30 ~ 15:15:51]# kubectl get cronjob mycronjob
NAME        SCHEDULE      TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
mycronjob   */2 * * * *   <none>     False     0        27s             74s
[root@master30 ~ 15:16:27]# kubectl get jobs
kubectl get pods
NAME                 STATUS     COMPLETIONS   DURATION   AGE
mycronjob-29707636   Complete   1/1           4s         53s
NAME                       READY   STATUS      RESTARTS   AGE
mycronjob-29707636-8p5d7   0/1     Completed   0          53s
[root@master30 ~ 15:16:53]# kubectl get all
NAME                           READY   STATUS      RESTARTS   AGE
pod/mycronjob-29707636-8p5d7   0/1     Completed   0          87s

NAME                      SCHEDULE      TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob.batch/mycronjob   */2 * * * *   <none>     False     0        87s             2m14s

NAME                           STATUS     COMPLETIONS   DURATION   AGE
job.batch/mycronjob-29707636   Complete   1/1           4s         87s
[root@master30 ~ 15:17:27]# vim 1.yaml
[root@master30 ~ 15:21:26]# kubectl create cm kubeconfig --from-file=config=/root/.kube/config
configmap/kubeconfig created
[root@master30 ~ 15:21:48]# vim 1.yaml
[root@master30 ~ 15:23:39]# kubectl apply -f 1.yaml
cronjob.batch/clean created
[root@master30 ~ 15:23:58]# kubectl get cronjob clean
NAME    SCHEDULE    TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
clean   * * * * *   <none>     False     0        17s             19s
[root@master30 ~ 15:24:17]# kubectl get jobs -l job-name=clean
No resources found in controllers namespace.
[root@master30 ~ 15:24:29]# kubectl logs -l job-name=clean
No resources found in controllers namespace.
[root@master30 ~ 15:24:40]# kubectl create job --from=cronjob/clean test-clean
job.batch/test-clean created
[root@master30 ~ 15:24:53]# kubectl logs job/test-clean
[root@master30 ~ 15:24:58]# kubectl delete cronjob clean
cronjob.batch "clean" deleted
[root@master30 ~ 15:34:48]# kubectl get configmap kubeconfig -n controllers || kubectl create configmap kubeconfig --from-file=config=$HOME/.kube/config -n controllers
NAME         DATA   AGE
kubeconfig   1      13m
[root@master30 ~ 15:34:53]# kubectl apply -f 2.yaml
cronjob.batch/clean-pods created
[root@master30 ~ 15:34:58]# # 查看 CronJob
kubectl get cronjob -n controllers

# 等待约 1 分钟后,查看 Job
kubectl get jobs -n controllers

# 查看日志
kubectl logs -n controllers -l job-name=clean-pods --tail=20
NAME         SCHEDULE      TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
clean-pods   * * * * *     <none>     False     1        4s              6s
mycronjob    */2 * * * *   <none>     False     0        64s             19m
NAME                  STATUS     COMPLETIONS   DURATION   AGE
clean-pods-29707655   Running    0/1           4s         4s
mycronjob-29707650    Complete   1/1           4s         5m4s
mycronjob-29707652    Complete   1/1           3s         3m4s
mycronjob-29707654    Complete   1/1           4s         64s
No resources found in controllers namespace.
[root@master30 ~ 15:35:04]# kubectl create job --from=cronjob/clean-pods test-clean-pods -n controllers
kubectl logs job/test-clean-pods -n controllers
job.batch/test-clean-pods created
Error from server (BadRequest): container "kubectl" in pod "test-clean-pods-cj7kv" is waiting to start: ContainerCreating
  437  2026-06-26 15:36:38 kubectl delete cronjob clean -n controllers --ignore-not-found
  438  2026-06-26 15:36:38 kubectl delete cronjob mycronjob -n controllers --ignore-not-found
  439  2026-06-26 15:36:43 kubectl delete jobs -n controllers -l job-name=clean --ignore-not-found
  440  2026-06-26 15:36:43 kubectl delete jobs -n controllers -l job-name=mycronjob --ignore-not-found
  441  2026-06-26 15:36:43 kubectl delete jobs -n controllers --all   # 如果有其他 Job 也可以清理
  442  2026-06-26 15:36:47 kubectl delete configmap kubeconfig -n controllers --ignore-not-found
  443  2026-06-26 15:36:51 kubectl delete pods -n controller -l app=hello --ignore-not-found
  444  2026-06-26 15:36:56 kubectl get all -n controllers
  445  2026-06-26 15:36:57 kubectl get pods -n controller -l app=hello
  446  2026-06-26 15:37:29 kubectl delete cronjob clean-pods -n controllers

Service基本管理

[root@master30 ~ 15:37:32]# kubectl create ns service
namespace/service created
[root@master30 ~ 15:46:15]# kubectl config set-context --current --namespace services
Context "kubernetes-admin@kubernetes" modified.
[root@master30 ~ 15:47:28]# kubectl run web --image=docker.io/library/httpd --image-pull-policy=IfNotPresent -o yaml --dry-run=client > pod-web.yml
[root@master30 ~ 15:47:49]# kubectl get pods -A
NAMESPACE     NAME                                        READY   STATUS    RESTARTS         AGE
blog          mysql-6b88dd5775-hcz8l                      1/1     Running   1 (6h51m ago)    23h
blog          wordpress-58ffdb8874-djw95                  1/1     Running   1 (6h51m ago)    23h
kube-system   calico-kube-controllers-5b9b456c66-8dh2c    1/1     Running   6 (6h51m ago)    3d4h
kube-system   calico-node-6lb2m                           1/1     Running   6 (6h51m ago)    3d4h
kube-system   calico-node-wfcsq                           1/1     Running   6 (6h51m ago)    3d4h
kube-system   calico-node-z94gp                           1/1     Running   6 (6h51m ago)    3d4h
kube-system   coredns-7db6d8ff4d-k4dc4                    1/1     Running   6 (6h51m ago)    3d4h
kube-system   coredns-7db6d8ff4d-x427m                    1/1     Running   6 (6h51m ago)    3d4h
kube-system   etcd-master30.my.cloud                      1/1     Running   10 (6h51m ago)   3d4h
kube-system   kube-apiserver-master30.my.cloud            1/1     Running   10 (6h51m ago)   3d4h
kube-system   kube-controller-manager-master30.my.cloud   1/1     Running   12 (77m ago)     3d4h
kube-system   kube-proxy-8d28c                            1/1     Running   6 (6h51m ago)    3d4h
kube-system   kube-proxy-gqjch                            1/1     Running   6 (6h51m ago)    3d4h
kube-system   kube-proxy-xmsh4                            1/1     Running   7 (6h51m ago)    3d4h
kube-system   kube-scheduler-master30.my.cloud            1/1     Running   13 (77m ago)     3d4h
[root@master30 ~ 16:08:12]# kubectl create ns services
namespace/services created
[root@master30 ~ 16:08:21]# kubectl config set-context --current --namespace services
Context "kubernetes-admin@kubernetes" modified.
[root@master30 ~ 16:08:26]#  kubectl create deployment web --image=docker.io/library/httpd --replicas=3
deployment.apps/web created
[root@master30 ~ 16:08:46]# kubectl get pods --show-labels
NAME                   READY   STATUS              RESTARTS   AGE   LABELS
web-6db76cb4fc-nkmb6   1/1     Running             0          23s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-rs2s2   0/1     ContainerCreating   0          23s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-wwm7m   1/1     Running             0          23s   app=web,pod-template-hash=6db76cb4fc
[root@master30 ~ 16:09:09]# kubectl get pods --show-labels
NAME                   READY   STATUS              RESTARTS   AGE   LABELS
web-6db76cb4fc-nkmb6   1/1     Running             0          30s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-rs2s2   0/1     ContainerCreating   0          30s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-wwm7m   1/1     Running             0          30s   app=web,pod-template-hash=6db76cb4fc
[root@master30 ~ 16:09:16]# kubectl get pods --show-labels
NAME                   READY   STATUS              RESTARTS   AGE   LABELS
web-6db76cb4fc-nkmb6   1/1     Running             0          34s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-rs2s2   0/1     ContainerCreating   0          34s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-wwm7m   1/1     Running             0          34s   app=web,pod-template-hash=6db76cb4fc
[root@master30 ~ 16:09:20]# kubectl get pods --show-labels
NAME                   READY   STATUS    RESTARTS   AGE   LABELS
web-6db76cb4fc-nkmb6   1/1     Running   0          48s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-rs2s2   1/1     Running   0          48s   app=web,pod-template-hash=6db76cb4fc
web-6db76cb4fc-wwm7m   1/1     Running   0          48s   app=web,pod-template-hash=6db76cb4fc
[root@master30 ~ 16:09:34]#  kubectl create service clusterip web --tcp=8080:80
service/web created
[root@master30 ~ 16:09:42]# kubectl get svc
NAME   TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
web    ClusterIP   10.109.242.150   <none>        8080/TCP   9s
[root@master30 ~ 16:09:51]# curl 10.109.242.150:8080
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>It works! Apache httpd</title>
</head>
<body>
<p>It works!</p>
</body>
</html>
[root@master30 ~ 16:11:10]# kubectl run web --image=docker.io/library/httpd --labels=app=web
pod/web created
[root@master30 ~ 16:11:25]# kubectl exec -it web -- bash -c "echo web > htdocs/index.html"
[root@master30 ~ 16:11:42]# kubectl get pods -o name | awk -F/ '{print $2}'
web
web-6db76cb4fc-nkmb6
web-6db76cb4fc-rs2s2
web-6db76cb4fc-wwm7m
[root@master30 ~ 16:13:21]# for pod in $(kubectl get pods -o name | awk -F/ '{print $2}'); do kubectl exec -it $pod -- bash -c "echo $pod > htdocs/index.html"; done
[root@master30 ~ 16:13:50]# for i in {1 ..60};do curl -s 10.109.242.150;done|sort |uniq -c
[root@master30 ~ 16:18:39]# for i in {1..60}; do curl -s 10.109.242.150:8080; done | sort | uniq -c
     15 web-6db76cb4fc-nkmb6
     21 web-6db76cb4fc-rs2s2
     24 web-6db76cb4fc-wwm7m
[root@master30 ~ 16:18:47]# kubectl run web --image=docker.io/library/httpd --labels=app=web
pod/web created
[root@master30 ~ 16:19:12]# kubectl exec -it web -- bash -c "echo web > htdocs/index.html"
[root@master30 ~ 16:19:46]# for i in {1..60};do curl -s 10.109.242.150:8080;done|sort |uniq -c
     17 web
     14 web-6db76cb4fc-nkmb6
     22 web-6db76cb4fc-rs2s2
      7 web-6db76cb4fc-wwm7m
[root@master30 ~ 16:20:00]# kubectl rollout restart deployment web
deployment.apps/web restarted
[root@master30 ~ 16:20:33]# for i in {1..60};do curl -s 10.109.242.150:8080;done|sort |uniq -c
     46 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
     46 </body>
     46 </head>
     46 </html>
     46 <body>
     46 <head>
     46 <html>
     46 <p>It works!</p>
     46 <title>It works! Apache httpd</title>
     14 web
[root@master30 ~ 16:20:46]# kubectl delete deployments.apps web --force
Warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.
deployment.apps "web" force deleted
[root@master30 ~ 16:38:25]# kubectl delete service web
service "web" deleted
[root@master30 ~ 16:38:44]# vim deploy-web.yaml
[root@master30 ~ 16:41:19]# kubectl apply -f deploy-web.yaml
deployment.apps/web created
[root@master30 ~ 16:42:12]# kubectl get deployment web
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    2/2     2            2           43s
[root@master30 ~ 16:42:55]# kubectl get pods -l app=web
NAME                   READY   STATUS    RESTARTS   AGE
web                    1/1     Running   0          23m
web-5db6f6d487-4z8gq   1/1     Running   0          50s
web-5db6f6d487-zzpg7   1/1     Running   0          50s
[root@master30 ~ 16:43:17]# kubectl expose deployment web --port=8080 --target-port=80 --name=web --type=ClusterIP
service/web exposed
[root@master30 ~ 16:44:13]# # 查看 Service
kubectl get svc web
# 查看 Endpoints(应该显示 Pod IP)
kubectl get endpoints web
# 查看 Service 详情
kubectl describe svc web
NAME   TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)    AGE
web    ClusterIP   10.98.82.88   <none>        8080/TCP   7s
NAME   ENDPOINTS                                              AGE
web    10.224.125.162:80,10.224.125.164:80,10.224.15.100:80   7s
Name:              web
Namespace:         services
Labels:            app=web
Annotations:       <none>
Selector:          app=web
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.98.82.88
IPs:               10.98.82.88
Port:              <unset>  8080/TCP
TargetPort:        80/TCP
Endpoints:         10.224.125.162:80,10.224.125.164:80,10.224.15.100:80
Session Affinity:  None
Events:            <none>
[root@master30 ~ 16:44:20]# kubectl get svc web
NAME   TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)    AGE
web    ClusterIP   10.98.82.88   <none>        8080/TCP   15s
[root@master30 ~ 16:45:27]# # 获取两个 Deployment Pod 的名称
POD1=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')
POD2=$(kubectl get pods -l app=web -o jsonpath='{.items[1].metadata.name}')
# 修改每个 Pod 的 index.html
kubectl exec -it $POD1 -- bash -c "echo $POD1 > /usr/local/apache2/htdocs/index.html"
kubectl exec -it $POD2 -- bash -c "echo $POD2 > /usr/local/apache2/htdocs/index.html"
[root@master30 ~ 16:45:38]# for i in {1..60}; do curl -s 10.98.82.88:8080; done | sort | uniq -c
     22 web-5db6f6d487-4z8gq
     38 web-5db6f6d487-zzpg7

yaml 文件创建

[root@master30 ~ 16:45:46]# kubectl delete svc web
service "web" deleted
[root@master30 ~ 16:49:28]# kubectl create service clusterip web --tcp=8080:80 -o yaml --dry-run=client > svc-web.yml
root@master30:~# cat svc-web.yml 
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: web
  name: web
spec:
  ports:
  - name: 8080-80
    port: 8080
    protocol: TCP
    targetPort: 80
  selector:
    app: web
  type: ClusterIP
status:
  loadBalancer: {}

更多推荐