文档
命令说明
1. 下载 kubectl 的二进制文件
下载地址: https://dl.k8s.io/release/kubectl版本/bin/linux/amd64/kubectl
示例:
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
curl -LO "https://dl.k8s.io/release/v1.29.0/bin/linux/amd64/kubectl"
2. 安装
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
chmod +x kubectl
mkdir -p ~/.local/bin
mv ./kubectl ~/.local/bin/kubectl
3. 检查安装是否成功(查看版本)
kubectl version --client
1. 添加仓库
vim /etc/zypp/repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://pkgs.k8s.io/core:/stable:/v1.29/rpm/
enabled=1
gpgcheck=1
gpgkey=https://pkgs.k8s.io/core:/stable:/v1.29/rpm/repodata/repomd.xml.key
若需安装其他版本的 Kubectl,将上方的
v1.29
替换为指定版本即可
zypper refresh
2. 安装 Kubectl
kubectl install -y kubectl
3. 验证安装
kubectl version --client
1. 添加仓库
vim /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://pkgs.k8s.io/core:/stable:/v1.29/rpm/
enabled=1
gpgcheck=1
gpgkey=https://pkgs.k8s.io/core:/stable:/v1.29/rpm/repodata/repomd.xml.key
若需安装其他版本的 Kubectl,将上方的
v1.29
替换为指定版本即可
yum clean all
yum makecache
2. 安装
yum install -y kubectl
3. 验证安装
kubectl version --client
1. 下载二进制包
下载地址: https://dl.k8s.io/release/kubectl版本/bin/windows/amd64/kubectl.exe
示例:
最新版本
查看最新版本: https://cdn.dl.k8s.io/release/stable.txt
下载二进制包: https://dl.k8s.io/release/kubectl最新版本/bin/windows/amd64/kubectl.exe
指定版本(此处下载 v1.26.5 版本)
下载二进制包: https://dl.k8s.io/release/v1.26.5/bin/windows/amd64/kubectl.exe
2. 安装(配置环境变量)
新建环境变量 KUBECTL_HOME
,值为 kubectl 二进制文件路径,然后将 KUBECTL_HOME
添加到环境变量 Path
中
3. 验证安装
在 CMD 中执行如下命令:
kubectl version --client
1. 安装 bash-completion
zypper install -y bash-completion
yum install -y bash-completion
2. 生成补全命令脚本
kubectl completion bash > /etc/bash_completion.d/kubernetes.sh
脚本内容示例:
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# bash completion V2 for kubectl -*- shell-script -*-
__kubectl_debug()
{
if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
fi
}
# Macs have bash3 for which the bash-completion package doesn't include
# _init_completion. This is a minimal version of that function.
__kubectl_init_completion()
{
COMPREPLY=()
_get_comp_words_by_ref "$@" cur prev words cword
}
# This function calls the kubectl program to obtain the completion
# results and the directive. It fills the 'out' and 'directive' vars.
__kubectl_get_completion_results() {
local requestComp lastParam lastChar args
# Prepare the command to request completions for the program.
# Calling ${words[0]} instead of directly kubectl allows to handle aliases
args=("${words[@]:1}")
requestComp="${words[0]} __complete ${args[*]}"
lastParam=${words[$((${#words[@]}-1))]}
lastChar=${lastParam:$((${#lastParam}-1)):1}
__kubectl_debug "lastParam ${lastParam}, lastChar ${lastChar}"
if [[ -z ${cur} && ${lastChar} != = ]]; then
# If the last parameter is complete (there is a space following it)
# We add an extra empty parameter so we can indicate this to the go method.
__kubectl_debug "Adding extra empty parameter"
requestComp="${requestComp} ''"
fi
# When completing a flag with an = (e.g., kubectl -n=<TAB>)
# bash focuses on the part after the =, so we need to remove
# the flag part from $cur
if [[ ${cur} == -*=* ]]; then
cur="${cur#*=}"
fi
__kubectl_debug "Calling ${requestComp}"
# Use eval to handle any environment variables and such
out=$(eval "${requestComp}" 2>/dev/null)
# Extract the directive integer at the very end of the output following a colon (:)
directive=${out##*:}
# Remove the directive
out=${out%:*}
if [[ ${directive} == "${out}" ]]; then
# There is not directive specified
directive=0
fi
__kubectl_debug "The completion directive is: ${directive}"
__kubectl_debug "The completions are: ${out}"
}
__kubectl_process_completion_results() {
local shellCompDirectiveError=1
local shellCompDirectiveNoSpace=2
local shellCompDirectiveNoFileComp=4
local shellCompDirectiveFilterFileExt=8
local shellCompDirectiveFilterDirs=16
local shellCompDirectiveKeepOrder=32
if (((directive & shellCompDirectiveError) != 0)); then
# Error code. No completion.
__kubectl_debug "Received error from custom completion go code"
return
else
if (((directive & shellCompDirectiveNoSpace) != 0)); then
if [[ $(type -t compopt) == builtin ]]; then
__kubectl_debug "Activating no space"
compopt -o nospace
else
__kubectl_debug "No space directive not supported in this version of bash"
fi
fi
if (((directive & shellCompDirectiveKeepOrder) != 0)); then
if [[ $(type -t compopt) == builtin ]]; then
# no sort isn't supported for bash less than < 4.4
if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then
__kubectl_debug "No sort directive not supported in this version of bash"
else
__kubectl_debug "Activating keep order"
compopt -o nosort
fi
else
__kubectl_debug "No sort directive not supported in this version of bash"
fi
fi
if (((directive & shellCompDirectiveNoFileComp) != 0)); then
if [[ $(type -t compopt) == builtin ]]; then
__kubectl_debug "Activating no file completion"
compopt +o default
else
__kubectl_debug "No file completion directive not supported in this version of bash"
fi
fi
fi
# Separate activeHelp from normal completions
local completions=()
local activeHelp=()
__kubectl_extract_activeHelp
if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
# File extension filtering
local fullFilter filter filteringCmd
# Do not use quotes around the $completions variable or else newline
# characters will be kept.
for filter in ${completions[*]}; do
fullFilter+="$filter|"
done
filteringCmd="_filedir $fullFilter"
__kubectl_debug "File filtering command: $filteringCmd"
$filteringCmd
elif (((directive & shellCompDirectiveFilterDirs) != 0)); then
# File completion for directories only
local subdir
subdir=${completions[0]}
if [[ -n $subdir ]]; then
__kubectl_debug "Listing directories in $subdir"
pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
else
__kubectl_debug "Listing directories in ."
_filedir -d
fi
else
__kubectl_handle_completion_types
fi
__kubectl_handle_special_char "$cur" :
__kubectl_handle_special_char "$cur" =
# Print the activeHelp statements before we finish
if ((${#activeHelp[*]} != 0)); then
printf "\n";
printf "%s\n" "${activeHelp[@]}"
printf "\n"
# The prompt format is only available from bash 4.4.
# We test if it is available before using it.
if (x=${PS1@P}) 2> /dev/null; then
printf "%s" "${PS1@P}${COMP_LINE[@]}"
else
# Can't print the prompt. Just print the
# text the user had typed, it is workable enough.
printf "%s" "${COMP_LINE[@]}"
fi
fi
}
# Separate activeHelp lines from real completions.
# Fills the $activeHelp and $completions arrays.
__kubectl_extract_activeHelp() {
local activeHelpMarker="_activeHelp_ "
local endIndex=${#activeHelpMarker}
while IFS='' read -r comp; do
if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
comp=${comp:endIndex}
__kubectl_debug "ActiveHelp found: $comp"
if [[ -n $comp ]]; then
activeHelp+=("$comp")
fi
else
# Not an activeHelp line but a normal completion
completions+=("$comp")
fi
done <<<"${out}"
}
__kubectl_handle_completion_types() {
__kubectl_debug "__kubectl_handle_completion_types: COMP_TYPE is $COMP_TYPE"
case $COMP_TYPE in
37|42)
# Type: menu-complete/menu-complete-backward and insert-completions
# If the user requested inserting one completion at a time, or all
# completions at once on the command-line we must remove the descriptions.
# https://github.com/spf13/cobra/issues/1508
local tab=$'\t' comp
while IFS='' read -r comp; do
[[ -z $comp ]] && continue
# Strip any description
comp=${comp%%$tab*}
# Only consider the completions that match
if [[ $comp == "$cur"* ]]; then
COMPREPLY+=("$comp")
fi
done < <(printf "%s\n" "${completions[@]}")
;;
*)
# Type: complete (normal completion)
__kubectl_handle_standard_completion_case
;;
esac
}
__kubectl_handle_standard_completion_case() {
local tab=$'\t' comp
# Short circuit to optimize if we don't have descriptions
if [[ "${completions[*]}" != *$tab* ]]; then
IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
return 0
fi
local longest=0
local compline
# Look for the longest completion so that we can format things nicely
while IFS='' read -r compline; do
[[ -z $compline ]] && continue
# Strip any description before checking the length
comp=${compline%%$tab*}
# Only consider the completions that match
[[ $comp == "$cur"* ]] || continue
COMPREPLY+=("$compline")
if ((${#comp}>longest)); then
longest=${#comp}
fi
done < <(printf "%s\n" "${completions[@]}")
# If there is a single completion left, remove the description text
if ((${#COMPREPLY[*]} == 1)); then
__kubectl_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
comp="${COMPREPLY[0]%%$tab*}"
__kubectl_debug "Removed description from single completion, which is now: ${comp}"
COMPREPLY[0]=$comp
else # Format the descriptions
__kubectl_format_comp_descriptions $longest
fi
}
__kubectl_handle_special_char()
{
local comp="$1"
local char=$2
if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
local word=${comp%"${comp##*${char}}"}
local idx=${#COMPREPLY[*]}
while ((--idx >= 0)); do
COMPREPLY[idx]=${COMPREPLY[idx]#"$word"}
done
fi
}
__kubectl_format_comp_descriptions()
{
local tab=$'\t'
local comp desc maxdesclength
local longest=$1
local i ci
for ci in ${!COMPREPLY[*]}; do
comp=${COMPREPLY[ci]}
# Properly format the description string which follows a tab character if there is one
if [[ "$comp" == *$tab* ]]; then
__kubectl_debug "Original comp: $comp"
desc=${comp#*$tab}
comp=${comp%%$tab*}
# $COLUMNS stores the current shell width.
# Remove an extra 4 because we add 2 spaces and 2 parentheses.
maxdesclength=$(( COLUMNS - longest - 4 ))
# Make sure we can fit a description of at least 8 characters
# if we are to align the descriptions.
if ((maxdesclength > 8)); then
# Add the proper number of spaces to align the descriptions
for ((i = ${#comp} ; i < longest ; i++)); do
comp+=" "
done
else
# Don't pad the descriptions so we can fit more text after the completion
maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
fi
# If there is enough space for any description text,
# truncate the descriptions that are too long for the shell width
if ((maxdesclength > 0)); then
if ((${#desc} > maxdesclength)); then
desc=${desc:0:$(( maxdesclength - 1 ))}
desc+="…"
fi
comp+=" ($desc)"
fi
COMPREPLY[ci]=$comp
__kubectl_debug "Final comp: $comp"
fi
done
}
__start_kubectl()
{
local cur prev words cword split
COMPREPLY=()
# Call _init_completion from the bash-completion package
# to prepare the arguments properly
if declare -F _init_completion >/dev/null 2>&1; then
_init_completion -n =: || return
else
__kubectl_init_completion -n =: || return
fi
__kubectl_debug
__kubectl_debug "========= starting completion logic =========="
__kubectl_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"
# The user could have moved the cursor backwards on the command-line.
# We need to trigger completion from the $cword location, so we need
# to truncate the command-line ($words) up to the $cword location.
words=("${words[@]:0:$cword+1}")
__kubectl_debug "Truncated words[*]: ${words[*]},"
local out directive
__kubectl_get_completion_results
__kubectl_process_completion_results
}
if [[ $(type -t compopt) = "builtin" ]]; then
complete -o default -F __start_kubectl kubectl
else
complete -o default -o nospace -F __start_kubectl kubectl
fi
# ex: ts=4 sw=4 et filetype=sh
3. 加载补全脚本文件
source /etc/bash_completion.d/kubernetes.sh
1. 修改 ~/.zshrc 文件
echo '[[ $commands[kubectl] ]] && source <(kubectl completion zsh)' >> ~/.zshrc
2. 重载 ~/.zshrc 文件
source ~/.zshrc
kubectl [command] [TYPE] [NAME] [flags]
其中:
command
表示命令TYPE
表示资源类型NAME
表示资源名称flags
表示参数kubectl help
kubectl options
kubectl version [flags]
其中:
flags
表示参数,可选值如下:
--client
: 仅查看客户端版本
--short
: 仅输出版本号
--output
或 -o
: 以指定格式输出信息,可选 json
和 yaml
示例:
kubectl version
kubectl version --client
kubectl version --short
kubectl version --output json
kubectl version --output yaml
kubectl cluster-info
kubectl api-versions
kubectl api-resources
kubectl get nodes [NAME]
其中:
NAME
表示节点名称,可选,不输入时显示集群所有节点示例:
kubectl get nodes
node1
的节点kubectl get nodes node1
kubectl describe nodes [NAME]
其中:
NAME
表示节点名称,可选,不输入时显示集群所有节点的详细信息示例:
kubectl describe nodes
node1
的节点的详细信息kubectl describe nodes node1
kubectl top nodes [NAME] [flags]
其中:
NAME
表示节点名称flags
表示参数,可选值如下:
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点--sort-by
: 排序,可选 cpu
和 memory
示例:
kubectl top nodes
kubectl top nodes --sort-by memory
node1
的节点的CPU、内存占用kubectl top node node1
kubectl cordon [NAME] [flags]
其中:
NAME
表示节点名称flags
表示参数,可选值如下:
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点示例:
node2
节点标记为不可调度kubectl cordon node2
type
且值为 test
的节点标记为不可调度kubectl cordon --selector type=test
kubectl uncordon [NAME] [flags]
其中:
NAME
表示节点名称flags
表示参数,可选值如下:
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点示例:
node2
节点标记为可调度kubectl uncordon node2
type
且值为 test
的节点标记为可调度kubectl uncordon --selector type=test
kubectl drain [NAME] [flags]
其中:
NAME
表示节点名称flags
表示参数,部分可选值如下:
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点
--force
:强制清除节点上的所有 pods
--delete-local-data
:即使有使用emptyDir(在耗尽节点时将删除的本地数据)的pod也要继续。
--ignore-daemonsets
:忽略 DaemonSet 调度的 Pod
示例:
node2
节点上的资源(pods)kubectl drain node2
type
且值为 test
的节点上的资源(pods)kubectl drain --selector type=test
node2
节点上的所有资源(pods)kubectl drain node2 --force
kubectl get nodes [NAME] --show-labels
其中:
NAME
表示节点名称,可选,不输入时显示集群所有节点示例:
kubectl get nodes --show-labels
node1
节点的标签kubectl get nodes node1 --show-labels
kubectl label nodes [NAME] [flags] KEY_1=VAL_1 ... KEY_N=VAL_N
其中:
NAME
表示节点名称flags
表示参数,部分可选值如下:
--all
: 选择全部节点
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点
示例:
node2
节点添加标签,标签名为 type
、标签值为 demo
kubectl label nodes node2 type=demo
type
、标签值为 demo
kubectl label nodes --all type=demo
region
且值为 test
的节点添加新的标签,标签名为 type
、标签值为 demo
kubectl label nodes --selector region=test type=demo
kubectl label nodes [NAME] [flags] KEY_1- ... KEY_N-
其中:
NAME
表示节点名称flags
表示参数,部分可选值如下:
--all
: 选择全部节点
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点
示例:
node2
节点的 type
标签kubectl label nodes node2 type-
type
标签kubectl label nodes --all type-
region
且值为 test
的节点的 type
标签值kubectl label nodes --selector region=test type-
kubectl label nodes [NAME] [flags] KEY_1=VAL_1 ... KEY_N=VAL_N --overwrite
其中:
NAME
表示节点名称flags
表示参数,部分可选值如下:
--all
: 选择全部节点
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点
示例:
node2
节点的标签,标签名为 type
、标签值为 demo
kubectl label nodes node2 type=demo --overwrite
type
、标签值为 demo
kubectl label nodes --all type=demo --overwrite
region
且值为 test
的节点的标签,标签名为 type
、标签值为 demo
kubectl label nodes --selector region=test type=demo --overwrite
kubectl delete nodes [NAME] [flags]
其中:
NAME
表示节点名称flags
表示参数,部分可选值如下:
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的节点示例:
node2
节点kubectl delete nodes node2
type
且值为 demo
的节点kubectl delete nodes --selector type=demo
kubectl get namespaces
kubectl describe namespaces [NAME]
其中:
NAME
表示名称空间名称,不指定时返回全部名称空间详情示例:
default
名称空间详情kubectl describe namespaces default
kubectl create namespace [NAME]
其中:
NAME
表示名称空间名称示例:
demo
的名称空间kubectl create namespace demo
kubectl delete namespaces [NAME] [flags]
其中:
NAME
表示名称空间名称flags
表示参数,部分可选值如下:
--selector
或 -l
: 标签选择器,支持 =
、==
和 !=
,将选择满足全部条件的名称空间
--force
:强制删除
示例:
demo
的名称空间kubectl delete namespaces demo
kubectl run [NAME] --image=image [--env="key=value"] [--port=port] [--restart=Never|OnFailure|Always] [--stdin/-i] [--tty/-t] [--command] -- [COMMAND] [args...] [options]
其中:
NAME
表示应用名称--image
表示使用的镜像--env
表示容器内部的环境变量,可配置多个--port
表示映射的端口号--restart
表示容器重启策略--stdin
或 -i
表示保持容器的 stdin 为打开状态--tty
或 -t
表示为容器分配一个终端--command
表示容器启动后要执行命令,需执行的命令在 COMMAND
处指定,可指定多个示例:
kubectl run nginx --image=nginx:
kubectl run -i -t busybox --image=busybox --restart=Never
kubectl create -f 指定yaml文件
如需同时部署多个应用,可重复指定 -f 参数,如
kubectl create -f app1.yaml -f app2.yaml
示例:
kubectl create -f demo.yaml
kubectl apply -f 指定yaml文件
如需同时部署多个应用,可重复指定 -f 参数,如
kubectl apply -f app1.yaml -f app2.yaml
示例:
kubectl apply -f demo.yaml
kubectl delete -f 指定yaml文件
示例:
kubectl delete -f demo.yaml
kubectl get pods -A
kubectl get pods --namespace 名称空间
示例:
demo
名称空间的 Podkubectl get pods --namespace demo
kubectl describe pods --namespace 名称空间 Pod名称
示例:
demo
名称空间中名称为 nginx-deployment-64d6df956f-q8gft
Pod 的详细信息kubectl describe pods --namespace demo nginx-deployment-64d6df956f-q8gft
kubectl top pod --namespace 名称空间 Pod名称
示例:
demo
名称空间中名称为 nginx-deployment-64d6df956f-q8gft
Pod 的CPU、内存占用情况kubectl top pod --namespace demo nginx-deployment-64d6df956f-q8gft
kubectl logs -f --namespace Pod所属名称空间 Pod名称
其中:
-f
表示持续输出日志内容示例:
demo
名称空间中 nginx-deployment-64d6df956f-q8gft
的日志kubectl logs -f --namespace demo nginx-deployment-64d6df956f-q8gft
kubectl cp 本地文件 Pod名称:Pod内部文件 -n Pod所属名称空间
示例:
test.db
文件至名称为 db-mysql-statefulset-0
Pod 的 /tmp
目录,此 Pod 在 demo
名称空间kubectl cp ./test.db db-mysql-statefulset-0:/tmp -n demo
kubectl exec -i -t -n Pod所属名称空间 Pod名称 /bin/bash
示例:
db-mysql-statefulset-0
Pod 的内容,,此 Pod 在 demo
名称空间kubectl exec -i -t -n demo db-mysql-statefulset-0 /bin/bash