Kubernetes常用基础命令

如何查看帮助文档

// 查看 kubectl 能使用哪些命令
[root@master ~]# kubectl --help
kubectl controls the Kubernetes cluster manager.

 Find more information at: https://k8s.io/docs/reference/kubectl/overview/

Basic Commands (Beginner):
  create        Create a resource from a file or from stdin
  expose        Take a replication controller, service, deployment or pod and expose it as a new Kubernetes service
  run           在集群中运行一个指定的镜像
  set           为 objects 设置一个指定的特征

Basic Commands (Intermediate):
  explain       Get documentation for a resource
  get           显示一个或更多 resources
  edit          在服务器上编辑一个资源
  delete        Delete resources by file names, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout       Manage the rollout of a resource
  scale         Set a new size for a deployment, replica set, or replication controller
  autoscale     Auto-scale a deployment, replica set, stateful set, or replication controller

Cluster Management Commands:
  certificate   修改 certificate 资源.
  cluster-info  Display cluster information
  top           Display resource (CPU/memory) usage
  cordon        标记 node 为 unschedulable
  uncordon      标记 node 为 schedulable
  drain         Drain node in preparation for maintenance
  taint         更新一个或者多个 node 上的 taints

Troubleshooting and Debugging Commands:
  describe      显示一个指定 resource 或者 group 的 resources 详情
  logs          输出容器在 pod 中的日志
  attach        Attach 到一个运行中的 container
  exec          在一个 container 中执行一个命令
  port-forward  Forward one or more local ports to a pod
  proxy         运行一个 proxy 到 Kubernetes API server
  cp            Copy files and directories to and from containers
  auth          Inspect authorization
  debug         Create debugging sessions for troubleshooting workloads and nodes

Advanced Commands:
  diff          Diff the live version against a would-be applied version
  apply         Apply a configuration to a resource by file name or stdin
  patch         Update fields of a resource
  replace       Replace a resource by file name or stdin
  wait          Experimental: Wait for a specific condition on one or many resources
  kustomize     Build a kustomization target from a directory or URL.

Settings Commands:
  label         更新在这个资源上的 labels
  annotate      更新一个资源的注解
  completion    Output shell completion code for the specified shell (bash, zsh or fish)

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        修改 kubeconfig 文件
  plugin        Provides utilities for interacting with plugins
  version       输出 client 和 server 的版本信息

Usage:
  kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

// 查看单独命令的使用方法
[root@master ~]# kubectl delete --help	// 举个例子

类型介绍

Pod:K8s最小部署单元,一组容器的集合

Deployment:最常见的控制器,用于更高级别部署和管理Pod

Service:为一组Pod提供负载均衡,对外提供一访问入口,可使用缩写 “svc”

Label:标签,附加到某个资源上,用于关联对象、查询和筛

Namespaces:命令空间,将对象逻辑上隔离,也利于权限控制

[root@master ~]# kubectl get pods
NAME                  READY   STATUS    RESTARTS   AGE
nginx                 1/1     Running   1          23h
web-96d5df5c8-46xf7   1/1     Running   1          23h
web-96d5df5c8-lvp7n   1/1     Running   1          23h
web-96d5df5c8-x2j8v   1/1     Running   1          23h

# deployment
[root@master ~]# kubectl get deployments
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    3/3     3            3           23h
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    47h
web          ClusterIP   10.109.125.152   <none>        8080/TCP   23h

# svc
[root@master ~]# kubectl get pods
NAME                  READY   STATUS    RESTARTS   AGE
nginx                 1/1     Running   1          23h
web-96d5df5c8-46xf7   1/1     Running   1          23h
web-96d5df5c8-lvp7n   1/1     Running   1          23h
web-96d5df5c8-x2j8v   1/1     Running   1          23h
[root@master ~]# kubectl get deployments
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    3/3     3            3           23h
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    47h
web          ClusterIP   10.109.125.152   <none>        8080/TCP   23h

常用基础命令

create:创建

sleep:延迟
[root@master ~]# kubectl create deployment b2 --image busybox -- slepp 6000
deployment.apps/b2 created
[root@master ~]# kubectl get pods
NAME                  READY   STATUS              RESTARTS   AGE
b2-7c7c9fd96c-zpvg8   0/1     ContainerCreating   0          12s
nginx                 1/1     Running             1          23h
replicas:复制
[root@master ~]# kubectl create deployment myapp --image nginx --replicas 3
deployment.apps/myapp created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b2-7c7c9fd96c-zpvg8      0/1     CrashLoopBackOff   2          2m10s
myapp-6d8d776547-t2pbl   1/1     Running            0          76s
myapp-6d8d776547-tqjb6   1/1     Running            0          76s
myapp-6d8d776547-vjd7q   1/1     Running            0          76s
nginx                    1/1     Running            1          23h
port:指定端口
[root@master ~]# kubectl create deployment test --image nginx --port 80
deployment.apps/test created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b2-7c7c9fd96c-zpvg8      0/1     CrashLoopBackOff   4          4m37s
myapp-6d8d776547-t2pbl   1/1     Running            0          3m43s
myapp-6d8d776547-tqjb6   1/1     Running            0          3m43s
myapp-6d8d776547-vjd7q   1/1     Running            0          3m43s
nginx                    1/1     Running            1          23h
test-7968d6985c-8wvkb    1/1     Running            0          43s

// 查看详细信息
[root@master ~]# kubectl get pods -o wide
NAME                     READY   STATUS             RESTARTS   AGE     IP            NODE                NOMINATED NODE   READINESS GATES
b2-7c7c9fd96c-zpvg8      0/1     CrashLoopBackOff   5          5m18s   10.244.2.13   node2.example.com   <none>           <none>
myapp-6d8d776547-t2pbl   1/1     Running            0          4m24s   10.244.2.16   node2.example.com   <none>           <none>
myapp-6d8d776547-tqjb6   1/1     Running            0          4m24s   10.244.2.15   node2.example.com   <none>           <none>
myapp-6d8d776547-vjd7q   1/1     Running            0          4m24s   10.244.2.14   node2.example.com   <none>           <none>
nginx                    1/1     Running            1          23h     10.244.1.3    node1.example.com   <none>           <none>
test-7968d6985c-8wvkb    1/1     Running            0          84s     10.244.2.17   node2.example.com   <none>           <none>
[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
b2      0/1     1            0           6m20s
myapp   3/3     3            3           5m26s
test    1/1     1            1           2m26s

expose:暴露

映射端口
// 暴露8080端口,映射到容器里面的80端口
[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
b2      0/1     1            0           7m21s
myapp   3/3     3            3           6m27s
test    1/1     1            1           3m27s
[root@master ~]# kubectl expose deployment myapp --port 8080 --target-port 80
service/myapp exposed
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    47h
myapp        ClusterIP   10.110.135.211   <none>        8080/TCP   7s

// 访问测试
[root@master ~]# curl 10.110.135.211: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>

get:获取

获取来源
// kubernetes初始化文件
[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   47h
kube-node-lease   Active   47h
kube-public       Active   47h
kube-system       Active   47h
[root@master ~]# kubectl get nodes
NAME                 STATUS   ROLES                  AGE   VERSION
master.example.com   Ready    control-plane,master   47h   v1.20.0
node1.example.com    Ready    <none>                 47h   v1.20.0
node2.example.com    Ready    <none>                 47h   v1.20.0
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    47h
myapp        ClusterIP   10.110.135.211   <none>        8080/TCP   2m43s

// 看的是default里面的
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b2-7c7c9fd96c-zpvg8      0/1     CrashLoopBackOff   6          10m
myapp-6d8d776547-t2pbl   1/1     Running            0          9m27s
myapp-6d8d776547-tqjb6   1/1     Running            0          9m27s
myapp-6d8d776547-vjd7q   1/1     Running            0          9m27s
nginx                    1/1     Running            1          24h
test-7968d6985c-8wvkb    1/1     Running            0          6m27s
过滤查看
// 不指定,查看所有部署
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b2-7c7c9fd96c-zpvg8      0/1     CrashLoopBackOff   6          11m
myapp-6d8d776547-t2pbl   1/1     Running            0          10m
myapp-6d8d776547-tqjb6   1/1     Running            0          10m
myapp-6d8d776547-vjd7q   1/1     Running            0          10m
nginx                    1/1     Running            1          24h
test-7968d6985c-8wvkb    1/1     Running            0          7m27s

[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
b2      0/1     1            0           11m
myapp   3/3     3            3           10m
test    1/1     1            1           7m51s

// 指定过滤,指定查看myapp部署
[root@master ~]# kubectl get deployment myapp
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
myapp   3/3     3            3           11m
使用json格式展示部署效果
[root@master ~]# kubectl get deployment myapp -o json
{
    "apiVersion": "apps/v1",
    "kind": "Deployment",
    "metadata": {
        "annotations": {
            "deployment.kubernetes.io/revision": "1"
        },
        "creationTimestamp": "2021-12-20T10:30:39Z",
        "generation": 1,
        "labels": {
            "app": "myapp"
        },
        "managedFields": [
            {
                "apiVersion": "apps/v1",
                "fieldsType": "FieldsV1",
                "fieldsV1": {
                    "f:metadata": {
                        "f:labels": {
                            ".": {},
                            "f:app": {}
                        }
                    },
                    ......省略
使用yaml格式展示部署效果
[root@master ~]# kubectl get deployment myapp -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2021-12-20T10:30:39Z"
  generation: 1
  labels:
    app: myapp
  managedFields:
  - apiVersion: apps/v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:labels:
          .: {}
          f:app: {}
      f:spec:
        f:progressDeadlineSeconds: {}
        f:replicas: {}
        f:revisionHistoryLimit: {}
        f:selector: {}
        f:strategy:
          f:rollingUpdate:
            .: {}
            f:maxSurge: {}
            ......省略

delete:删除

  • -f:强制删除
  • -l:指定标签删除
单个删除
// 删除一个(deployment)
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b2-7c7c9fd96c-zpvg8      0/1     CrashLoopBackOff   7          14m
myapp-6d8d776547-t2pbl   1/1     Running            0          14m
myapp-6d8d776547-tqjb6   1/1     Running            0          14m
myapp-6d8d776547-vjd7q   1/1     Running            0          14m
nginx                    1/1     Running            1          24h
test-7968d6985c-8wvkb    1/1     Running            0          11m
[root@master ~]# kubectl delete deployment b2
deployment.apps "b2" deleted
[root@master ~]# kubectl get pods
NAME                     READY   STATUS        RESTARTS   AGE
b2-7c7c9fd96c-zpvg8      0/1     Terminating   7          15m
myapp-6d8d776547-t2pbl   1/1     Running       0          14m
myapp-6d8d776547-tqjb6   1/1     Running       0          14m
myapp-6d8d776547-vjd7q   1/1     Running       0          14m
nginx                    1/1     Running       1          24h
test-7968d6985c-8wvkb    1/1     Running       0          11m
多个删除
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
myapp-6d8d776547-t2pbl   1/1     Running   0          15m
myapp-6d8d776547-tqjb6   1/1     Running   0          15m
myapp-6d8d776547-vjd7q   1/1     Running   0          15m
nginx                    1/1     Running   1          24h
test-7968d6985c-8wvkb    1/1     Running   0          12m
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    47h
myapp        ClusterIP   10.110.135.211   <none>        8080/TCP   9m4s

// 删除两个(deployment,svc)
[root@master ~]# kubectl delete deployment,svc myapp
deployment.apps "myapp" deleted
service "myapp" deleted
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   47h
[root@master ~]# kubectl get pods
NAME                    READY   STATUS    RESTARTS   AGE
nginx                   1/1     Running   1          24h
test-7968d6985c-8wvkb   1/1     Running   0          13m
删除所有
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS      AGE
nginx-85b98978db-2dj8t   1/1     Running   1 (19h ago)   19h
test-7c68854699-bph9c    1/1     Running   0             41m
[root@master ~]# kubectl delete deployment --all
deployment.apps "nginx" deleted
deployment.apps "test" deleted
[root@master ~]# kubectl get pods
No resources found in default namespace.
-l:指定标签删除
// 运行多个nginx标签
[root@master ~]# kubectl run test --image nginx --labels "app=nginx" 
pod/test created
[root@master ~]# kubectl run test2 --image nginx --labels "app=nginx"
pod/test2 created
[root@master ~]# kubectl run test3 --image nginx --labels "app=nginx" 
pod/test3 created


// 这四个都是以 --labels "app=nginx" 运行的
[root@master ~]# kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   1          24h
test    1/1     Running   0          59s
test2   1/1     Running   0          45s
test3   1/1     Running   0          39s

// 当有很多个nginx服务
[root@master ~]# kubectl delete pod -l "app=nginx"
pod "nginx" deleted
pod "test" deleted
pod "test2" deleted
pod "test3" deleted

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

run:运行

  • labels:指定标签
  • dry-run:干跑格式
  • it:交互模式
默认运行pod类型
// 运行nginx镜像,没有nginx镜像会先去拉取
[root@master ~]# kubectl run nginx --image nginx
pod/nginx created

// 正在获取nginx镜像
[root@master ~]# kubectl get pods
NAME    READY   STATUS              RESTARTS   AGE
nginx   0/1     ContainerCreating   0          8s

[root@master ~]# kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          115s

// 删除单个pod,这里是pod类型,不是deployment类型
[root@master ~]# kubectl delete pod nginx
pod "nginx" deleted
[root@master ~]# kubectl get pods
No resources found in default namespace.
–labels:指定标签
// app=nginx这是指定的标签
[root@master ~]# kubectl run nginx --image nginx --labels "app=nginx"
pod/nginx created

[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node2.example.com/192.168.200.143
Start Time:   Mon, 20 Dec 2021 18:56:54 +0800
Labels:       app=nginx    // 这里就是标签
Annotations:  <none>
Status:       Running
IP:           10.244.2.22
IPs:
  IP:  10.244.2.22
Containers:
  nginx:
    Container ID:   docker://66177f11c8a50d8a36dd446e022026b12f8bdc5a949e60796cbde3c69b960d4c
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Mon, 20 Dec 2021 18:57:10 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-kstwn (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-kstwn:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-kstwn
    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  52s   default-scheduler  Successfully assigned default/nginx to node2.example.com
  Normal  Pulling    52s   kubelet            Pulling image "nginx"
  Normal  Pulled     36s   kubelet            Successfully pulled image "nginx" in 15.669725458s
  Normal  Created    36s   kubelet            Created container nginx
  Normal  Started    36s   kubelet            Started container nginx
–dry-run:干跑格式(假设,不是真的跑)
[root@master ~]# kubectl run nginx --image nginx --dry-run client
W1220 18:59:14.010960   24301 helpers.go:553] --dry-run is deprecated and can be replaced with --dry-run=client.
pod/nginx created (dry run)    // 显示created,说明是可以创建的

[root@master ~]# kubectl get pods
No resources found in default namespace.
-it:交互模式
[root@master ~]# kubectl run -it busybox --image=busybox --restart=Never
If you don't see a command prompt, try pressing enter.
/ # ls
bin   etc   proc  sys   usr
dev   home  root  tmp   var

// 运行的时候是Running状态
[root@master ~]# kubectl get pods
NAME      READY   STATUS    RESTARTS   AGE
busybox   1/1     Running   0          51s

// 退出的时候是Completed状态
/ # exit
[root@master ~]# kubectl get pods
NAME      READY   STATUS      RESTARTS   AGE
busybox   0/1     Completed   0          89s

edit:编辑

[root@master ~]# kubectl run nginx --image nginx --labels "app=abc"
pod/nginx created

[root@master ~]# kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          34s

// 编辑标签
[root@master ~]# kubectl edit pods/nginx
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2021-12-20T11:03:37Z"
  labels:
    app: cba   // 修改这里
  name: nginx
  namespace: default
  resourceVersion: "28499"
  uid: 30da328b-bf09-4b13-b65d-920f627a68b0
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: nginx
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    ......
    // 编译完成 ZZ 或者 wq!退出


// 查看nginx描述
[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node2.example.com/192.168.200.143
Start Time:   Mon, 20 Dec 2021 19:03:37 +0800
Labels:       app=cba   // 标签已经修改成功
Annotations:  <none>
Status:       Running
IP:           10.244.2.24
IPs:
  IP:  10.244.2.24
Containers:
  nginx:
    Container ID:   docker://ff387983dbad7bb1f79fb2c7420f49b0630ae338fa3483f0da1b5fc38b782ccf
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Mon, 20 Dec 2021 19:03:39 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-kstwn (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-kstwn:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-kstwn
    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  3m     default-scheduler  Successfully assigned default/nginx to node2.example.com
  Normal  Pulling    2m59s  kubelet            Pulling image "nginx"
  Normal  Pulled     2m58s  kubelet            Successfully pulled image "nginx" in 1.502212051s
  Normal  Created    2m58s  kubelet            Created container nginx
  Normal  Started    2m58s  kubelet            Started container nginx

explain:解释

// 查看定义文件怎么编写的
[root@master ~]# kubectl explain deployment
KIND:     Deployment
VERSION:  apps/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     <Object>
     Standard object metadata.

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

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

rollout:回本

有效的资源类型的:

  • deployments
  • daemonsets
  • statefulsets
[root@master ~]# kubectl create deployment nginx --image nginx
deployment.apps/nginx created

// 回本成功
[root@master ~]# kubectl rollout status deployments/nginx
deployment "nginx" successfully rolled out
更新版本之后才能看见回本效果

注意:rollout不能回本 pod 和 svc 类型

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
test                     1/1     Running     0          61m

[root@master ~]# kubectl rollout status pod/test
error: no status viewer has been implemented for Pod

[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP   46h
nginx        ClusterIP   10.108.208.249   <none>        80/TCP    68m

[root@master ~]# kubectl rollout status svc/nginx
error: no status viewer has been implemented for Service

scale:扩展

[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-tj9cz   1/1     Running   0          68s

// 动态扩展:之前只有一个,现在变成五个
[root@master ~]# kubectl scale --replicas 5 deployment/nginx
deployment.apps/nginx scaled

[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-hxhg2   1/1     Running   0          105s
nginx-6799fc88d8-n4dmr   1/1     Running   0          105s
nginx-6799fc88d8-tj9cz   1/1     Running   0          3m4s
nginx-6799fc88d8-tktsg   1/1     Running   0          105s
nginx-6799fc88d8-xf5wf   1/1     Running   0          105s

// 当你不需要那么多的 deployment/nginx 时候,你可以指定你想留下几个,他会随机删除不需要的
[root@master ~]# kubectl scale --replicas 3 deployment/nginx
deployment.apps/nginx scaled

[root@master ~]# kubectl get pods 
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-hxhg2   1/1     Running   0          3m49s
nginx-6799fc88d8-n4dmr   1/1     Running   0          3m49s
nginx-6799fc88d8-tj9cz   1/1     Running   0          5m8s

autoscale:自动扩展

  • min:最少扩展
  • max:最大扩展
  • percent:百分比
[root@master ~]# kubectl get pods 
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-hxhg2   1/1     Running   0          4m51s
nginx-6799fc88d8-n4dmr   1/1     Running   0          4m51s
nginx-6799fc88d8-tj9cz   1/1     Running   0          6m10s

// 最少1个,最多5个,cpu占比50%
[root@master ~]# kubectl autoscale --min 1 --max 5 --cpu-percent 50 deployment/nginx
horizontalpodautoscaler.autoscaling/nginx autoscaled   // hpa类型

// 查看运行情况
[root@master ~]# kubectl get hpa
NAME    REFERENCE          TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
nginx   Deployment/nginx   <unknown>/50%   1         5         3          57s

// 自动扩展成功
[root@master ~]# kubectl get pods 
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-hxhg2   1/1     Running   0          7m32s
nginx-6799fc88d8-n4dmr   1/1     Running   0          7m32s
nginx-6799fc88d8-tj9cz   1/1     Running   0          8m51s
nginx-85b98978db-h2zvv   1/1     Running   0          17m
nginx-85b98978db-k4twc   1/1     Running   0          13m

// 删除所有 deployment类型的 nginx
[root@master ~]# kubectl delete deployment/nginx
deployment.apps "nginx" deleted

top:查看资源使用率

top           Display resource (CPU/memory) usage
// 使用top命令需要安装插件

describe:描述

// 查看test容器的描述
[root@master ~]# kubectl describe pod/test
Name:         test
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.91.137
Start Time:   Mon, 20 Dec 2021 09:39:51 +0800
Labels:       run=test
Annotations:  <none>
Status:       Running
IP:           10.244.1.17
......以下省略

logs:查看日志

// 默认pod类型。不是pod类型,需要指定,比如是 deployment类型的,就是deployment/tests
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
test   1/1     Running   0          34m


[root@master ~]# kubectl logs test
/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 01:40:08 [notice] 1#1: using the "epoll" event method
2021/12/20 01:40:08 [notice] 1#1: nginx/1.21.4
2021/12/20 01:40:08 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2021/12/20 01:40:08 [notice] 1#1: OS: Linux 4.18.0-257.el8.x86_64
2021/12/20 01:40:08 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/20 01:40:08 [notice] 1#1: start worker processes
2021/12/20 01:40:08 [notice] 1#1: start worker process 31
2021/12/20 01:40:08 [notice] 1#1: start worker process 32

exec:

-it:交互模式

# pod
// 进去执行命令
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
test   1/1     Running   0          43m

// pod类型查看日期
[root@master ~]# kubectl exec test -- date
Mon Dec 20 02:23:45 UTC 2021

// 使用交互模式进入
[root@master ~]# kubectl exec -it test -- /bin/bash
root@test:/# ls
bin   docker-entrypoint.d   home   media  proc  sbin  tmp
boot  docker-entrypoint.sh  lib    mnt    root  srv   usr
dev   etc                   lib64  opt    run   sys   var
root@test:/# exit
exit

# deployment
// 创建一个deployment类型的nginx容器
[root@master ~]# kubectl create deployment nginx --image nginx
deployment.apps/nginx created

[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-85b98978db-mns5l   1/1     Running   0          28s
test                     1/1     Running   0          45m

// deployment类型查看日期
[root@master ~]# kubectl exec nginx-85b98978db-mns5l -- date 
Mon Dec 20 02:25:19 UTC 2021


[root@master ~]# kubectl exec -it nginx-85b98978db-mns5l /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.	// 未来会删除这个功能
root@nginx-85b98978db-mns5l:/# ls
bin   docker-entrypoint.d   home   media  proc  sbin  tmp
boot  docker-entrypoint.sh  lib    mnt    root  srv   usr
dev   etc                   lib64  opt    run   sys   var

# svc
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP   46h
nginx        ClusterIP   10.108.208.249   <none>        80/TCP    56m

// svc类型查看日期
[root@master ~]# kubectl exec svc/nginx -- dateMon Dec 20 02:31:08 UTC 2021

[root@master ~]# kubectl exec -it svc/nginx /bin/sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.	// 未来会删除这个功能
# ls
bin   docker-entrypoint.d   home   media  proc  sbin  tmp
boot  docker-entrypoint.sh  lib    mnt    root  srv   usr
dev   etc                   lib64  opt    run   sys   var

转发端口

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          6m18s
nginx-85b98978db-mns5l   1/1     Running     0          19m
test                     1/1     Running     0          64m
[root@master ~]# kubectl port-forward deployment/nginx 80	// 容器是80,本机也是80
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80

// 访问测试
[root@master ~]# curl 127.0.0.1:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>


[root@master ~]# kubectl port-forward deployment/nginx :80	// 本机随机端口,容器80端口
Forwarding from 127.0.0.1:34767 -> 80
Forwarding from [::1]:34767 -> 80
Handling connection for 34767

// 访问测试
[root@master ~]# curl 127.0.0.1:34767
<!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>


// 隐藏IP地址
[root@master ~]# kubectl port-forward --address 0.0.0.0 deployment/nginx :80
Forwarding from 0.0.0.0:32841 -> 80

cp:复制

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          17m
nginx-85b98978db-mns5l   1/1     Running     0          31m
test                     1/1     Running     0          75m

// 现在 test容器里面的tmp目录没有文件
[root@master ~]# kubectl exec test -- ls /tmp/

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

// 我把本机家目录下的 anaconda-ks.cfg文件复制到 test容器的 tmp目录下
[root@master ~]# kubectl cp /root/anaconda-ks.cfg test:/tmp/ 
[root@master ~]# kubectl exec test -- ls /tmp/
anaconda-ks.cfg

overwrite:覆盖

// 运行一个pod类型的nginx容器,标签设置为app=nginx
[root@master ~]# kubectl run nginx --image nginx --labels "app=test"
pod/nginx created

// 查看描述情况
[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.91.137
Start Time:   Mon, 20 Dec 2021 10:57:33 +0800
Labels:       app=test		// 标签设置成功
Annotations:  <none>
Status:       Running
IP:           10.244.1.19
......以下省略

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          19m
nginx                    1/1     Running     0          21s
nginx-85b98978db-mns5l   1/1     Running     0          33m
test                     1/1     Running     0          78m

// 使用 app=test 覆盖掉原有的 app=nginx 标签
[root@master ~]# kubectl label pod nginx --overwrite app=amu
pod/nginx unlabeled


// 查看描述情况
[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.91.137
Start Time:   Mon, 20 Dec 2021 10:57:33 +0800
Labels:       app=amu		// 标签覆盖成功
Annotations:  <none>
Status:       Running
IP:           10.244.1.19
......以下省略

label:添加标签

// 添加标签
[root@master ~]# kubectl label pod nginx test1=xixi
pod/nginx labeled

// 查看描述情况
[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.91.137
Start Time:   Mon, 20 Dec 2021 10:57:33 +0800
Labels:       app=amu
              test1=xixi		// 标签添加成功,这里不是覆盖了

api-resources:查看api资源详细信息

[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
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
......以下省略

api-versions:api可以版本号

[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

基础命令组合使用

使用上面的基础命令,进行两个小实验

自动扩展删除

测试一下之前做的自动创建是否还生效
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-jgbw6   1/1     Running   0          26s
// 删除nginx容器
[root@master ~]# kubectl delete pod nginx-6799fc88d8-jgbw6
pod "nginx-6799fc88d8-jgbw6" deleted

// 虽然我们删除了nginx容器,由于自动创建(最少一个),它又自动重新创建了一个nginx容器
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-hsm9j   1/1     Running   0          28s
// 删除 deployment控制器
[root@master ~]# kubectl delete deployment nginx
deployment.apps "nginx" deleted
// 控制器删除了,自动创建就失效了,不会再自动创建
[root@master ~]# kubectl get pods
No resources found in default namespace.

使用随机端口访问nginx页面

// 创建一个deployment类型的nginx容器,映射本机端口8080,容器内端口映射80
[root@master ~]# kubectl create deployment nginx --image nginx 
deployment.apps/nginx created

// 暴露本机端口8080,容器内端口映射80,类型为节点端口
[root@master ~]# kubectl expose deployment nginx --port 8080 --target-port 80 --type NodePort
service/nginx exposed
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP          2d
nginx        NodePort    10.108.211.140   <none>        8080:32014/TCP   5s

// 本机访问测试
[root@master ~]# curl 10.108.211.140: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>

web页面访问

访问页面本机 IP + 32014
在这里插入图片描述

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐