kubectl基础

kubectl基本语法

  1. kubectl [command] [type] [name] [flags]
  • comand:指定要对资源执行的操作,例如create、get、describe、delete、exec、run、scale、edit、expose、set、rollout等。
  • type:指定资源类型,比如Namespace、Pod、Deployment、StatefulSet 、DaemonSet、Job、CronJob、ReplicaSet、Ingress,Endpoints、PersistentVolume、ConfigMap、Secret等。资源类型是大小写敏感的,开发者能使用单数、复数和缩略的形式。
  • name: 指定资源的名称,名称也大小写敏感的。
  • flags:指定可选的参数。例如,kubectl apply -f xxxx.yaml的-f表示从文件创建资源。

    从控制台创建

    创建Pod

    kubectl run mynginx --image=nginx
    

    查看pod

    # -owide 输出pod的详细信息
    # kubectl get pod -n <namespace> -owide
    [root@k8s-master develop]# kubectl get pod -owide
    NAME      READY   STATUS    RESTARTS   AGE   IP                NODE        NOMINATED NODE   READINESS GATES
    mynginx   1/1     Running   1          21h   192.168.169.141   k8s-node2   <none>           <none>
    

    进入Pod

    ```bash

    kubectl exec -it -n — /bin/sh

    kubectl exec -it mynginx — /bin/sh [root@k8s-master develop]# kubectl exec -it mynginx — /bin/sh

    curl localhost

    <!DOCTYPE html>

    Welcome to nginx!

    If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

# exit <a name="pZxJo"></a> ### 查看pod详情bash # kubectl describe pod kubectl describe pod mynginx [root@k8s-master develop]# kubectl describe pod mynginx Name: mynginx Namespace: default Priority: 0 Node: k8s-node2/10.1.1.9 Start Time: Tue, 26 Oct 2021 21:14:04 +0800 Labels: run=mynginx Annotations: cni.projectcalico.org/containerID: 4848da0ffa176fcc50dd036ffe837d3aff2dce1849c2916d2b1025f6fcc42509 cni.projectcalico.org/podIP: 192.168.169.141/32 cni.projectcalico.org/podIPs: 192.168.169.141/32 Status: Running IP: 192.168.169.141 IPs: IP: 192.168.169.141 Containers: mynginx: … [root@k8s-master develop]# curl 192.168.169.141 <!DOCTYPE html>

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

<a name="iO6Vc"></a> ### 删除Podbash # kubectl delete mynginx -n kubectl delete mynginx <a name="KhPUZ"></a> ## 从文件创建 <a name="QlePh"></a> ### 创建Podyaml apiVersion: v1 kind: Pod metadata: name: mynginx namespace: world spec: containers: - image: nginx name: mynginx ```yaml [root@k8s-master develop]# kubectl create -f mynginx-pod.yaml pod/mynginx created [root@k8s-master develop]# kubectl get pod -owide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES mynginx 1/1 Running 0 10s 192.168.169.144 k8s-node2 <none> <none> # Namespace ## 概述 大多数 kubernetes 资源(例如 Pod、Service、副本控制器等)都位于某些名字空间中。 但是名字空间资源本身并不在名字空间中。而且底层资源,例如节点和持久化卷不属于任何名字空间。 yaml # 位于名字空间中的资源 # kubectl api-resources --namespaced=true [root@k8s-master develop]# kubectl api-resources --namespaced=true NAME SHORTNAMES APIVERSION NAMESPACED KIND bindings v1 true Binding configmaps cm v1 true ConfigMap endpoints ep v1 true Endpoints events ev v1 true Event limitranges limits v1 true LimitRange persistentvolumeclaims pvc v1 true PersistentVolumeClaim pods po v1 true Pod podtemplates v1 true PodTemplate replicationcontrollers rc v1 true ReplicationController resourcequotas quota v1 true ResourceQuota secrets v1 true Secret serviceaccounts sa v1 true ServiceAccount services svc v1 true Service controllerrevisions apps/v1 true ControllerRevision daemonsets ds apps/v1 true DaemonSet deployments deploy apps/v1 true Deployment replicasets rs apps/v1 true ReplicaSet statefulsets sts apps/v1 true StatefulSet localsubjectaccessreviews authorization.k8s.io/v1 true LocalSubjectAccessReview horizontalpodautoscalers hpa autoscaling/v1 true HorizontalPodAutoscaler cronjobs cj batch/v1beta1 true CronJob jobs batch/v1 true Job leases coordination.k8s.io/v1 true Lease networkpolicies crd.projectcalico.org/v1 true NetworkPolicy networksets crd.projectcalico.org/v1 true NetworkSet endpointslices discovery.k8s.io/v1beta1 true EndpointSlice events ev events.k8s.io/v1 true Event ingresses ing extensions/v1beta1 true Ingress ingresses ing networking.k8s.io/v1 true Ingress networkpolicies netpol networking.k8s.io/v1 true NetworkPolicy poddisruptionbudgets pdb policy/v1beta1 true PodDisruptionBudget rolebindings rbac.authorization.k8s.io/v1 true RoleBinding roles rbac.authorization.k8s.io/v1 true Role # 不在名字空间中的资源 # kubectl api-resources --namespaced=false [root@k8s-master develop]# kubectl api-resources --namespaced=false NAME SHORTNAMES APIVERSION NAMESPACED KIND componentstatuses cs v1 false ComponentStatus namespaces ns v1 false Namespace nodes no v1 false Node persistentvolumes pv v1 false PersistentVolume mutatingwebhookconfigurations admissionregistration.k8s.io/v1 false MutatingWebhookConfiguration validatingwebhookconfigurations admissionregistration.k8s.io/v1 false ValidatingWebhookConfiguration customresourcedefinitions crd,crds apiextensions.k8s.io/v1 false CustomResourceDefinition apiservices apiregistration.k8s.io/v1 false APIService tokenreviews authentication.k8s.io/v1 false TokenReview selfsubjectaccessreviews authorization.k8s.io/v1 false SelfSubjectAccessReview selfsubjectrulesreviews authorization.k8s.io/v1 false SelfSubjectRulesReview subjectaccessreviews authorization.k8s.io/v1 false SubjectAccessReview certificatesigningrequests csr certificates.k8s.io/v1 false CertificateSigningRequest bgpconfigurations crd.projectcalico.org/v1 false BGPConfiguration bgppeers crd.projectcalico.org/v1 false BGPPeer blockaffinities crd.projectcalico.org/v1 false BlockAffinity clusterinformations crd.projectcalico.org/v1 false ClusterInformation felixconfigurations crd.projectcalico.org/v1 false FelixConfiguration globalnetworkpolicies crd.projectcalico.org/v1 false GlobalNetworkPolicy globalnetworksets crd.projectcalico.org/v1 false GlobalNetworkSet hostendpoints crd.projectcalico.org/v1 false HostEndpoint ipamblocks crd.projectcalico.org/v1 false IPAMBlock ipamconfigs crd.projectcalico.org/v1 false IPAMConfig ipamhandles crd.projectcalico.org/v1 false IPAMHandle ippools crd.projectcalico.org/v1 false IPPool kubecontrollersconfigurations crd.projectcalico.org/v1 false KubeControllersConfiguration flowschemas flowcontrol.apiserver.k8s.io/v1beta1 false FlowSchema prioritylevelconfigurations flowcontrol.apiserver.k8s.io/v1beta1 false PriorityLevelConfiguration ingressclasses networking.k8s.io/v1 false IngressClass runtimeclasses node.k8s.io/v1 false RuntimeClass podsecuritypolicies psp policy/v1beta1 false PodSecurityPolicy clusterrolebindings rbac.authorization.k8s.io/v1 false ClusterRoleBinding clusterroles rbac.authorization.k8s.io/v1 false ClusterRole priorityclasses pc scheduling.k8s.io/v1 false PriorityClass csidrivers storage.k8s.io/v1 false CSIDriver csinodes storage.k8s.io/v1 false CSINode storageclasses sc storage.k8s.io/v1 false StorageClass volumeattachments storage.k8s.io/v1 false VolumeAttachment Namespace隔离资源但不隔离网络。隔离网络需要使用NetworkPolicy资源,后面再说。 ## 案例 ### 查看所有的命名空间。 yaml [root@k8s-master develop]# kubectl get ns NAME STATUS AGE default Active 7d hello Active 71m kube-node-lease Active 7d kube-public Active 7d kube-system Active 7d world Active 70m ### 创建命名空间。 yaml # hello-ns.yaml apiVersion: v1 kind: Namespace metadata: name: hello yaml kubectl create -f hello-ns.yaml ### 命名空间中的资源是唯一的 yaml [root@k8s-master develop]# kubectl get pod NAME READY STATUS RESTARTS AGE mynginx 1/1 Running 1 2d19h [root@k8s-master develop]# kubectl run mynginx --image=nginx Error from server (AlreadyExists): pods "mynginx" already exists ### 网络不隔离 ```yaml # 查看default命名空间下面的pod [root@k8s-master develop]# kubectl get pod -owide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES mynginx 1/1 Running 1 2d19h 192.168.169.145 k8s-node2 mynginx2 1/1 Running 0 33s 192.168.169.147 k8s-node2 # 查看dev下面的pod [root@k8s-master develop]# kubectl get pod -n=dev -owide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES mynginx2 1/1 Running 0 20s 192.168.169.148 k8s-node2 # 进入dev的mynginx2,访问default下面的mynginx2 [root@k8s-master develop]# kubectl exec -it mynginx2 -n=dev — /bin/bash root@mynginx2:/# curl 192.168.169.147 <!DOCTYPE html>

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

<a name="lX4Tp"></a>
## 配置环境
<a name="vI5Fb"></a>
### 查看当前工作环境
```yaml
[root@k8s-master develop]# kubectl config current-context
kubernetes-admin@kubernetes

查看工作环境的配置

[root@k8s-master develop]# kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://cluster-endpoint:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED

配置工作环境

# 配置pro工作环境,指定其使用pro命名空间
[root@k8s-master develop]#   kubectl config set-context pro --namespace=pro \
>   --cluster=kubernetes \
>   --user=kubernetes-admin

# 配置dev工作环境,指定其使用dev命名空间
[root@k8s-master develop]#   kubectl config set-context dev --namespace=dev \
>   --cluster=kubernetes \
>   --user=kubernetes-admin

切换工作环境

[root@k8s-master develop]# kubectl config use-context dev
Switched to context "dev".

声明式API

kubectl的动作参数有很多,比如create、delete和expose等。这些都是命令式API,即可以将系统理解为一个状态机,你输入什么命令,状态机就会由某个状态转为另一状态,如果当前状态不能被应用指定的动作,就会报错。即命令式API是指将系统从一个状态转换至另一个状态。
而声明式API是指,我要什么状态,我想系统成为什么状态。
比如同样的创建命名空间。

# hello-ns.yaml
apiVersion: v1
kind: Namespace
metadata:
        name: hello

用命令式API就是

kubectl create -f hello-ns.yaml

如果你多次创建就会报错

[root@k8s-master develop]# kubectl create -f hello-ns.yaml
Error from server (AlreadyExists): error when creating "hello-ns.yaml": namespaces "hello" already exists

使用声明式API就不会存在在这个问题。

[root@k8s-master develop]# kubectl apply -f hello-ns.yaml
namespace/hello unchanged

因为对于声明式API来说,用户要的只是集群存在hello这么一个命名空间,而集群已经有了, 所以就不再需要创建了。如果hello这个命名空间修改了一些属性,比如新增一个label,使用声明式API不再需要考虑系统中是否存在这个命名空间。系统会自动满足我们的需求,将hello这个命名空间转换为我们需要的状态。

给命名空间创建label

不带label的hello命名空间。

[root@k8s-master develop]# kubectl describe ns hello
Name:         hello
Labels:       <none>
Annotations:  <none>
Status:       Active

No resource quota.

No LimitRange resource.

带label的hello命名空间

apiVersion: v1
kind: Namespace
metadata:
  name: hello
  labels:
    env: dev
[root@k8s-master develop]# kubectl apply -f hello-ns.yaml
namespace/hello configured

查看

[root@k8s-master develop]# kubectl describe ns hello
Name:         hello
Labels:       env=dev
Annotations:  <none>
Status:       Active

No resource quota.

No LimitRange resource.

还可以使用如下命令查看命名空间的label。

[root@k8s-master develop]# kubectl get namespace --show-labels
NAME              STATUS   AGE     LABELS
default           Active   10d     <none>
dev               Active   3d17h   <none>
hello             Active   3d19h   env=dev
kube-node-lease   Active   10d     <none>
kube-public       Active   10d     <none>
kube-system       Active   10d     <none>
pro               Active   3d17h   <none>
world             Active   3d19h   <none>