kubectl?命令詳解
一、常用命令
1、獲取信息
#獲取節(jié)點信息 kubectl get nodes #獲取pod信息 kubectl get pods #獲取pod信息包含具體在哪個節(jié)點 kubectl get pods -o wide
2、部署
# 部署pod kubectl create deployment tomcat9 --image=tomcat:9.0.102-jre17 # 發(fā)布service # --post=80 --target-post=8080 : pod的80端口映射容器的8080端口 # --type=NodePort : service會代理pod的80端口 kubectl expose deployment tomcat9 --port=8080 --target-port=8080 --type=NodePort # --dry-run 表示測試不實際運行 # -o yaml 生成yaml # > tomcat.yaml 輸出到tomcat.yaml #根據kubectl create deployment tomcat9 --image=tomcat:9.0.102-jre17生成yaml并輸出到tomcat.yaml kubectl create deployment tomcat9 --image=tomcat:9.0.102-jre17 --dry-run -o yaml > tomcat.yaml # 應用tomcat.yaml(根據上面命令生成的 tomcat.yaml), 實際上和kubectl create deployment tomcat6 --image=tomcat:9.0.102-jre17一樣的效果,只是yaml可以自己寫更靈活 kubectl apply -f tomcat.yaml
二、基本命令
使用以下語法從終端窗口運行 kubectl 命令:
kubectl [command] [TYPE] [NAME] [flags]
其中 command
、TYPE
、NAME
和 flags
分別是:
command
:指定要對一個或多個資源執(zhí)行的操作,例如create
、get
、describe
、delete
。TYPE
:指定資源類型。資源類型不區(qū)分大小寫, 可以指定單數、復數或縮寫形式。NAME
:指定資源的名稱。名稱區(qū)分大小寫。 如果省略名稱,則顯示所有資源的詳細信息。例如:kubectl get pods
。flags
: 指定可選的參數。例如,可以使用-s
或--server
參數指定 Kubernetes API 服務器的地址和端口。
在對多個資源執(zhí)行操作時,你可以按類型和名稱指定每個資源,或指定一個或多個文件,要按類型和名稱指定資源:
要對所有類型相同的資源進行分組,請執(zhí)行以下操作:TYPE1 name1 name2 name<#>
。
例子:kubectl get pod example-pod1 example-pod2
分別指定多個資源類型:TYPE1/name1 TYPE1/name2 TYPE2/name3
TYPE<#>/name<#>。
例子:kubectl get pod/example-pod1 replicationcontroller/example-rc1
用一個或多個文件指定資源:-f file1 -f file2 -f file<#>
例子:kubectl get -f ./pod.yaml
(為什么使用 YAML 而不是 JSON, 是因為 YAML 對用戶更友好, 特別是對于配置文件)
1、操作
操作名稱 | 描述 | 語法 | 示例 |
---|---|---|---|
get | 列出指定類型的資源 | kubectl get <資源類型> [flags] | kubectl get pods -n kube-system |
describe | 顯示資源詳細配置和狀態(tài) | kubectl describe <資源類型>/<資源名稱> | kubectl describe node/node01 |
create | 通過文件創(chuàng)建資源 | kubectl create -f <文件路徑> | kubectl create -f deployment.yaml |
apply | 通過文件更新/創(chuàng)建資源(冪等) | kubectl apply -f <文件路徑> | kubectl apply -f service.yaml |
delete | 刪除指定資源 | kubectl delete <資源類型>/<資源名稱> | kubectl delete configmap/app-config |
logs | 輸出容器日志流 | kubectl logs <Pod名稱> [-c 容器名] | kubectl logs nginx-pod --tail=100 |
exec | 在容器中執(zhí)行交互命令 | kubectl exec -it <Pod名稱> -- <命令> | kubectl exec -it redis-pod -- /bin/sh |
port-forward | 將本地端口映射到Pod端口 | kubectl port-forward <資源類型>/<名稱> <本地端口>:<目標端口> | kubectl port-forward service/nginx 8080:80 |
scale | 調整Deployment副本數 | kubectl scale deploy/<名稱> --replicas=<數量> | kubectl scale deploy/web-server --replicas=5 |
rollout | 管理資源部署,包含子命令status(查看狀態(tài))、history(查看歷史版本)、undo(回滾操作)、pause(暫停)、restart(恢復更新) | kubectl rollout undo <資源類型>/<名稱> | kubectl rollout undo deployment/frontend |
top | 顯示Pod/Node資源消耗 | kubectl top [pods|nodes] | kubectl top pods --sort-by=cpu |
edit | 直接編輯資源定義 | kubectl edit <資源類型>/<資源名稱> | kubectl edit deployment/backend |
label | 為資源添加/修改標簽 | kubectl label <資源類型> <名稱> <鍵>=<值> | kubectl label nodes node01 disktype=ssd |
config | 切換kubeconfig上下文 | kubectl config use-context <上下文名稱> | kubectl config use-context prod-cluster |
patch | 通過JSON補丁修改資源 | kubectl patch <資源類型>/<名稱> -p '<補丁內容>' | kubectl patch deploy/nginx -p '{"spec":{"replicas":3}}' |
cp | 在容器和本地間傳輸文件 | kubectl cp <源路徑> <目標路徑> | kubectl cp default/nginx-pod:/log.txt ./local.log |
taint | 管理節(jié)點的調度污點 | kubectl taint nodes <節(jié)點名> <鍵>=<值>:<效果> | kubectl taint nodes node01 app=test:NoSchedule |
cordon/uncordon | 禁止/允許節(jié)點調度Pod | kubectl cordon/uncordon <節(jié)點名> | kubectl cordon node02 |
drain | 安全驅逐節(jié)點上的Pod | kubectl drain <節(jié)點名> [--ignore-daemonsets] | kubectl drain node03 --delete-emptydir-data |
run | 快速運行臨時容器 | kubectl run <名稱> --image=<鏡像> [-- <命令] | kubectl run debug-tool --image=busybox -- sleep 3600 |
diff | 對比集群配置與本地文件的差異 | kubectl diff -f <文件路徑> [flags] | kubectl diff -f updated-deployment.yaml |
expose | 將資源暴露為 Kubernetes 服務 | kubectl expose <資源類型>/<名稱> [--port=端口] [--target-port=目標端口] | kubectl expose deploy/nginx --port=80 --target-port=9376 |
proxy | 創(chuàng)建到 Kubernetes API 的代理通道 | kubectl proxy [--port=端口] [--address=地址] | kubectl proxy --port=8080 --address='192.168.1.100' |
set | 動態(tài)修改資源配置(鏡像/環(huán)境變量/資源限制) | kubectl set <子命令> <資源類型>/<名稱> [參數] | kubectl set image deploy/nginx nginx=1.25.2-alpine |
explain | 查看資源配置字段的文檔說明 | kubectl explain [<資源類型>.<字段路徑>] [--recursive] | kubectl explain pod.spec.containers.resources.limits |
補充說明
- 表格中所有命令支持 -n <命名空間> 指定命名空間,--all-namespaces 查看全集群資源
- 資源類型支持縮寫(如 po=pods, deploy=deployments, svc=services)
- 使用 --dry-run=client -o yaml 可生成資源模板(如 kubectl create deploy test --image=nginx --dry-run=client -o yaml)
- 生產環(huán)境建議結合 kubectl diff -f <文件> 預演配置變更
- 資源名稱需替換為實際環(huán)境中的標識符
- 可通過 kubectl explain <資源字段> 查看資源配置字段說明
- 時間敏感操作(如日志查看)可結合 --since 參數(如 --since=1h)
使用技巧與注意事項
多文件操作
# 批量應用目錄下所有配置 -R:遞歸應用某個目錄及其子目錄下的所有 YAML/JSON 文件 kubectl apply -f ./manifests/ -R
資源選擇器組合
# 聯合使用文件選擇與標簽過濾 kubectl delete -f deploy.yaml -l app=critical
輸出格式化
# 生成資源配置模板(YAML 與 JSON 互轉) kubectl get deploy/nginx -o yaml > nginx-template.yaml
版本控制集成
# 記錄操作歷史(需配合 --record 參數) kubectl apply -f deploy.yaml --record
- 安全提示:使用 --force 刪除、drain 節(jié)點等高風險操作前,務必通過 --dry-run=server 驗證影響范圍。
2、資源
資源名 | 縮寫名 | API 版本 | 按命名空間 | 資源類型 |
---|---|---|---|---|
Core/v1 資源 | ||||
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 |
replicationcontrollers | rc | v1 | true | ReplicationController |
secrets | - | v1 | true | Secret |
services | svc | v1 | true | Service |
Apps 工作負載資源 | ||||
daemonsets | ds | apps/v1 | true | DaemonSet |
deployments | deploy | apps/v1 | true | Deployment |
statefulsets | sts | apps/v1 | true | StatefulSet |
replicasets | rs | apps/v1 | true | ReplicaSet |
Network 網絡資源 | ||||
ingresses | ing | networking.k8s.io/v1 | true | Ingress |
networkpolicies | netpol | networking.k8s.io/v1 | true | NetworkPolicy |
擴展與安全資源 | ||||
horizontalpodautoscalers | hpa | autoscaling/v2 | true | HorizontalPodAutoscaler |
cronjobs | cj | batch/v1 | true | CronJob |
certificatesigningrequests | csr | certificates.k8s.io/v1 | false | CertificateSigningRequest |
poddisruptionbudgets | pdb | policy/v1 | true | PodDisruptionBudget |
storageclasses | sc | storage.k8s.io/v1 | false | StorageClass |
RBAC 權限資源 | ||||
clusterroles | - | rbac.authorization.k8s.io/v1 | false | ClusterRole |
rolebindings | - | rbac.authorization.k8s.io/v1 | true | RoleBinding |
關鍵特性標注
API 版本差異
PodSecurityPolicy
(psp
) 使用已棄用的policy/v1beta1
(Kubernetes 1.25+ 移除)FlowSchema
/PriorityLevelConfiguration
使用測試版 APIflowcontrol.apiserver.k8s.io/v1beta2
命名空間隔離性
- 集群級資源(
false
):nodes
,persistentvolumes
,storageclasses
- 命名空間級資源(
true
):pods
,services
,configmaps
高頻縮寫對照
縮寫 | 全稱 | 使用場景 |
---|---|---|
ds | DaemonSet | 節(jié)點守護進程部署 |
hpa | HorizontalPodAutoscaler | 自動水平擴縮容 |
pdb | PodDisruptionBudget | 維護期 Pod 中斷預算 |
使用建議
# 查詢資源縮寫(含擴展資源) kubectl api-resources --verbs=list -o wide # 檢查特定資源的 API 版本兼容性 kubectl explain <resource> --api-version=<version>
3、可選參數
Flag 參數 | 默認值 | 適用命令 | 功能描述 |
---|---|---|---|
--namespace=<ns> | default | 所有命令 | 指定操作的命名空間,縮寫 -n |
--kubeconfig=<path> | ~/.kube/config | 所有命令 | 指定 Kubernetes 配置文件路徑 |
--output=<format> | text | get/describe 等 | 輸出格式控制(json , yaml , wide , name ),縮寫 -o |
--dry-run=<mode> | none | apply/create | 試運行模式(client /server /none ),用于驗證配置 |
--force | false | delete | 強制刪除資源(繞過優(yōu)雅刪除策略) |
--selector=<label> | 無 | 資源查詢命令 | 按標簽篩選資源,縮寫 -l |
--field-selector=<query> | 無 | get | 按字段條件篩選資源(如 status.phase=Running ) |
--record | false | apply/set | 在資源注解中記錄命令操作歷史 |
--server=<address> | 無 | 所有命令 | 直接指定 Kubernetes API 服務器地址 |
--insecure-skip-tls-verify | false | 所有命令 | 跳過 TLS 證書驗證(僅測試環(huán)境使用) |
--filename | 無 | apply /create /delete /diff /replace /get /explain 等 | 從 本地文件/目錄/URL/標準輸入流 加載資源配置,驅動聲明式或命令式操作,縮寫 -f |
特殊場景參數擴展表
Flag 參數 | 典型使用場景 | 示例命令 |
---|---|---|
--watch / -w | 實時監(jiān)控資源變化 | kubectl get pods -w |
--timeout=<duration> | 設置命令超時時間(如 30s , 5m ) | kubectl delete pod --timeout=10s |
--all | 操作全部資源(慎用) | kubectl delete pods --all |
--show-labels | 顯示資源標簽列 | kubectl get pods --show-labels |
--sort-by=<jsonpath> | 按字段排序輸出結果 | kubectl get pods --sort-by=.metadata.creationTimestamp |
使用說明
- 命令兼容性:不同子命令支持的 flags 存在差異(如
--replicas
僅適用于kubectl scale
) - 動態(tài)查看幫助:
# 查看全局 flags kubectl options # 查看子命令專屬 flags kubectl <command> --help
參考資料:
到此這篇關于kubectl 命令的文章就介紹到這了,更多相關kubectl 命令內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Google?Kubernetes?Engine?集群實戰(zhàn)詳解
這篇文章主要為大家介紹了Google?Kubernetes?Engine?集群實戰(zhàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08tkestack/gpu-manager在k8s1.23版本之后的使用方法
這篇文章主要介紹了tkestack/gpu-manager在k8s1.23版本之后的使用,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04