1857 字
9 分钟

Common Kubectl Commands

1. Kubectl Command Summary#

Basic Commands (Beginner)

CommandDescription
kubectl createCreate a resource object from a YAML/JSON file or from standard input. Supports many subcommands such as namespace, pod, deployment, service, etc.
kubectl exposeExpose the ports of a resource defined in a YAML/JSON file through a new Service resource object.
kubectl runCreate and run one or more container images.
kubectl setConfigure specific features on resource objects.

Basic Commands (Intermediate)

CommandDescription
kubectl explainShow detailed information about a resource object (commonly used as a hint when writing YAML. For example, kubectl explain deployment will show the fields you can write under deployment, their attributes, and can be used hierarchically).
kubectl getRetrieve information about one or more resource objects.
kubectl editEdit a resource object defined on the server using the default editor.
kubectl deleteDelete resources by YAML/JSON file, standard input, resource name, or label selector.

Deploy Commands

CommandDescription
kubectl rolloutManage the rollout of resources.
kubectl rollout-updatePerform a rolling update using an rc (replication controller).
kubectl scaleScale up or down deployments, replicasets, replication controllers, etc.
kubectl autoscaleAutomatically set the number of running Pods in Kubernetes (horizontal pod autoscaling).

Cluster Manager Commands

CommandDescription
kubectl cetificateModify Certificate resources.
kubectl cluster-infoDisplay cluster information.
kubectl topShow CPU, memory, and storage usage.
kubectl cordonMark a node as unschedulable.
kubectl uncordonMark a node as schedulable.
kubectl drainSafely evict all Pods from a node.
kubectl taintAdd taints to one or more nodes.

Troubleshooting and Debugging Commands

CommandDescription
kubectl describeDisplay detailed information about one or more resource objects.
kubectl logsPrint the logs of a single container in a Pod.
kubectl attachAttach to a running container.
kubectl execExecute a command in a specified container.
kubectl port-forwardForward a local port to a port on a Pod.
kubectl proxyForward a local port to the kube-apiserver.
kubectl cpCopy files between a Pod and the host.
kubectl authInspect authorization.

Advanced Commands

CommandDescription
kubectl diffCompare local YAML/JSON files against the configurations running in the kube-apiserver and show differences.
kubectl applyConfigure or create resources from YAML/JSON files or standard input.
kubectl patchModify resource fields using a patch (patch-style update).
kubectl replaceReplace a resource object by providing a YAML/JSON file or from standard input.
kubectl waitWait for conditions on one or more resources to be met.
kubectl convertConvert YAML/JSON files to different resource versions.
kubectl kustomizeCustomize Kubernetes configurations.

Settings Commands

CommandDescription
kubectl labelAdd, update, or remove labels on resources.
kubectl annotateUpdate annotations on one or more resource objects.
kubectl completionShell command auto-completion.

Other Commands

CommandDescription
kubectl configManage kubeconfig configuration files.
kubectl pluginRun kubectl CLI plugins.
kubectl versionShow client and server version information.
kubectl api-versionsList the API groups and versions supported by the current Kubernetes cluster, in the form /.
kubectl api-resourcesList the resource types supported by the current Kubernetes cluster.
kubectl optionsShow the list of supported global command-line options.

2. Common RESOURCE_NAME Values#

NameAbbreviation
all
certificatesigningrequests(abbr csr)
clusterrolebindings
clusterrol
componentstatuses(abbr cs)
configmaps(abbr cm)
controllerrevisions
cronjobs
customresourcedefinition(abbr crd)
daemonsets(abbr ds)
deployments(abbr deploy)
endpoints(abbr ep)
events(abbr ev)
horizontalpodautoscalers(abbr hpa)
ingresses(abbr ing)
jobs
limitranges(abbr limits)
namespaces(abbr ns)
networkpolicies(abbr netpol)
nodes(abbr no)
persistentvolumeclaims(abbr pvc)
persistentvolumes(abbr pv)
poddisruptionbudgets(abbr pdb)
podpreset
pods(abbr po)
podsecuritypolicies(abbr psp)
podtemplates
replicasets(abbr rs)
replicationcontrollers(abbr rc)
resourcequotas(abbr quota)
rolebindings
roles
secrets
serviceaccounts(abbr sa)
services(abbr svc)
statefulsets(abbr sts)
storageclasses(abbr sc)

3. Detailed Explanation of Important kubectl Commands#

kubectl create#

Create a cluster resource object from a configuration file or from stdin. Supports JSON and YAML files.

Syntax:

Terminal window
kubectl create -f FILENAME

Examples:

Terminal window
# Create a Pod from pod.yml
kubectl create -f ./pod.yml
# Create a Pod from YAML via stdin
cat pod.yml | kubectl create -f -
# Grant the cluster-admin role to gitlab-runner in the namespace
kubectl create rolebinding deploy-runner --clusterrole=cluster-admin --serviceaccount=deploy:default --namespace=hsh-pre-service

kubectl expose#

Expose a resource as a new Kubernetes Service. Specify a deployment, service, replica set, replication controller, or pod, and use that resource’s selector as the selector of the new Service on the specified port. Deployment or replica set can only be exposed as a new Service when their selector can be converted into a selector supported by Service, i.e., when the selector only contains matchLabels.

Syntax:

Terminal window
kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]

Examples:

Terminal window
# Create a Service for nginx rc and forward Service port 80 to container port 8000
kubectl expose rc nginx --port=80 --target-port=8000
# Create a Service for the rc identified by type and name in "nginx-controller.yml",
# forwarding Service port 80 to container port 8000
kubectl expose -f nginx-controller.yml --port=80 --target-port=8000

kubectl get#

Retrieve information about one or more resource objects.

Syntax:

Terminal window
kubectl get RESOURCE_NAME

Examples:

Terminal window
# View master status
kubectl get componentstatuses
# List all namespaces
kubectl get namespaces
# List all Pods
kubectl get pods
# Show more information about Pods (e.g., Pod IP and Node)
kubectl get pods -o wide
# List the rc named web
kubectl get replicationcontroller web
# Get information about Pod web-pod-13cd8 and output it in JSON format
kubectl get -o json pod web-pod-13cd8
# Find Pods defined in pod.yaml and output them in JSON format
kubectl get -f pod.yaml -o json
# Get the status of a Pod
kubectl get -o template pod/kube-dns-795f5f6f9c-ldxxs --template {{.status.phase}}
# List all rc and services
kubectl get rc,services
# Get all rc, svc, and Pod resources that match the criteria
kubectl get rc/web service/frontend pods/web-pod-13cd8
# Get all resources
kubectl get all

kubectl edit#

Edit a resource defined on the server using the default editor. Any resource retrievable via the command line can be edited using edit. The edit command opens the editor defined by the KUBE_EDITOR, GIT_EDITOR, or EDITOR environment variables. You can edit multiple resources at once, but changes are submitted in a single operation. Besides command arguments, edit also accepts filenames. YAML is the default output format; use -o json to edit in JSON.

Syntax:

Terminal window
kubectl edit (RESOURCE/NAME | -f FILENAME)

Examples:

Terminal window
# Edit the Service named "docker-registry"
kubectl edit svc/docker-registry
# Use an alternative editor
KUBE_EDITOR="nano" kubectl edit svc/docker-registry
# Edit deployment "mydeployment" in YAML format and save the changed config into annotations
kubectl edit deployment/mydeployment -o yaml --save-config

kubectl delete#

Delete resources by configuration file, stdin, resource names, or label selectors. Supports JSON and YAML files. You can only specify one type of parameter at a time: filenames, resource names, or label selectors.

Note: delete does not check resource versions. If an update occurs while a delete is in progress, that update will be deleted along with the resource.

Syntax:

Terminal window
kubectl delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])

Examples:

Terminal window
# Delete the Pod specified by type and name in pod.yml
kubectl delete -f ./pod.yml
# Delete the Pod specified by type and name in the YAML from stdin
cat pod.json | kubectl delete -f -
# Delete Pods and Services named "foo" and "bar"
kubectl delete pod,service foo bar
# Delete Pods and Services whose label name=myLabel
kubectl delete pods,services -l name=myLabel
# Force delete Pods on a dead node
kubectl delete pod foo --grace-period=0 --force
# Delete all Pods
kubectl delete pods --all

kubectl rollout#

Manage the rollout of resources. Supported resources: deployments, daemonsets.

Subcommands:

  • history (show rollout history)
  • pause (pause a resource)
  • resume (resume a paused resource)
  • status (show rollout status)
  • undo (roll back to a previous revision)

Syntax:

Terminal window
kubectl rollout SUBCOMMAND

Examples:

Terminal window
# Show the rollout history of a deployment
kubectl rollout history deployment/abc
# Show details of daemonset revision=3
kubectl rollout history daemonset/abc --revision=3
# Mark a deployment as paused. While paused, updates to the deployment have no effect.
kubectl rollout pause deployment/nginx
# Resume a paused deployment
kubectl rollout resume deployment/nginx
# Show the rollout status of a deployment
kubectl rollout status deployment/nginx
# Roll back a deployment to the previous revision
kubectl rollout undo deployment/abc
kubectl rollout undo --dry-run=true deployment/abc
# Roll back a daemonset to revision 3
kubectl rollout undo daemonset/abc --to-revision=3
# Set the number of replicas in the ReplicaSet named foo to 3
kubectl scale --replicas=3 rs/foo
# Set the number of Pod replicas defined in foo.yaml to 3
kubectl scale --replicas=3 -f foo.yaml
# If mysql currently has 2 replicas, scale it to 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
# Set the number of Pod replicas in multiple RCs
kubectl scale --replicas=5 rc/foo rc/bar

kubectl describe#

Print detailed information about one or more specified resources. This command combines multiple API calls and outputs a detailed description of the specified resource(s).

Syntax:

Terminal window
kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)

Examples:

Terminal window
# Describe a node
kubectl describe nodes kubernetes-minion-emt8.c.myproject.internal
# Describe a Pod
kubectl describe pods/nginx
# Describe the Pod specified by type and name in pod.yml
kubectl describe -f pod.yml
# Describe all Pods
kubectl describe pods
# Describe all Pods with label name=myLabel
kubectl describe po -l name=myLabel
# Describe all Pods managed by the replication controller "frontend"
# (Pods created by an rc use the rc name as prefix)
kubectl describe pods frontend

kubectl logs#

Print the logs of a container in a Pod. If the Pod has only one container, the container name can be omitted.

Syntax:

Terminal window
kubectl logs [-f] [-p] POD [-c CONTAINER]

Examples:

Terminal window
# Return a snapshot of logs from Pod nginx (with a single container)
kubectl logs nginx
# Return a snapshot of logs from the previously terminated container web-1 in Pod ruby
kubectl logs -p -c ruby web-1
# Stream logs from container web-1 in Pod ruby
kubectl logs -f -c ruby web-1
# Show only the last 20 log lines from Pod nginx
kubectl logs --tail=20 nginx
# Show all logs generated in the last hour from Pod nginx
kubectl logs --since=1h nginx

kubectl exec#

Execute a command inside a container.

Syntax:

Terminal window
kubectl exec POD [-c CONTAINER] -- COMMAND [args...]

Examples:

Terminal window
# Run "date" in the first container of Pod 123456-abcd and print the output
kubectl exec 123456-abcd date
# Run "date" in container ruby-container of Pod 123456-abcd and print the output
kubectl exec 123456-abcd -c ruby-container date
# Start an interactive shell by sending console input to the "bash" command
# in ruby-container of Pod 123456-abcd and forwarding stdout/stderr back
kubectl exec 123456-abcd -c ruby-container -i -t -- bash -il

kubectl apply#

Create or update a cluster resource object from a configuration file or stdin. Supports JSON and YAML files.

Syntax:

Terminal window
kubectl apply -f FILENAME

Examples:

Terminal window
# Create a Pod from pod.yml
kubectl apply -f ./pod.yml
# Create a Pod from YAML via stdin
cat pod.yml | kubectl apply -f -

Differences between creating resources with kubectl create and kubectl apply:

kubectl applykubectl create
Directly updates existing resources in the cluster based on the fields present in the YAML file (the YAML can contain only the fields you want to change).First deletes all existing resources in the cluster, then recreates new resources from the YAML file (which must contain the full configuration).
The YAML can be partial and only contain required fields.The YAML must contain a complete set of configuration fields.
kubectl apply only operates on the fields that have changed in the YAML file.kubectl create operates on all fields in the YAML file.
When only some declarations in the YAML file are changed instead of all of them, you can use kubectl apply.If there are no changes in the YAML file, running kubectl replace with the same YAML will fail because there is no change information.

kubectl label#

Update (add, modify, or remove) labels on resources. Labels must start with a letter or number, can contain letters, numbers, dashes, dots, and underscores, and must be no longer than 63 characters. If --overwrite is true, existing labels can be overwritten; otherwise, attempts to overwrite labels will fail. If --resource-version is specified, the update will use that resource version; otherwise, the existing resource version is used.

Syntax:

Terminal window
kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]

Examples:

Terminal window
# Add label unhealthy=true to Pod foo
kubectl label pods foo unhealthy=true
# Overwrite label 'status' on Pod foo with value 'unhealthy'
kubectl label --overwrite pods foo status=unhealthy
# Add a label to all Pods in the namespace
kubectl label pods --all status=unhealthy
# Update the label on Pod foo only if resource-version=1
kubectl label pods foo status=unhealthy --resource-version=1
# Delete label "bar" from Pod foo (use a trailing minus sign)
kubectl label pods foo bar-
Common Kubectl Commands
https://catcat.blog/en/kubectl-command.html
作者
猫猫博客
发布于
2023-10-07
许可协议
CC BY-NC-SA 4.0