基操:

缩写:

# kubectl get option 缩写
-namespace        -n
--all-namespaces  -A
--filename=[]     -f
--kustomize=''    -k
--label-columns   -L
--output=''       -o
--recursive       -R
--selector        -l
--watch           -w

# kubectl create option 缩写
和get基本一致

# kubectl delete option 缩写
和get基本一致

# kubectl logs option 缩写
--container       -c
--follow          -f
--previous        -p
--selector        -l


# 对象缩写
NAME                              SHORTNAMES   APIGROUP                       NAMESPACED   KIND
bindings                                                                      true         Binding
componentstatuses                 cs                                          false        ComponentStatus
configmaps                        cm                                          true         ConfigMap
endpoints                         ep                                          true         Endpoints
events                            ev                                          true         Event
limitranges                       limits                                      true         LimitRange
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumeclaims            pvc                                         true         PersistentVolumeClaim
persistentvolumes                 pv                                          false        PersistentVolume
pods                              po                                          true         Pod
podtemplates                                                                  true         PodTemplate
replicationcontrollers            rc                                          true         ReplicationController
resourcequotas                    quota                                       true         ResourceQuota
secrets                                                                       true         Secret
serviceaccounts                   sa                                          true         ServiceAccount
services                          svc                                         true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
controllerrevisions                            apps                           true         ControllerRevision
daemonsets                        ds           apps                           true         DaemonSet
deployments                       deploy       apps                           true         Deployment
replicasets                       rs           apps                           true         ReplicaSet
statefulsets                      sts          apps                           true         StatefulSet
tokenreviews                                   authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch                          true         CronJob
jobs                                           batch                          true         Job
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
leases                                         coordination.k8s.io            true         Lease
events                            ev           events.k8s.io                  true         Event
daemonsets                        ds           extensions                     true         DaemonSet
deployments                       deploy       extensions                     true         Deployment
ingresses                         ing          extensions                     true         Ingress
networkpolicies                   netpol       extensions                     true         NetworkPolicy
podsecuritypolicies               psp          extensions                     false        PodSecurityPolicy
replicasets                       rs           extensions                     true         ReplicaSet
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
poddisruptionbudgets              pdb          policy                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io      true         RoleBinding
roles                                          rbac.authorization.k8s.io      true         Role
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment

kubectl get 操作:

  # 显示当前进程所有pods
  kubectl get pods  (default namespace 下所有pod)
  kubectl get pods -n namespace podname (指定namespace下的pod)
  kubectl get pods -A (所有namespace下的所有pod)
  
  # 显示pods详细信息
  kubectl get pods -o [format] # 详细显示,format可以是json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...
  
  # 显示RC的信息
  kubectl get replicationcontroller rcname
  
  # 显示Deployment信息
  kubectl get deployments.v1.apps -o [format]
  
  # 查询单个pod信息
  kubectl get pod podname -o [format]
  
  # 用yaml文件查询
  kubectl get -f pod.yaml -o [format]
  
  # 使用目录下的yaml文件查询,可以有多个yaml文件
  kubectl get -k dir/ # -k 不能和 -f -R同用
  
  # Return only the phase value of the specified pod.
  kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}
  
  # 在自定义列中列出资源信息
  kubectl get pod podname -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
  
  # 一起查询所有 RC和Service
  kubectl get rc,services
  
  # 通过类型和名称列出一个或多个资源
  kubectl get rc/web service/frontend pods/web-pod-13je7

kubectl create 操作:

# 使用当前目录的pod.json创建
  kubectl create -f ./pod.json
  
# 使用文件输入流,定向到创建命令
cat pod.json | kubectl create -f -

# 先以json格式编辑yaml,然后使用编辑后的yaml创建
kubectl create -f docker-registry.yaml --edit -o json

kubectl delete 操作:

  # 使用文件删除
  kubectl delete -f ./pod.json
  
  # 使用目录下的yaml删除
  kubectl delete -k dir
  
  # 使用文件输入流,重定向到删除命令
  cat pod.json | kubectl delete -f -
  
  # 使用同名的 pod(baz)、service(foo),进行删除
  kubectl delete pod,service baz foo
  
  # 使用label删除pod和service
  kubectl delete pods,services -l name=myLabel
  
  # 最小延迟的删除
  kubectl delete pod foo --now
  
  # 强制删除死节点上的pod
  kubectl delete pod foo --grace-period=0 --force
  
  # 删除所有pod
  kubectl delete pods --all

kubectl logs 操作:

  # 用于输出Pod中的容器或者特定资源的日志信息,如果Pod中只有一个容器,那就可以忽略容器名称。
  # logs == log 

  # 显示名称为nginx的Pod中只有一个容器的日志
  kubectl logs nginx
  
  # 显示名称为nginxPod中的多个容器的日志
  kubectl logs nginx --all-containers=true
  
  # 显示label app=nginx,的所有容器日志 
  kubectl logs -lapp=nginx --all-containers=true
  
  # 打开之前停掉的名称为web-1的pod中的名称为ruby的容器的日志
  kubectl logs -p -c ruby web-1
  
  # 打开名称为web-1的pod中的名称为ruby的容器的日志流
  kubectl logs -f -c ruby web-1
  
  # Begin streaming the logs from all containers in pods defined by label app=nginx
  kubectl logs -f -lapp=nginx --all-containers=true
  
  # 显示名称为nginx的pod中的,最近20行日志
  kubectl logs --tail=20 nginx
  
  # 显示名称为nginx的pod中,最近一小时的全部日志
  kubectl logs --since=1h nginx
  
  # 显示名称为hello的job中的第一个容器的日志
  kubectl logs job/hello
  
  # 显示名称为nginx的deployment中的容器叫做nginx-1的日志
  kubectl logs deployment/nginx -c nginx-1

kubectl describe 操作:

  # 显示指定资源的详细信息(命名空间是default)

  # 描述一个node信息
  kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
  
  # 描述名称为nginx的pod的信息
  kubectl describe pods/nginx
  
  # 通过pod.json描述pod信息
  kubectl describe -f pod.json
  
  # 描述所有pod信息
  kubectl describe pods
  
  # 通过label描述
  kubectl describe po -l name=myLabel # po是缩写,参考上面的缩写部分
  
  # Describe all pods managed by the 'frontend' replication controller (rc-created pods
  # get the name of the rc as a prefix in the pod the name).
  kubectl describe pods frontend

kubectl scale 操作: 

  # Scale a replicaset named 'foo' to 3.
  kubectl scale --replicas=3 rs/foo
  
  # Scale a resource identified by type and name specified in "foo.yaml" to 3.
  kubectl scale --replicas=3 -f foo.yaml
  
  # If the deployment named mysql's current size is 2, scale mysql to 3.
  kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
  
  # Scale multiple replication controllers.
  kubectl scale --replicas=5 rc/foo rc/bar rc/baz
  
  # Scale statefulset named 'web' to 3.
  kubectl scale --replicas=3 statefulset/web

查看namespace列表:

kubectl get namespaces

查看指定Pod信息:

kubectl get pods [-n namespace] podName 

查看所有Pod:

 kubectl get pods --all-namespaces

查看Pod启动状态:

kubectl describe pod [-n namespace] podName

查看Pod日志信息:

kubectl logs [-n namespace] api-gw

创建对象:

kubectl create -f xxx.yaml

删除对象:

kubectl delete xxx.yaml

查看Pod启动yaml

kubectl get pod [-n namespace] podName -o yaml

打标签:

kubectl label nodes nodeName slave=153

从容器复制文件到本地目录

kubectl cp podName:workDir/path1/path2/file.txt  /home/emg/target_file.txt

# 需要知道exec进入容器之后的工作目录是什么,如果是文件,需要指向一个本地的文件,这里使用workDir表示进入容器后的pwd

YAML 样例

nginx.yaml:

apiVersion: v1
kind: Pod # 对象类型为Pod,类型为k8s自定义,区分大小写
metadata: # 元数据描述
  name: nginx # 对象名称,自定义
  labels: # 对象标签,用于其它类型对象绑定时使用,例如下面的Service对象
     app: nginx
spec: # Pod对象中具体哪些内容详情
  containers: # 容器部分
    - name: nginx # 容器名称
      image: nginx # 启动容器用的镜像的名称
      imagePullPolicy: IfNotPresent # 镜像拉取策略:Never、Always(默认)、IfNotPresent(没有才拉取) 
      ports: # 容器端口
        - containerPort: 80
  restartPolicy: Always # 重启策略,详见docker restart策略
---
apiVersion: v1 
kind: Service # 对象类型为Service
metadata: # 元数据描述
  name: nginx-service
spec:
  type: NodePort # 一种端口映射策略
  sessionAffinity: ClientIP # session维持
  selector: # 选择器,对应label
    app: nginx
  ports:
    - port: 80 # 对应容器的端口
      nodePort: 30001 # 此node对应的外部访问port  The range of valid ports is 30000-32767

nodejsApp.yaml 普通Pod部署:

apiVersion: v1
kind: Pod
metadata:
  name: api
  namespace: kube-public # 指定namespace,如果没有,需要提前创建
  labels:
    app: api
spec:
  containers:
    - name: api
      image: registry.local/projectGroup/api:v1 # 此处是私有镜像库,需要进行配置,下面有说明
      imagePullPolicy: IfNotPresent
      volumeMounts: # 需要挂载配置文件
        - name: config-path # 对应下面的volumes的name
          mountPath: /home/ # 容器的路径
          readOnly: true # 是否只读
      ports:
        - containerPort: 3000
  volumes: # 挂载目录集合
  - name: config-path # 名称,用于被挂载
    hostPath: # 使用的 hostPath,还有 empDir等配置
      path: /data/config/api/ # 宿主机目录(node机器的目录)
  nodeSelector:
        slave: "184" # 指定调度到某台机器,slave=184是通过label命令给node机器打过label的
---
apiVersion: v1
kind: Service
metadata:
  name: api-service
  namespace: kube-public
spec:
  type: NodePort
  selector:
    app: api
  ports:
    - port: 3000
      nodePort: 30003 # 默认使用

nodeApp.yaml 多副本集部署:

apiVersion: apps/v1 # Deployment对象,需要这个版本
kind: Deployment
metadata:
  name: api-gw
  namespace: kube-public
  labels:
    app: api-Gateway
spec:
  replicas: 2
  selector:
    matchLabels:
      app: apigw # 表明Deployment需要如何寻找需要管理的Pod
  template:
    metadata:
      labels:
        app: apigw # 要被管理的资源
    spec:
      containers:
      - name: api-gw
        image: registry.local/project/api-gw:v1 # 私有镜像库
        imagePullPolicy: IfNotPresent
        volumeMounts:
        - name: config-path
          mountPath: /home/
          readOnly: true
        ports:
        - containerPort: 3000 # 镜像启动的容器内部进程,端口号
      volumes:
      - name: config-path
        hostPath:
          path: /data/config/api-gw/
---
apiVersion: v1
kind: Service
metadata:
  name: api-service
  namespace: kube-public
spec:
  type: NodePort
  selector:
    app: apigw # service需要绑定selector,而不是绑定deployment
  ports:
    - port: 3000 # 对应容器内部进程端口号
      nodePort: 30003

使用私有库:

  1. 保证有一台机器可以成功拉取私有库镜像
  2. 执行 echo $HOME找到home目录
  3. home/.docker/config.json 文件复制到 node机器的 /var/lib/kubelet/
  4. 拉取镜像时需要带上repository名称(例如 docker.io/nginx:latest。docker.io就是repository名称)
  5. 参考文档:https://kubernetes.io/docs/concepts/containers/images/#using-a-private-registry

Master VS Node

  1. master 只负责调度控制,对机器要求并不高
  2. master 在不将自己当作node添加到master中的情况下,master不会将pod调度到自己身上
  3. node是实际工作的机器,根据实际要求,可能需要较高的配置
  4. 所有node节点都需要有docker、k8s环境(node部分)

网络问题:

  1.  
Logo

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

更多推荐