玩k8s----kubectl命令行管理工具
程序员文章站
2022-07-10 10:46:50
...
玩k8s----kubectl命令行管理工具
一:Kubectl管理
1.1: Kubectl 基本指令
- kubectl是管理k8s的命令行工具,通过生成json格式传递给apiserver进行一些操作
- 更全的kubectl命令请查看
kubectl --help
,以下仅列出常用的命令 - 查看更详细的帮助信息
kubectl create --help
查看create命令帮助信息
[aaa@qq.com bin]# 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 使用 replication controller, service, deployment 或者 pod
并暴露它作为一个 新的 Kubernetes Service '暴露服务,提供给别人访问'
run 在集群中运行一个指定的镜像
set 为 objects 设置一个指定的特征 '可以做设定版本更新'
Basic Commands (Intermediate): '中级基础指令'
explain 查看资源的文档
get 显示一个或更多 resources
edit 在服务器上编辑一个资源
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 为 Deployment, ReplicaSet, Replication Controller 或者 Job
设置一个新的副本数量 '做弹性伸缩'
autoscale 自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController
的副本数量 '自动做弹性伸缩'
Cluster Management Commands: '集群管理指令'
certificate 修改 certificate 资源.
cluster-info 显示集群信息
top Display Resource (CPU/Memory/Storage) 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 复制 files 和 directories 到 containers 和从容器中复制 files 和
directories. '从本地当中复制到容器当中'
auth Inspect authorization '验证'
Advanced Commands: '高级指令'
apply 通过文件名或标准输入流(stdin)对资源进行配置
patch 使用 strategic merge patch 更新一个资源的 field(s)
replace 通过 filename 或者 stdin替换一个资源
wait Experimental: Wait for a specific condition on one or many
resources.
convert 在不同的 API versions 转换配置文件
Settings Commands:
label 更新在这个资源上的 labels '打标签'
annotate 更新一个资源的注解
completion Output shell completion code for the specified shell (bash or
zsh) '输出shell终端的代码到指定的shell'
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).
命令 | 描述 |
---|---|
create | 通过文件名或标准输入创建资源 |
expose | 将一个资源公开为一个新的Service |
run | 在集群中运行一个特定的镜像 |
set | 在对象上设置特定的功能 |
get | 显示一个或多个资源 |
explain | 文档参考资料 |
edit | 使用默认的编辑器编辑一个资源。 |
delete | 通过文件名、标准输入、资源名称或标签选择器来删除资源。 |
rollout | 管理资源的发布 |
rolling-update | 对给定的复制控制器滚动更新 |
scale | 扩容或缩容Pod数量,Deployment、ReplicaSet、RC或Job |
autoscale | 创建一个自动选择扩容或缩容并设置Pod数量 |
certificate | 修改证书资源 |
cluster-info | 显示集群信息 |
top | 显示资源(CPU/Memory/Storage)使用。需要Heapster运行 |
cordon | 标记节点不可调度 |
uncordon | 标记节点可调度 |
drain | 驱逐节点上的应用,准备下线维护 |
taint | 修改节点taint标记 |
describe | 显示特定资源或资源组的详细信息 |
logs | 在一个Pod中打印一个容器日志。如果Pod只有一个容器,容器名称是可选的 |
attach | 附加到一个运行的容器 |
exec | 执行命令到容器 |
port-forward | 转发一个或多个本地端口到一个pod |
proxy | 运行一个proxy到Kubernetes API server |
cp | 拷贝文件或目录到容器中 |
auth | 检查授权 |
apply | 通过文件名或标准输入对资源应用配置;创建和更新资源 |
patch | 使用补丁修改、更新资源的字段 |
replace | 通过文件名或标准输入替换一个资源 |
convert | 不同的API版本之间转换配置文件 |
label | 更新资源上的标签 |
annotate | 更新资源上的注释 |
completion | 用于实现kubectl工具自动补全 |
api-versions | 打印受支持的API版本 |
config | 修改kubeconfig文件(用于访问API,比如配置认证信息) |
help | 所有命令帮助 |
plugin | 运行一个命令行插件 |
version | 打印客户端和服务版本信息 |
1.2:使用kubectl管理应用生命周期
- 项目的生命周期:创建–》发布–》更新–》回滚–》删除
1、创建
kubectl create deployment web --image=nginx
kubectl get deploy,pods
或kubectl run web --image=nginx:latest --port=80 --replicas=3 "run命令默认创建deploy"
kubectl get pods -w '-w:动态查看'
2、发布
kubectl expose deployment web --port=8080 --type=NodePort --target-port=8080 --name=web
kubectl get service '查看原有的service服务'
--port=80 "pod的服务端口"
--target-port=8080 "对接tomcat镜像服务的端口,这里target-port要和跑的容器服务端口(container-port)一致"
kubectl get pods -o wide '网络状态详细信息,查看pods在哪个节点上'
kubectl get endpoints '查看关联后端的节点'
3、升级
kubectl set image deployment/web nginx=nginx:1.15
kubectl rollout status deployment/nginx-deployment # 查看升级状态
'容器的更新:滚动更新,创建一个runing后,删一个,保证副本数量,然后再创建一个,依次滚动更新,容器只有删除和创建,没有重启的'
4、回滚
kubectl rollout history deployment/web # 查看发布记录
kubectl rollout undo deployment/web # 回滚最新版本
kubectl rollout undo deployment/web --to-revision=2 # 回滚指定版本
5. 副本扩容
kubectl scale deployment/web --replicas=3
6、删除
kubectl delete deploy/web
kubectl delete svc/web
kubectl delete pod/nginx
7.查看某个pod信息,用于pod排障
kubectl describe pod/liveness-exec
kubectl logs liveness-exec
8.进入pod
kubectl exec -it pod-name bash
- 详解k8s中的port
- port是k8s集群内部访问service的端口,即通过clusterIP: port可以访问到某个service
- nodePort
nodePort是外部访问k8s集群中service的端口,通过nodeIP: nodePort可以从外部访问到某个service。 - targetPort
targetPort是pod的端口,从port和nodePort来的流量经过kube-proxy流入到后端pod的targetPort上,最后进入容器。 - containerPort
containerPort是pod内部容器的端口,targetPort映射到containerPort。
示例:
[aaa@qq.com ~]# kubectl create deployment tomcat --image=tomcat
deployment.apps/tomcat created
[aaa@qq.com ~]# kubectl expose deployment tomcat --port=8080 --type=NodePort --target-port=8080 --name=tomcat
service/tomcat exposed
[aaa@qq.com ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 25h
tomcat-85c798b5d5-qztp9 1/1 Running 0 3m13s
[aaa@qq.com ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx 1/1 Running 0 25h 10.244.0.2 k8s-node2 <none> <none>
tomcat-85c798b5d5-qztp9 1/1 Running 0 3m20s 10.244.1.10 k8s-node1 <none> <none>
[aaa@qq.com ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.0.0.1 <none> 443/TCP 27h
tomcat NodePort 10.0.0.26 <none> 8080:32120/TCP 45s
"资源分配在nodee1节点对外暴露端口号32120"
//没有首页文件,报404
[aaa@qq.com ~]# kubectl exec -it tomcat-85c798b5d5-qztp9 bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead.
root@tomcat-85c798b5d5-qztp9:/usr/local/tomcat# cd webapps
root@tomcat-85c798b5d5-qztp9:/usr/local/tomcat/webapps# mkdir ROOT
root@tomcat-85c798b5d5-qztp9:/usr/local/tomcat/webapps# cd ROOT
root@tomcat-85c798b5d5-qztp9:/usr/local/tomcat/webapps/ROOT# echo "hello world" > index.html
升级:
[aaa@qq.com ~]# kubectl set image deployment/nginx-web nginx=nginx:1.14
deployment.apps/nginx-web image updated
[aaa@qq.com ~]# kubectl rollout history deployment/nginx-web
deployment.apps/nginx-web
REVISION CHANGE-CAUSE
1 <none>
2 <none>
[aaa@qq.com ~]# kubectl rollout undo deployment/nginx-web
deployment.apps/nginx-web rolled back
[aaa@qq.com ~]# kubectl rollout history deployment/nginx-web
deployment.apps/nginx-web
REVISION CHANGE-CAUSE
3 <none>
4 <none>
[aaa@qq.com ~]# kubectl create deployment nginx --image=nginx
deployment.apps/nginx created
[aaa@qq.com ~]# kubectl expose deployment nginx --port=80 --type=NodePort --target-port=80 --name=nginx-web
service/nginx-web exposed
[aaa@qq.com ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.0.0.1 <none> 443/TCP 27h
nginx-web NodePort 10.0.0.170 <none> 80:32479/TCP 6s
tomcat NodePort 10.0.0.26 <none> 8080:32120/TCP 15m
[aaa@qq.com ~]# kubectl set image deployment/nginx nginx=nginx:1.15
deployment.apps/nginx image updated
[aaa@qq.com ~]# kubectl rollout history deployment/nginx
deployment.apps/nginx
REVISION CHANGE-CAUSE
1 <none>
2 <none>
[aaa@qq.com ~]# kubectl rollout status deployment/nginx
deployment "nginx" successfully rolled out
//回滚
[aaa@qq.com ~]# kubectl get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 1/1 1 1 9m34s
tomcat 1/1 1 1 26m
[aaa@qq.com ~]# kubectl rollout undo deployment/nginx
deployment.apps/nginx rolled back
[aaa@qq.com ~]# kubectl rollout history deployment/nginx
deployment.apps/nginx
REVISION CHANGE-CAUSE
2 <none>
3 <none>
[aaa@qq.com ~]# kubectl rollout undo deployment/nginx --to-revision=2
deployment.apps/nginx rolled back
-
删除pode前要删除deployment ,要不然删不掉,删除deployment后pod也会自动删除
pod是K8S部署的最小资源, 使用deployment控制器去管理pod,pod的更高一层的管理就是deployment
[aaa@qq.com ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 25h
nginx-5749bd847d-pbwr5 1/1 Running 0 2m55s
tomcat-85c798b5d5-qztp9 1/1 Running 0 34m
[aaa@qq.com ~]# kubectl delete pod tomcat-85c798b5d5-qztp9
pod "tomcat-85c798b5d5-qztp9" deleted
[aaa@qq.com ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 25h
nginx-5749bd847d-pbwr5 1/1 Running 0 3m33s
tomcat-85c798b5d5-68f99 1/1 Running 0 8s
[aaa@qq.com ~]# kubectl get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 1/1 1 1 13m
tomcat 1/1 1 1 31m
[aaa@qq.com ~]# kubectl delete deployment/nginx
deployment.apps "nginx" deleted
[aaa@qq.com ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.0.0.1 <none> 443/TCP 27h
nginx-web NodePort 10.0.0.170 <none> 80:32479/TCP 23m
tomcat NodePort 10.0.0.26 <none> 8080:32120/TCP 38m
[aaa@qq.com ~]# kubectl delete svc/nginx-web
service "nginx-web" deleted
[aaa@qq.com ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 25h
tomcat-85c798b5d5-68f99 1/1 Running 0 7m19s
//删除deployment后,它管理的pod也将自动删除
- 查看资源对象简写
[aaa@qq.com ~]# kubectl api-resources
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
networkpolicies netpol networking.k8s.io true NetworkPolicy
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
storageclasses sc storage.k8s.io false StorageClass
volumeattachments storage.k8s.io false VolumeAttachment
1.3:pod资源的调度
- 当我们创建多个pod、service资源时,kube-proxy会做负载均衡,此时我们通过访问任意node节点ip可以访问所有的资源
- kubernetes中kube-proxy支持三种模式,在v1.8之前我们使用的是iptables以及userspace两种模式,在kubernetes1.8之后加入了ipvs
[aaa@qq.com ~]# yum -y install ipvsadm
[aaa@qq.com ~]# ipvsadm -L -n '查看调度,-L表示列表,-n表示以数字化显示'
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 20.0.0.54:30001 rr
-> 172.17.58.2:8443 Masq 1 0 0
TCP 20.0.0.54:36865 rr
-> 172.17.46.3:80 Masq 1 0 0
-> 172.17.46.4:80 Masq 1 0 0
-> 172.17.58.3:80 Masq 1 0 0
//查看日志测试轮询
[aaa@qq.com ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-dbddb74b8-9csfl 1/1 Running 0 23h
nginx-test-59f87d55d6-9nkvl 1/1 Running 0 33m
nginx-test-59f87d55d6-c52ph 1/1 Running 0 33m
nginx-test-59f87d55d6-ngl4v 1/1 Running 0 33m
[aaa@qq.com ~]# kubectl logs nginx-test-59f87d55d6-9nkvl
[aaa@qq.com ~]# kubectl logs nginx-test-59f87d55d6-c52ph
[aaa@qq.com ~]# kubectl logs nginx-test-59f87d55d6-ngl4v
...省略内容
172.17.46.0 - - [10/Oct/2020:02:27:59 +0000] "GET /favicon.ico HTTP/1.1" 404 556 "http://20.0.0.54:36865/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-"
通过示例得知:
1、快速部署、回滚(快速原因是因为用现在镜像起副本,无需准备环境和测试)
2、管理方便
3、容器挂掉自动拉起,自我修复
4、降低运维复杂度
5、环境治理
6、提高资源利用率