Use of Kubectl basic commands

Basic concepts of kubernetes

  • Pod: k8s minimum deployment unit, a collection of containers
  • Deployment: the most common controller for higher-level deployment and management of pods
  • Service: provides load balancing for a group of pods and provides unified access to the outside world
  • Label: label, attached to a resource, used to associate objects, query and filter
  • Namespaces: namespace. The logical isolation of objects is also conducive to permission control

kubectl management command

typecommanddescribe
Basic commandcreate expose run expose set explain get edit deleteCreate resources by file name or standard input; Create a Service for Deployment and Pod; Run a specific image in the cluster; Set specific functions on the object; Document references; Displaying one or more resources; Edit a resource using the system editor; Delete resources through file name, standard input, resource name or label selector
Deployment commandrollout rolling-update scale autoscaleManage the release of Deployment and daemon resources (such as status, release record, rollback, etc.); Rolling upgrade, ReplicationController only; Expand or shrink the number of pods for Deployment, ReplicaSet, RC or Job resources; Configure auto scaling rules for Deploy, RS and RC (depending on metrics server and hpa)
Cluster management commandcertificate cluster-info top cordon uncordon drain taintModify certificate resources; Display cluster information; View resource utilization (relying on metrics server); The marked node is not schedulable; Marked nodes are schedulable; Expel applications on nodes and prepare for offline maintenance; Modify node taint tag

kubectl help

kubectl command official document
Use kubectl help to view kubectl related commands

[root@master ~]# kubectl --help
kubectl controls the Kubernetes cluster manager.
 
Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/
 
Basic Commands (Beginner):
  create         Create a resource from a file or from stdin.
  expose         use replication controller, service, deployment perhaps pod And expose it as a new Kubernetes Service
  run            Run a specified mirror in the cluster
  set            by objects Sets a specified feature
 
Basic Commands (Intermediate):
  explain        View documents for resources
  get            Show one or more resources
  edit           Edit a resource on the server
  delete         Delete resources by filenames, stdin, resources and names, or by resources and label selector
 
Deploy Commands:
  rollout        Manage the rollout of a resource
  scale          by Deployment, ReplicaSet, Replication Controller perhaps Job Set a new number of copies
  autoscale      Automatically adjust one Deployment, ReplicaSet, perhaps ReplicationController Number of copies
 
Cluster Management Commands:
  certificate    modify certificate resources.
  cluster-info   Display cluster information
  top            Display Resource (CPU/Memory/Storage) usage.
  cordon         sign node by unschedulable
  uncordon       sign node by schedulable
  drain          Drain node in preparation for maintenance
  taint          Update one or more node Upper taints
 
Troubleshooting and Debugging Commands:
  describe       Displays a specified resource perhaps group of resources details
  logs           Output container in pod Logs in
  attach         Attach To a running container
  exec           In a container Execute a command in
  port-forward   Forward one or more local ports to a pod
  proxy          Run a proxy reach Kubernetes API server
  cp             copy files and directories reach containers And copy from container files and directories.
  auth           Inspect authorization
 
Advanced Commands:
  diff           Diff live version against would-be applied version
  apply          By file name or standard input stream(stdin)Configure resources
  patch          use strategic merge patch Update the of a resource field(s)
  replace        adopt filename perhaps stdin Replace a resource
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        In different API versions Conversion profile
 
Settings Commands:
  label          Update on this resource labels
  annotate       Update the annotation of a resource
  completion     Output shell completion code for the specified shell (bash or zsh)
 
Other Commands:
  alpha         Commands for features in alpha
  api-resources  Print the supported API resources on the server
  api-versions   Print the supported API versions on the server, in the form of "group/version"
  config         modify kubeconfig file
  plugin         Provides utilities for interacting with plugins.
  version        output client and server Version information for

Use of Kubectl common commands

explain

Get resources

Usage:
kubectl explain RESOURCE

//Gets the document for the resource and its fields
,[root@master ~]# kubectl explain pods
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata     <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status       <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

edit

Edit resources

//Run an nginx of pod type, named nginx, and the inner type is deployment
[root@master ~]# kubectl create deployment nginx --image nginx 
deployment.apps/nginx created
[root@master ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-7wp8w   1/1     Running   0          24s
[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   1/1     1            1           28s



//Edit using the edit command
[root@master ~]# kubectl edit deployment nginx
......
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2021-12-20T10:33:49Z"
  generation: 1
  labels:
    app: test   #Change to test
    name: jj	#Add name: jj
.....

//see
[root@master ~]# kubectl describe deploy nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Tue, 21 Dec 2021 01:18:37 +0800
Labels:                 app=test   #Can be added or modified
                        name=jj
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=nginx
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-6799fc88d8 (1/1 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  2m51s  deployment-controller  Scaled up replica set nginx-6799fc88d8 to 1

scale

Dynamic expansion

//Using scale extension
[root@master ~]# kubectl scale deployment/nginx --replicas 3
deployment.apps/nginx scaled
//After expansion, you can view several more pod s of the same type
[root@master ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-7wp8w   1/1     Running   0          3m56s
nginx-6799fc88d8-jxq2b   1/1     Running   0          18s
nginx-6799fc88d8-mk2tl   1/1     Running   0          18s

[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   3/3     3            3           4m3s


//If only 2 nginx pod s of deployment type are required
[root@master ~]# kubectl scale deployment/nginx --replicas 2
deployment.apps/nginx scaled

[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   2/2     2            2           4m24s

//Only two are found (deletion is random)
[root@master ~]# kubectl get pod
NAME                     READY   STATUS        RESTARTS   AGE
nginx-6799fc88d8-7wp8w   1/1     Running       0          4m27s
nginx-6799fc88d8-mk2tl   1/1     Running       0          49s

autoscale

Automatic expansion: given a range, it will automatically increase or decrease according to the traffic

//At least 3, which will be created automatically when the conditions are not met
[root@master ~]# kubectl autoscale deployment/nginx --min 3 --max=5
horizontalpodautoscaler.autoscaling/nginx autoscaled
[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6799fc88d8-27zww   0/1     ContainerCreating   0          0s
nginx-6799fc88d8-7wp8w   1/1     Running             0          5m28s
nginx-6799fc88d8-mk2tl   1/1     Running             0          110s

//When there are more than 5, they will be created first and then deleted randomly until the five conditions are met
[root@master ~]# kubectl scale deployment/nginx --replicas 7
deployment.apps/nginx scaled
[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6799fc88d8-27zww   1/1     Running             0          40s
nginx-6799fc88d8-7wp8w   1/1     Running             0          6m8s
nginx-6799fc88d8-dkvsg   0/1     ContainerCreating   0          4s
nginx-6799fc88d8-hzvlm   0/1     ContainerCreating   0          4s
nginx-6799fc88d8-jk56n   0/1     ContainerCreating   0          4s
nginx-6799fc88d8-mk2tl   1/1     Running             0          2m30s
[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6799fc88d8-27zww   1/1     Running             0          47s
nginx-6799fc88d8-7wp8w   1/1     Running             0          6m15s
nginx-6799fc88d8-dkvsg   0/1     Terminating         0          11s
nginx-6799fc88d8-hzvlm   1/1     Running             0          11s
nginx-6799fc88d8-jk56n   0/1     ContainerCreating   0          11s
nginx-6799fc88d8-mk2tl   1/1     Running             0          2m37s

cluster-info

Display cluster information

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

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

cordon

Schedulable

[root@master ~]# kubectl cordon node2
node/node2 already cordoned
[root@master ~]# kubectl cordon node2
node/node2 cordoned
[root@master ~]# kubectl get node
NAME     STATUS                     ROLES                  AGE     VERSION
master   Ready                      control-plane,master   2d23h   v1.20.0
node1    Ready                      <none>                 2d23h   v1.20.0
node2    Ready,SchedulingDisabled   <none>                 2d23h   v1.20.0

[root@master ~]# kubectl get pod -o wide
NAME                     READY   STATUS    RESTARTS   AGE     IP            NODE    NOMINATED NODE   READINESS GATES
nginx-6799fc88d8-27zww   1/1     Running   0          2m6s    10.244.1.21   node1   <none>           <none>
nginx-6799fc88d8-7wp8w   1/1     Running   0          7m34s   10.244.1.19   node1   <none>           <none>
nginx-6799fc88d8-hzvlm   1/1     Running   0          90s     10.244.1.22   node1   <none>           <none>
nginx-6799fc88d8-jk56n   1/1     Running   0          90s     10.244.2.13   node2   <none>           <none>
nginx-6799fc88d8-mk2tl   1/1     Running   0          3m56s   10.244.2.11   node2   <none>           <none>

[root@master ~]# kubectl scale deployment/nginx --replicas 2
[root@master ~]# kubectl get pod -o wide
NAME                     READY   STATUS        RESTARTS   AGE     IP            NODE    NOMINATED NODE   READINESS GATES
nginx-6799fc88d8-27zww   0/1     Terminating   0          2m27s   10.244.1.21   node1   <none>           <none>
nginx-6799fc88d8-7wp8w   0/1     Terminating   0          7m55s   10.244.1.19   node1   <none>           <none>
nginx-6799fc88d8-hzvlm   0/1     Terminating   0          111s    10.244.1.22   node1   <none>           <none>
nginx-6799fc88d8-jk56n   1/1     Running       0          111s    10.244.2.13   node2   <none>           <none>
nginx-6799fc88d8-mk2tl   1/1     Running       0          4m17s   10.244.2.11   node2   <none>           <none>

uncordon

Non schedulable

[root@master ~]# kubectl uncordon node2
node/node2 uncordoned
[root@master ~]# kubectl get node
NAME     STATUS   ROLES                  AGE     VERSION
master   Ready    control-plane,master   2d23h   v1.20.0
node1    Ready    <none>                 2d23h   v1.20.0
node2    Ready    <none>                 2d23h   v1.20.0

[root@master ~]# kubectl create deployment nginx2  --image nginx
deployment.apps/nginx2 created

[root@master ~]# kubectl get pod -o wide
NAME                      READY   STATUS    RESTARTS   AGE     IP            NODE    NOMINATED NODE   READINESS GATES
nginx-6799fc88d8-jk56n    1/1     Running   0          3m56s   10.244.2.13   node2   <none>           <none>
nginx-6799fc88d8-kp8vf    1/1     Running   0          2m      10.244.1.23   node1   <none>           <none>
nginx-6799fc88d8-mk2tl    1/1     Running   0          6m22s   10.244.2.11   node2   <none>           <none>
nginx2-5fc4444698-f22tb   1/1     Running   0          32s     10.244.1.24   node1   <none>           <none>

describe

Displays the details of the specified pod

[root@master ~]# kubectl describe pod nginx
Name:         nginx-6799fc88d8-jk56n
Namespace:    default
Priority:     0
Node:         node2/192.168.47.121
Start Time:   Tue, 21 Dec 2021 01:24:41 +0800
Labels:       app=nginx
              pod-template-hash=6799fc88d8
Annotations:  <none>
Status:       Running
IP:           10.244.2.13
IPs:
  IP:           10.244.2.13
Controlled By:  ReplicaSet/nginx-6799fc88d8
Containers:
  nginx:
    Container ID:   docker://4b7f630e06232bdfa7c862f3937a6e1256ae3c023644c28c6089961ac9b6c738
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Tue, 21 Dec 2021 01:25:13 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-mrc8p (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-mrc8p:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-mrc8p
    Optional:    false
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  4m46s  default-scheduler  Successfully assigned default/nginx-6799fc88d8-jk56n to node2
  Normal  Pulling    4m46s  kubelet            Pulling image "nginx"
  Normal  Pulled     4m15s  kubelet            Successfully pulled image "nginx" in 31.002882533s
  Normal  Created    4m15s  kubelet            Created container nginx
  Normal  Started    4m15s  kubelet            Started container nginx
·····

logs

view log

[root@master ~]# kubectl logs deployment/nginx
Found 3 pods, using pod/nginx-6799fc88d8-mk2tl
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/12/20 17:22:17 [notice] 1#1: using the "epoll" event method
2021/12/20 17:22:17 [notice] 1#1: nginx/1.21.4
2021/12/20 17:22:17 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2021/12/20 17:22:17 [notice] 1#1: OS: Linux 4.18.0-193.el8.x86_64
2021/12/20 17:22:17 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/20 17:22:17 [notice] 1#1: start worker processes
2021/12/20 17:22:17 [notice] 1#1: start worker process 32
2021/12/20 17:22:17 [notice] 1#1: start worker process 33


[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP    2d4h
nginx        ClusterIP   10.102.213.63   <none>        8080/TCP   24h
[root@master ~]# curl 10.102.213.63: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>
<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 ~]#  kubectl logs deployment/nginx
......
2021/12/20 12:44:49 [notice] 1#1: start worker processes
2021/12/20 12:44:49 [notice] 1#1: start worker process 31
2021/12/20 12:44:49 [notice] 1#1: start worker process 32
10.244.0.0 - - [20/Dec/2021:13:04:14 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.61.1" "-"
10.244.0.0 - - [20/Dec/2021:13:05:26 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.61.1" "-"

attach

Attached to a container

[root@master ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-cpbg4   1/1     Running   0          43m
nginx-6799fc88d8-plvhf   1/1     Running   0          6m38s
nginx-6799fc88d8-rf74m   1/1     Running   0          8m57s
[root@master ~]# kubectl attach nginx-6799fc88d8-jk56n
Defaulting container name to nginx.
Use 'kubectl describe pod/nginx-6799fc88d8-jk56n -n default' to see all of the containers in this pod.
If you don't see a command prompt, try pressing enter.



[root@master ~]# kubectl get pod -o wide
NAME                      READY   STATUS    RESTARTS   AGE     IP            NODE    NOMINATED NODE   READINESS GATES
nginx-6799fc88d8-jk56n    1/1     Running   0          7m49s   10.244.2.13   node2   <none>           <none>
nginx-6799fc88d8-kp8vf    1/1     Running   0          5m53s   10.244.1.23   node1   <none>           <none>
nginx-6799fc88d8-mk2tl    1/1     Running   0          10m     10.244.2.11   node2   <none>           <none>
nginx2-5fc4444698-f22tb   1/1     Running   0          4m25s   10.244.1.24   node1   <none>           <none>


[root@master ~]# curl http://10.244.2.13
<!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>

#Add access log information, < Ctrl > + C exit, and the container will not terminate
[root@master ~]# kubectl attach nginx-6799fc88d8-jk56n
Defaulting container name to nginx.
Use 'kubectl describe pod/nginx-6799fc88d8-jk56n -n default' to see all of the containers in this pod.
If you don't see a command prompt, try pressing enter.
10.244.0.0 - - [20/Dec/2021:17:32:58 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.61.1" "-"
^C
[root@master ~]# kubectl get pod
NAME                      READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-jk56n    1/1     Running   0          8m59s
nginx-6799fc88d8-kp8vf    1/1     Running   0          7m3s
nginx-6799fc88d8-mk2tl    1/1     Running   0          11m
nginx2-5fc4444698-f22tb   1/1     Running   0          5m35s


exec

Execute container command

[root@master ~]# kubectl get pod
NAME                      READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-jk56n    1/1     Running   0          10m

[root@master ~]# kubectl exec nginx-6799fc88d8-jk56n -- date
Mon Dec 20 17:35:29 UTC 2021


[root@master ~]# kubectl exec -it nginx-6799fc88d8-jk56n -- /bin/sh
# ls
bin   dev                  docker-entrypoint.sh  home  lib64  mnt  proc  run   srv  tmp  var
boot  docker-entrypoint.d  etc                   lib   media  opt  root  sbin  sys  usr
# exit
[root@master ~]# kubectl get pod
NAME                      READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-jk56n    1/1     Running   0          11m

prot-forward

Forward one or more ports to the pod

[root@master ~]# kubectl get deployment
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
nginx2   1/1     1            1           11m

[root@master ~]# kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
nginx2-5fc4444698-f22tb   1/1     Running   0          11m

[root@master ~]# kubectl port-forward deployment/nginx2 80
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80
#It can be changed to ': 80' (a random port number, which can only be accessed locally) or to the specified port number '8080:80' (80 for local access and 8080 for other hosts)
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80

[root@master ~]# ss -anlt
State          Recv-Q          Send-Q                     Local Address:Port                    Peer Address:Port         
......                        0.0.0.0:*            
LISTEN         0               128                            127.0.0.1:2381                         0.0.0.0:*            
LISTEN         0               128                            127.0.0.1:80                           0.0.0.0:*            

[root@master ~]# curl 127.0.0.1
<!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 ~]# kubectl port-forward --address 0.0.0.0 deployment/nginx2 80
Forwarding from 0.0.0.0:80 -> 80


//Allow all IP access to port 80
[root@master ~]# curl 127.0.0.1
<!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>

cp

copy
Copy files or directories into the container or from the container

[root@master ~]# kubectl get pod
NAME                      READY   STATUS    RESTARTS   AGE
nginx2-5fc4444698-f22tb   1/1     Running   0          14m

[root@master ~]# ls
anaconda-ks.cfg  init

[root@master ~]# kubectl cp /root/init nginx2-5fc4444698-f22tb:/tmp
[root@master ~]# kubectl exec nginx2-5fc4444698-f22tb -- ls -l /tmp
total 4
-rw-r--r-- 1 root root 174 Dec 20 17:43 init

label

label
Set and update labels for resources

[root@master ~]# kubectl get pod
NAME                      READY   STATUS    RESTARTS   AGE
nginx2-5fc4444698-f22tb   1/1     Running   0          17m

[root@master ~]# kubectl describe pod nginx2
Name:         nginx2-5fc4444698-f22tb
Namespace:    default
Priority:     0
Node:         node1/192.168.47.120
Start Time:   Tue, 21 Dec 2021 01:28:05 +0800
Labels:       app=nginx2
              pod-template-hash=5fc4444698
.....

//Append label
[root@master ~]#  kubectl label pods nginx2-5fc4444698-f22tb name=test
pod/nginx2-5fc4444698-f22tb labeled
[root@master ~]# kubectl describe pod nginx2-5fc4444698-f22tb
Name:         nginx2-5fc4444698-f22tb
Namespace:    default
Priority:     0
Node:         node1/192.168.47.120
Start Time:   Tue, 21 Dec 2021 01:28:05 +0800
Labels:       app=nginx2
              name=test
              pod-template-hash=5fc4444698
Annotations:  <none>



//Change label
[root@master ~]# kubectl label --overwrite pods nginx2-5fc4444698-f22tb app=test
pod/nginx labeled

//Check whether the change is successful
[root@master ~]# kubectl describe pod nginx2-5fc4444698-f22tb
Name:         nginx2-5fc4444698-f22tb
Namespace:    default
Priority:     0
Node:         node1/192.168.47.120
Start Time:   Tue, 21 Dec 2021 01:28:05 +0800
Labels:       app=test
              name=test
              pod-template-hash=5fc4444698

api-resources

View all resources

[root@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
......  

api-versions

API version

[root@master ~]# kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
flowcontrol.apiserver.k8s.io/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

version

View version

[root@master ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:59:43Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:51:19Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}

Deploying a mirror using the deployment controller

[root@master ~]# kubectl create deployment nginx --image lizhenliang/java-demo
deployment.apps/nginx created
[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
nginx-5fd5cdd7d4-4sjb7   1/1     Running       0          3m30s
nginx-5fd5cdd7d4-nq9bb   1/1     Running       0          3m30s
nginx-5fd5cdd7d4-p97tp   1/1     Running       0          3m45s

[root@master ~]# kubectl get deploy,pods
NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   1/3     3            1           38s

NAME                         READY   STATUS              RESTARTS   AGE
pod/nginx-5fd5cdd7d4-4sjb7   1/1     Running       0          3m59s
pod/nginx-5fd5cdd7d4-nq9bb   1/1     Running       0          3m59s
pod/nginx-5fd5cdd7d4-p97tp   1/1     Running       0          4m14s

//Expose the pod using Service
[root@master ~]# kubectl expose deployment nginx --port=80 --target-port=8080 --type=NodePort
service/nginx exposed
[root@master ~]# kubectl get service
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        2d6h
nginx        NodePort    10.111.209.122   <none>        80:32603/TCP   8s

//visit
[root@master ~]# curl 192.168.129.250:32603
<!DOCTYPE html>
<html>
<head lang="en">
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Take beauty home application case</title>
        <meta name="description" content="Take beauty home application case">
        <meta name="keywords" content="index">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta http-equiv="Cache-Control" content="no-siteapp" />
        <link rel="stylesheet" href="../js/layui/css/layui.css" media="all">
        <link rel="stylesheet" href="../css/reset.css">
    <link rel="stylesheet" href="../css/supersized.css">
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/typeit.css">
    <link rel="stylesheet" href="../css/date.css">
</head>
<body>
<!-- <img src="../images/logo.png"> -->
<div class="page-container">
            <h1 class="title"></h1>
            <div style="margin-top: 15%;">
                <button class="layui-btn layui-btn-lg layui-btn-primary layui-btn-radius" onclick="adduser()">Add beauty</button>
                <button class="layui-btn layui-btn-lg layui-btn-primary layui-btn-radius" onclick="queryuserList()">Which one do you want to turn over tonight</button>
            </div>
         <!--    <div style="text-align:center;clear:both" class="date">
                        </div> -->
                        <!-- <div class="connect">
                <p>Contact author:Zibin</p>
                <p>
                    <a class="qq" target="_blank" href="http://wpa.qq.com/msgrd?Menu=no&Exe=QQ&Uin=125720240"></a>
                    <a class="twitter" href=""></a>
                </p>
            </div> -->
        </div>
        <script src="../js/jquery-1.8.2.min.js"></script>
        <script src="../js/layui/layui.js"></script>
        <script src="../js/supersized.3.2.7.min.js"></script>
        <script src="../js/supersized-init.js"></script>
        <script src="../js/typeit.js"></script>
        <script src="../js/date.js"></script>
        <script src="../js/index.js"></script>
        <script type="text/javascript">
                 $('.title').typeIt({
                  whatToType: "There are many beauties here. Pick one and go home!",
              typeSpeed: 300,
              lifeLike: true,
              breakLines :true
                }, function() {
                          console.log('This is tomcat callback function!');
                });
         </script>
</body>
</html>

Rolling update and rollback

Write two images with Dockerfile

[root@master ~]# mkdir httpd
[root@master ~]# cd httpd/
//Make the first version image
[root@master httpd]# vim Dockerfile
[root@master httpd]# cat Dockerfile 
FROM busybox

RUN mkdir  /data && \
    echo "test page on v1" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]

[root@master httpd]# docker build -t jiejiehao/httpd:v1 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> ffe9d497c324
Step 2/3 : RUN mkdir  /data &&     echo "test page on v1" > /data/index.html
 ---> Running in 0753a276c632
Removing intermediate container 0753a276c632
 ---> 75825bd6a4d5
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in af4ecc493da0
Removing intermediate container af4ecc493da0
 ---> 477d3c5c8fe7
Successfully built 477d3c5c8fe7
Successfully tagged jiejiehao/httpd:v1


//Make second edition image
[root@master httpd]# vim Dockerfile 
[root@master httpd]# cat Dockerfile 
FROM busybox

RUN mkdir  /data && \
    echo "test page on v2" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]


[root@master httpd]# docker build -t jiejiehao/httpd:v2 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> ffe9d497c324
Step 2/3 : RUN mkdir  /data &&     echo "test page on v2" > /data/index.html
 ---> Running in c6a32c0067e4
Removing intermediate container c6a32c0067e4
 ---> 6d1103c3febc
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in e24dd849a599
Removing intermediate container e24dd849a599
 ---> 7236b2280632
Successfully built 7236b2280632
Successfully tagged jiejiehao/httpd:v2

    
[root@master httpd]# docker images
REPOSITORY                                                        TAG        IMAGE ID       CREATED          SIZE
jiejiehao/httpd                                                   v1         477d3c5c8fe7   39 seconds ago   1.24MB
jiejiehao/httpd                                                   v2         7236b2280632   54 seconds ago   1.24MB
busybox                                                           latest     ffe9d497c324   12 days ago      1.24MB
[root@master ~]# docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: jiejiehao
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
[root@master ~]# docker push jiejiehao/httpd:v1
The push refers to repository [docker.io/jiejiehao/httpd]
222718935aad: Pushed 
64cac9eaf0da: Mounted from library/busybox 
v1: digest: sha256:1ae146ca01daf76043ccad9cb5ece9eaede66ceaa2fdf9c1afdb29fcaa95ba7c size: 734
[root@master ~]# docker push jiejiehao/httpd:v2
The push refers to repository [docker.io/jiejiehao/httpd]
d59d343cf27e: Layer already exists 
64cac9eaf0da: Layer already exists 
v2: digest: sha256:ccb39d6e8db89e89efff912164ed1c309c98ea363b75c54c74afbfbd1530eb60 size: 734

Rolling update and rollback

//Run three pod s based on httpd:v1 image with k8s
[root@master httpd]# kubectl create deploy httpd --image jiejiehao/httpd:v1 --replicas 3
deployment.apps/httpd created

[root@master ~]# kubectl get pod
NAME                      READY   STATUS    RESTARTS   AGE
httpd-7649d9b878-5lvf7    1/1     Running   0          8m4s
httpd-7649d9b878-ck6cq    1/1     Running   0          8m4s
httpd-7649d9b878-pkqkk    1/1     Running   0          8m4s


#Exposed port number
[root@master ~]# kubectl expose deploy httpd --port 80 --type NodePort
service/httpd exposed

[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
httpd        NodePort    10.103.50.196   <none>        80:30263/TCP   37s

#visit
[root@master ~]# curl 10.103.50.196
test page on v1

[root@master ~]# curl 192.168.47.115:30263
test page on v1



//to update
[root@master ~]# kubectl set image deploy/httpd httpd=jiejiehao/httpd:v2
deployment.apps/httpd image updated

//Create a new pod and delete an old one. Until the update is complete
[root@master ~]# kubectl get pod
NAME                      READY   STATUS              RESTARTS   AGE
httpd-7649d9b878-5lvf7    1/1     Terminating         0          11m
httpd-7649d9b878-ck6cq    1/1     Running             0          11m
httpd-7649d9b878-pkqkk    1/1     Terminating         0          11m
httpd-cb9c79f99-gfk9z     0/1     ContainerCreating   0          10s
httpd-cb9c79f99-w722f     1/1     Running             0          11s
httpd-cb9c79f99-zcsw5     1/1     Running             0          35s


[root@master ~]# kubectl get pod
NAME                      READY   STATUS        RESTARTS   AGE
httpd-cb9c79f99-gfk9z     1/1     Running       0          101s
httpd-cb9c79f99-w722f     1/1     Running       0          102s
httpd-cb9c79f99-zcsw5     1/1     Running       0          2m6s


#visit
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
httpd        NodePort    10.103.50.196   <none>        80:30263/TCP   5m13s
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        3d
[root@master ~]# curl 10.103.50.196
test page on v2
[root@master ~]# curl 192.168.47.115:30263
test page on v2





//RollBACK 
[root@master ~]# kubectl rollout undo deploy/httpd
deployment.apps/httpd rolled back

[root@master ~]# kubectl get pod
NAME                      READY   STATUS        RESTARTS   AGE
httpd-7649d9b878-96cnm    1/1     Running       0          8s
httpd-7649d9b878-mq6mh    1/1     Running       0          6s
httpd-7649d9b878-rtmjt    1/1     Running       0          10s
httpd-cb9c79f99-gfk9z     1/1     Terminating   0          3m21s
httpd-cb9c79f99-w722f     1/1     Terminating   0          3m22s
httpd-cb9c79f99-zcsw5     1/1     Terminating   0          3m46s


[root@master ~]# curl 10.103.50.196
test page on v1
[root@master ~]# curl 192.168.47.115:30263
test page on v1


//Create v3 version
[root@master httpd]# vim Dockerfile 
[root@master httpd]# cat Dockerfile 
FROM busybox

RUN mkdir  /data && \
    echo "test page on v3" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master httpd]# docker build -t jiejiehao/httpd:v3 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> ffe9d497c324
Step 2/3 : RUN mkdir  /data &&     echo "test page on v3" > /data/index.html
 ---> Running in 8ea936e6629c
Removing intermediate container 8ea936e6629c
 ---> a827c5b321f9
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in 216b3ba59275
Removing intermediate container 216b3ba59275
 ---> 9777e0dbeee8
Successfully built 9777e0dbeee8
Successfully tagged jiejiehao/httpd:v3
[root@master httpd]# docker push jiejiehao/httpd:v3
The push refers to repository [docker.io/jiejiehao/httpd]
c05cffd8f41f: Pushed 
64cac9eaf0da: Layer already exists 
v3: digest: sha256:c27534074bae54cbf36e91e1161cc009465e4cc57b2ebf90a9edef2524bf6f12 size: 734
[root@master httpd]# kubectl set image deploy/httpd httpd=jiejiehao/httpd:v3
deployment.apps/httpd image updated

//It now belongs to v1, and the previous version was v2
[root@master ~]# curl 10.103.50.196
test page on v1
//Update version to v3
[root@master httpd]# kubectl set image deploy/httpd httpd=jiejiehao/httpd:v3
deployment.apps/httpd image updated
[root@master httpd]# curl 10.103.50.196
test page on v3
//RollBACK 
[root@master ~]# kubectl rollout undo deploy/httpd
deployment.apps/httpd rolled back
//Back to v1
[root@master ~]# curl 10.103.50.196
test page on v1
//Rollback again
[root@master ~]# kubectl rollout undo deploy/httpd
deployment.apps/httpd rolled back
//I found that I returned to v3, not v2
//Note rolling back to the previous version is also a version record, so it can only be rolled back once at most
[root@master ~]# curl 10.103.50.196
test page on v3

Keywords: Operation & Maintenance Docker Kubernetes

Added by ksmatthews on Tue, 21 Dec 2021 01:10:05 +0200