abstract
This paper introduces k8s cluster management command Kubectl classification and command details.
content
1. kubectl command list classification
(1) Basic Commands(Beginner)
kubectl create adopt yaml/json File or standard input to create a resource object, which supports many subcommands, such as namespace pod deployment service etc. kubectl expose take json/yaml The port of the resource object defined in the file is exposed to the new service Resource object kubectl run Create and run one or more container images kubectl set Configure resource objects and set specific functions
(2) Basic Commands (Intermediate)
kubectl explain View details of resource objects(It is usually written in one yaml Give a hint when you're ready kubectl explain deployment Will appear deployment The following fields and field attributes can be written and used level by level) kubectl get Gets information about one or more resource objects kubectl edit Use the default editor to edit resource objects defined on the server kubectl delete adopt json/yaml File, standard name, resource name, or label selector to delete a resource
(3) DeployCommands deployment commands
kubectl rollout Deployment of resource management objects kubectl rollout-update use rc(replication controller)To be a rolling star kubectl scale Expansion or contraction deployment replicaset replication contrller etc. kubectl autoscale Automatically set in k8s Running in the system pod Quantity (horizontal automatic expansion)
(4) Cluster Manager Commands
kubectl cetificate Modify certificate resource object kubectl cluster-info View cluster information kubectl top Show resources cpu Memory storage usage kubectl cordon Mark node as non schedulable kubectl uncordon Specifies that the node is schedulable kubectl drain Secure eviction of all nodes pod kubectl taint Set one or more nodes as stains
(5) Troubleshooting adn Debugging Commands
kubectl describe Displays the details of one or more resource objects kubectl logs output pod Log of a container in the resource object kubectl attach Connect to a running container kubectl exec Executes the command within the specified container kubectl port-forward Map the native specified port to pod Port of the resource object kubectl proxy Map the native specified port to kube-apiserver kubectl cp be used for pod Exchange files with host kubectl auth Check and verify
(6) Advanced Commands advanced commands
kubectl diff Compare local json/yaml Documents and kube-apiserver Are there any differences in the configuration files running in kubectl apply adopt json/yaml File standard input to update or create the configuration of resources kubectl patch adopt patch Modify the resource object field by (patch type) kubectl replace adopt json/yaml File or standard input to replace the resource object kubectl wait Wait for conditions to be met on one or more resources kubectl convert transformation json/yaml The file is a different resource version kubectl kustomize customized kubernetes to configure
(7) Settings Commands
kubectl label Add, delete or modify the label of the resource kubectl annotate Update comments for one or more resource objects( annotaion)information kubectl completion Command auto completion
(8) Other Commands
kubectl config Administration kubeconfig configuration file kubectl plugin Run the command line plug-in function kubectl version View the system version information of the client and server kubectl api-versions List current kubernetes The system supports resource groups and resource versions in the following forms:/ kubectl api-resources List current kubernetes System supported resource resource list kubectl options View a list of supported parameters
2. Basic Commands(Beginner)
(1)kubectl create
Create a cluster resource object by configuration file name or stdin. Support JSON and YAML format files.
grammar
$ create -f FILENAME
Example Create a pod through the pod.json file.
kubectl create -f ./pod.json
Create a pod through stdin's JSON.
cat pod.json | kubectl create -f -
Create resources in the docker-registry.yaml file in JSON format with API version v1.
kubectl create -f docker-registry.yaml --edit --output-version=v1 -o json
(2)kubectl expose
Expose the resource as a new Kubernetes Service. appoint deployment,service,replica set,replication controller or pod , and use the selector of this resource as the selector of the new service on the specified port. deployment or replica set will expose the new service only when its selector can be converted to the selector supported by the service, that is, when the selector only contains matchLabels components. Resources include (case insensitive): pod(po),service(svc),replication controller(rc),deployment(deploy),replica set(rs).
grammar
$ 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]
Example
Create a service for nginx of RC and forward it to port 8000 of the container through port 80 of the service.
kubectl expose rc nginx --port=80 --target-port=8000
The RC identified by the type and name specified in "nginx controller. Yaml" creates a Service and forwards it to port 8000 of the container through port 80 of the Service.
kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000
Other details
Name | Shorthand | Default | Usage |
---|---|---|---|
allow-missing-template-keys | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. | |
cluster-ip | ClusterIP to be assigned to the service. Leave empty to auto-allocate, or set to 'None' to create a headless service. | ||
container-port | Synonym for --target-port | ||
dry-run | false | If true, only print the object that would be sent, without sending it. | |
external-ip | Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP is routed to a node, the service can be accessed by this IP in addition to its generated service IP . if this IP is routed to a node, the service can be accessed by this IP in addition to the service IP generated by it. | ||
filename | f | [] | Filename, directory, or URL to files identifying the resource to expose a service |
generator | service/v2 | The name of the API generator to use. There are 2 generators: 'service/v1' and 'service/v2'. The only difference between them is that service port in v1 is named 'default', while it is left unnamed in v2. Default is 'service/v2'. | |
labels | l | Labels to apply to the service created by this call. | |
load-balancer-ip | IP to assign to the Load Balancer. If empty, an ephemeral IP will be created and used (cloud-provider specific). | ||
name | The name for the newly created object. | ||
no-headers | false | When using the default or custom-column output format, don't print headers (default print headers). | |
output | o | Output format. One of: json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://kubernetes.io/docs/user-guide/jsonpath]. | |
output-version | DEPRECATED: To use a specific API version, fully-qualify the resource, version, and group (for example: 'jobs.v1.batch/myjob'). | ||
overrides | An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. | ||
port | The port that the service should serve on. Copied from the resource being exposed, if unspecified | ||
protocol | The network protocol for the service to be created. Default is 'TCP'. | ||
record | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. | |
recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
save-config | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. | |
selector | A label selector to use for this service. Only equality-based selector requirements are supported. If empty (the default) infer the selector from the replication controller or replica set.) | ||
session-affinity | If non-empty, set the session affinity for the service to this; legal values: 'None', 'ClientIP' | ||
show-all | a | false | When printing, show all resources (default hide terminated pods.) |
show-labels | false | When printing, show all labels as the last column (default hide labels column) | |
sort-by | If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression must be an integer or a string. | ||
target-port | Name or number for the port on the container that the service should direct traffic to. Optional. | ||
template | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. | ||
type | Type for this service: ClusterIP, NodePort, or LoadBalancer. Default is 'ClusterIP'. |
(3)kubectl run
(4) kubectl set configure resource object to set specific functions
Configure application resources. Using these commands can help you change some information about existing application resources.
grammar
$ set SUBCOMMAND
Subcommand image resources selector subject
3. Basic Commands (Intermediate)
(1)kubectl explain
(2)kubectl get
grammar
kubectl get resource_name
Common resource_name
all certificatesigningrequests (abbreviation csr) clusterrolebindings clusterrol componentstatuses (abbreviation cs) configmaps (abbreviation cm) controllerrevisions cronjobs customresourcedefinition (abbreviation crd) daemonsets (abbreviation ds) deployments (abbreviation deploy) endpoints (abbreviation ep) events (abbreviation ev) horizontalpodautoscalers (abbreviation hpa) ingresses (abbreviation ing) jobs limitranges (abbreviation limits) namespaces (abbreviation ns) networkpolicies (abbreviation netpol) nodes (abbreviation no) persistentvolumeclaims (abbreviation pvc) persistentvolumes (abbreviation pv) poddisruptionbudgets (abbreviation pdb) podpreset pods (abbreviation po) podsecuritypolicies (abbreviation psp) podtemplates replicasets (abbreviation rs) replicationcontrollers (abbreviation rc) resourcequotas (abbreviation quota) rolebindings roles secrets serviceaccounts (abbreviation sa) services (abbreviation svc) statefulsets (abbreviation sts) storageclasses (abbreviation sc)
Other optional parameters View in different formats:
-o wide/yaml/json
Look at the pods of the specified label. The operators' = ',' = = ', and'! = 'are supported
-l key=value
give an example
# View Master status kubectl get componentstatuses # View all namespaces kubectl get namespaces # List all pods kubectl get pods # Display more pods list information (such as the ip address and node of the pod) kubectl get pods -o wide # List rc named web kubectl get replicationcontroller web # Get the information of the pod named web-pod-13je7 and output it in json format kubectl get -o json pod web-pod-13je7 # Find the pod according to the pod file and output it in json format kubectl get -f pod.yaml -o json # Gets the status of the pod container kubectl get -o template pod/kube-dns-795f5f6f9c-ldxxs --template {{.status.phase}} # Get all rc and service s at the same time kubectl get rc,services # Obtain all RC, SVC and pod that meet the conditions kubectl get rc/web service/frontend pods/web-pod-13je7 # Get all resource s kubectl get all
(3)kubectl edit
Use the default editor to edit the resources defined on the server. Any resource obtained by using the command line tool can be edited by using the edit command. The edit command will open the EDITOR defined by KUBE_EDITOR, GIT_EDITOR or EDITOR environment variable. Multiple resources can be edited at the same time, but the edited resources will only be submitted at one time. In addition to the command parameters, edit also accepts the form of file name. The default output format of the file is YAML. To edit in JSON format, specify the "- o json" option. If an error occurs when updating resources, a temporary file will be created on the disk to record. The most common error when updating resources is that several users use the editor to change the resources on the server at the same time. In this case, you need to apply your changes to the latest version of resources or update the saved temporary copy.
grammar
$ edit (RESOURCE/NAME | -f FILENAME)
Example Edit the service named 'docker registry':
kubectl edit svc/docker-registry
Use alternate editor
KUBE_EDITOR="nano" kubectl edit svc/docker-registry
Edit the service named "myjob" and output the V1 API version in JSON format
kubectl edit job.v1.batch/myjob -o json
Output and edit the deployment "mydeployment" in YAML format, and save the modified configuration in the annotation:
kubectl edit deployment/mydeployment -o yaml --save-config
(4)kubectl delete
Delete a resource by configuring a file name, stdin, resource name, or label selector. Supports JSON and YAML format files. You can specify only one type of parameter: file name, resource name, or label selector.
Some resources, such as pod, support graceful deletion. Because these resources are generally entities in the cluster, the deletion cannot take effect immediately. These resources define a period (grace period) by default before forced termination, but you can use -- grace period flag to override the value, or set the period to 1 through pass --now. If the Node hosting the Pod has stopped or cannot connect to the API Server, it takes longer to delete the Pod by using the delete command. To forcibly delete resources, specify - force flag and set the period (grace period) to 0. If the forced deletion of pods is performed, the scheduler will place the new pods on the nodes before the nodes release the pods, and the previous pods will be evicted immediately.
Note: the resource version will not be checked when the delete command is executed. If someone performs an update operation during the delete operation, the update operation will be deleted together with the resource.
grammar
$ delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])
Example Delete the pod using the resource type and name specified in pod.json.
kubectl delete -f ./pod.json
Delete the pod according to the type and name specified by the JSON passed in stdin.
cat pod.json | kubectl delete -f -
Delete the Pod and Service named "baz" and "foo".
kubectl delete pod,service baz foo
Delete the pod and Service with Label name = myLabel.
kubectl delete pods,services -l name=myLabel
Force deletion of pod on dead node
kubectl delete pod foo --grace-period=0 --force
Delete all pod s
kubectl delete pods --all
Flags
Name | Shorthand | Default | Usage |
---|---|---|---|
all | false | select all resources in the namespace of the specified resource types. | |
cascade | true | If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true. | |
filename | f | [] | Filename, directory, or URL to files containing the resource to delete. |
force | false | Immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. | |
grace-period | -1 | Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. | |
ignore-not-found | false | Treat "resource not found" as a successful delete. Defaults to "true" when --all is specified. | |
include-extended-apis | true | If true, include definitions of new APIs via calls to the API server. [default true] | |
now | false | If true, resources are signaled for immediate shutdown (same as --grace-period=1). | |
output | o | Output mode. Use "-o name" for shorter output (resource/name). | |
recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
selector | l | Selector (label query) to filter on. | |
timeout | 0s | The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object |
4. Deploy commands
(1)kubectl rollout
Manage resources. Available resources include: deployments daemonsets
Subcommand
- history (view historical version)
- pause (pause resources)
- resume (resume pause resource)
- status (view resource status)
- undo (rollback version)
grammar
$ rollout SUBCOMMAND
Example Rollback to previous deployment
kubectl rollout undo deployment/abc
View the status of the daemon
kubectl rollout status daemonset/foo
[1] kubectl rollout history
View previous releases (historical versions).
grammar
$ history (TYPE NAME | TYPE/NAME) [flags]
Example View the history of deployment
kubectl rollout history deployment/abc
View details of daemon revision 3
kubectl rollout history daemonset/abc --revision=3
[2] kubectl rollout pause
Mark the provided resources as suspended. The resources suspended by the pause command will not be coordinated by the controller. You can use the "kubectl rollout resume" command to resume the suspended resources. Currently only supported resources: deployments.
grammar
$ pause RESOURCE
Example Mark deployment as paused Updates using deployment will not take effect as long as deployment is suspended.
kubectl rollout pause deployment/nginx
[3] kubectl rollout resume
Resume paused resources
cover pause command Paused resources will not be coordinated by the controller. Resources can be recovered through resume. Currently only recovery is supported deployment resources.
grammar
$ resume RESOURCE
Example Resume suspended deployment
kubectl rollout resume deployment/nginx
[4] kubectl rollout status
View the status of the resource.
Use -- watch = false to view the current status. If you need to view the status of a specific revision, use -- revision = N to specify.
grammar
$ status (TYPE NAME | TYPE/NAME) [flags]
Example View the status of deployment
kubectl rollout status deployment/nginx
[5] kubectl rollout undo
Rollback to previous version.
grammar
$ undo (TYPE NAME | TYPE/NAME) [flags]
Example Rollback to previous deployment version
kubectl rollout undo deployment/abc kubectl rollout undo --dry-run=true deployment/abc
Rollback to daemon revision 3
kubectl rollout undo daemonset/abc --to-revision=3
(2)kubectl rollout-update
(3)kubectl scale
Expand or shrink the number of pods in a Deployment, ReplicaSet, Replication Controller, or Job. scale can also specify multiple preconditions, such as the current number of replicas or -- resource version. Before setting the scaling ratio, the system will verify whether the preconditions are valid.
grammar
scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)
Example Set the number of pod copies named foo to 3.
kubectl scale --replicas=3 rs/foo
Set the Pod resource copy identified by the resource object and name specified in the "foo.yaml" configuration file to 3.
kubectl scale --replicas=3 -f foo.yaml
If the current number of replicas is 2, expand it to 3.
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
Set the number of Pod copies in multiple RC.
kubectl scale --replicas=5 rc/foo rc/bar rc/baz
option
Name | Shorthand | Default | Usage |
---|---|---|---|
current-replicas | -1 | Precondition for current size. Requires that the current size of the resource match this value in order to scale. | |
filename | f | [] | Filename, directory, or URL to files identifying the resource to set a new size |
include-extended-apis | true | If true, include definitions of new APIs via calls to the API server. [default true] | |
output | o | Output mode. Use "-o name" for shorter output (resource/name). | |
record | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. | |
recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
replicas | -1 | The new desired number of replicas. Required. | |
resource-version | Precondition for resource version. Requires that the current resource version match this value in order to scale. | ||
timeout | 0s | The length of time to wait before giving up on a scale operation, zero means don't wait. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h). |
(4)kubectl autoscale
5. Cluster Manager Commands
(1)kubectl cetificate
Modify certificate resource object
(2)kubectl cluster-info
View cluster information
(3)kubectl top
Displays resource cpu memory storage usage
(4)kubectl cordon
Mark node as non schedulable
(5)kubectl uncordon
Specifies that the node is schedulable
(6)kubectl drain
Secure eviction of all nodes pod
(7) kubectl taint (stain and tolerance)
Taint and tolerance can act on nodes and pods. Their purpose is to optimize the scheduling of pods between clusters, which is similar to node affinity, but in the opposite way. Nodes and pods with taint are mutually exclusive, while nodes and pods with node affinity are attracted. In addition, you can set a label for the node node and schedule the pod to the node with matching labels by setting a nodeSelector for the pod.
taint and tolerance cooperate with each other to avoid pod being allocated to inappropriate nodes. One or more taints can be applied to each node, which means that pods that cannot tolerate these taints will not be accepted by the node. If tolerance is applied to pods, it means that these pods can (but are not required to) be scheduled to nodes with corresponding taints.
The following examples are setting taint for node and tolerance for pod.
Set taint for node
kubectl taint nodes node1 key1=value1:NoSchedule kubectl taint nodes node1 key1=value1:NoExecute kubectl taint nodes node1 key2=value2:NoSchedule
Delete taint above:
kubectl taint nodes node1 key1:NoSchedule- kubectl taint nodes node1 key1:NoExecute- kubectl taint nodes node1 key2:NoSchedule-
To view taint on node1:
kubectl describe nodes node1
Set tolerance for pod As long as you set the descriptions field in the spec of the pod, you can have multiple key s, as shown below:
tolerations: - key: "key1" operator: "Equal" value: "value1" effect: "NoSchedule" - key: "key1" operator: "Equal" value: "value1" effect: "NoExecute" - key: "node.alpha.kubernetes.io/unreachable" operator: "Exists" effect: "NoExecute" tolerationSeconds: 6000
The value of value can be NoSchedule, PreferNoSchedule, or NoExecute. Tolerance seconds is the time when the pod can continue to run on the node when it needs to be evicted.
For detailed usage, please refer to Official documents.
6. Troubleshooting adn Debugging Commands
(1)kubectl describe
Outputs the details of the specified one or more resources.
This command calls multiple API s in combination and outputs a detailed description of a specified resource or group of resources.
$ kubectl describe TYPE NAME_PREFIX
First check whether there is an exact match between TYPE and name_ If there is no prefix resource, all names will be output with name_ Resource details starting with prefix.
The supported resources include but are not limited to (unlimited case): pods (po), services (svc), replicationcontrollers (rc), nodes (no), events (ev), componentstatuses (cs), limitranges (limits), persistentvolumes (pv), persistentvolumeclaims (pvc), resourcequotes (quota), and secrets.
grammar
kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)
Example #Describe a node
$ kubectl describe nodes kubernetes-minion-emt8.c.myproject.internal
#Describe a pod
$ kubectl describe pods/nginx
#Describes the pod specified by the resource type and name in pod.json
$ kubectl describe -f pod.json
#Describe all pod s
$ kubectl describe pods
#Describe all pod s containing label name=myLabel
$ kubectl describe po -l name=myLabel
#Describe all pods managed by the replication controller "frontend" (the pods created by rc are prefixed with the name of rc)
$ kubectl describe pods frontend
option -f. -- filename = []: used to specify the file name, directory name or URL of the resource to be described. -l. -- selector = "": Label used to filter resources.
Options inherited from parent command
--alsologtostderr[=false]: Output the log to the standard error console and file at the same time. --api-version="": Used interactively with the server API edition. --certificate-authority="": Used for authentication and authorization.cert File path. --client-certificate="": TLS The path of the client certificate used. --client-key="": TLS The client key path used. --cluster="": Specify the used kubeconfig The cluster name in the configuration file. --context="": Specify the used kubeconfig The environment name in the configuration file. --insecure-skip-tls-verify[=false]: If yes true,The validity of the server credentials will not be checked, which will cause your HTTPS Links become unsafe. --kubeconfig="": The configuration file path used by the command line request. --log-backtrace-at=:0: When the log length exceeds the defined number of rows, the stack information is ignored. --log-dir="": If it is not empty, write the log file to this directory. --log-flush-frequency=5s: The maximum time interval to refresh the log. --logtostderr[=true]: Output logs to the standard error console, not to files. --match-server-version[=false]: The server and client versions are required to match. --namespace="": If it is not empty, this command will be used namespace. --password="": API Server Password used for simple authentication. -s, --server="": Kubernetes API Server Address and port number of the. --stderrthreshold=2: Logs above this level will be output to the error console. --token="": Certified to API Server Token used. --user="": Specify the used kubeconfig User name in the configuration file. --username="": API Server The user name used for simple authentication. --v=0: Specifies the level of the output log. --vmodule=: Specify the module to output the log in the following format: pattern=N,Use commas to separate.
(2)kubectl logs
Output the log of a container in pod. If the pod contains only one container, you can omit the container name.
Syntax format
kubectl logs [-f] [-p] POD [-c CONTAINER]
option
-c, --container="": Container name. -f, --follow[=false]: Specifies whether to continuously output logs. --interactive[=true]: If yes true,Prompt the user for input when required. Default to true. --limit-bytes=0: The maximum number of bytes of the output log. The default is unlimited. -p, --previous[=false]: If yes true,output pod Logs of containers that have been run in but are currently terminated. --since=0: Returns only the relative time range, such as 5 s,2m Or 3 h,Log within. All logs are returned by default. Can only be used at the same time since and since-time One of them. --since-time="": Returns only the specified time( RFC3339 Format). All logs are returned by default. Can only be used at the same time since and since-time One of them. --tail=-1: The latest number of log entries to display. Default to-1,Show all logs. --timestamps[=false]: Include a timestamp in the log.
Example
# Returns a log snapshot of pod nginx that contains only one container $ kubectl logs nginx # Returns the log snapshot of the stopped container web-1 in pod ruby $ kubectl logs -p -c ruby web-1 # Continuously output the log of web-1 container in pod ruby $ kubectl logs -f -c ruby web-1 # Only the last 20 logs in pod nginx are output $ kubectl logs --tail=20 nginx # Output all logs generated in the last hour in pod nginx $ kubectl logs --since=1h nginx
(3)kubectl attach
(4)kubectl exec
Execute commands inside the container.
Syntax format
kubectl exec POD [-c CONTAINER] -- COMMAND [args...]
option
-c, --container="": Container name. If not specified, use pod A container in. -p, --pod="": Pod Name. -i, --stdin[=false]: Send console input to the container. -t, --tty[=false]: Use the standard input console as the console input for the container.
give an example
# By default, run "date" in the first container of pod 123456-7890 and get the output $ kubectl exec 123456-7890 date # Run "date" in Ruby container of pod 123456-7890 and get the output $ kubectl exec 123456-7890 -c ruby-container date # Switch to the terminal mode, send the console input to the "bash" command of the ruby container of pod 123456-7890, and output it to the console/ # Error console information is sent back to the client. $ kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il
(5)kubectl port-forward
(6)kubectl proxy
(7)kubectl cp
(7)kubectl auth
7. Advanced Commands
(1)kubectl diff
(2)kubectl apply
Syntax:
kubectl apply -f FILENAME
option
-f, --filename=[]: The file name, directory name, or directory name that contains the configuration information URL. -o, --output="": Output format, using“-o name"To output short format (resource type)/Resource name). --schema-cache-dir="/tmp/kubectl.schema": If it is not empty, the API schema The cache is the specified file, which is cached to by default“/tmp/kubectl.schema". --validate[=true]: If yes true,Use before sending to the server schema To validate the input.
Options inherited from parent command
--alsologtostderr[=false]: Output the log to the standard error console and file at the same time. --api-version="": Used interactively with the server API edition. --certificate-authority="": Used for authentication and authorization.cert File path. --client-certificate="": TLS The path of the client certificate used. --client-key="": TLS The client key path used. --cluster="": Specify the used kubeconfig The cluster name in the configuration file. --context="": Specify the used kubeconfig The environment name in the configuration file. --insecure-skip-tls-verify[=false]: If yes true,The validity of the server credentials will not be checked, which will cause your HTTPS Links become unsafe. --kubeconfig="": The configuration file path used by the command line request. --log-backtrace-at=:0: When the log length exceeds the defined number of rows, the stack information is ignored. --log-dir="": If it is not empty, write the log file to this directory. --log-flush-frequency=5s: The maximum time interval to refresh the log. --logtostderr[=true]: Output logs to the standard error console, not to files. --match-server-version[=false]: The server and client versions are required to match. --namespace="": If it is not empty, this command will be used namespace. --password="": API Server Password used for simple authentication. -s, --server="": Kubernetes API Server Address and port number of the. --stderrthreshold=2: Logs above this level will be output to the error console. --token="": Certified to API Server Token used. --user="": Specify the used kubeconfig User name in the configuration file. --username="": API Server The user name used for simple authentication. --v=0: Specifies the level of the output log. --vmodule=: Specify the module to output the log in the following format: pattern=N,Use commas to separate.
The difference between creating resource objects using kubectl create and kubectl apply
Serial number | kubectl apply | kubectl create |
---|---|---|
1 | According to the fields contained in the yaml file (the yaml file can only write the fields that need to be changed), directly upgrade the existing resource objects in the cluster | First, delete all existing resources in the cluster, and then re generate new resource objects according to the yaml file (which must be complete configuration information) |
2 | yaml files can be incomplete and only the required fields are written | The yaml file must be a complete configuration field content |
3 | kubectl apply works only on some changed fields in the yaml file | kubectl create works in all fields in the yaml file |
4 | You can use kubectl apply when you only change some declarations in the yaml file, not all of them | If you execute the command kubectl replace with the same yaml file without changing the yaml file, it will not succeed (fail) because the relevant change information is missing |
(3)kubectl patch
(4)kubectl replace
(5)kubectl wait
(6)kubectl convert
(7)kubectl kustomize
8. Settings Commands
(1)kubectl label
Update (add, modify, or delete) the label on the resource. label must start with a letter or number. Letters, numbers, hyphens, dots and underscores can be used. The maximum length is 63 characters. If -- overwrite is true, you can overwrite the existing label, otherwise an error will be reported if you try to overwrite the label. If -- resource version is specified, the update will use this resource version, otherwise the existing resource version will be used.
grammar
$ label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
Example Add label unhealthy=true to the Pod named foo.
kubectl label pods foo unhealthy=true
Modify the label of Pod named foo to 'status' / value' unhealthy ', and overwrite the existing value.
kubectl label --overwrite pods foo status=unhealthy
Add label s to all pod s in the namespace
kubectl label pods --all status=unhealthy
The label on the Pod named foo is updated only when resource version = 1.
kubectl label pods foo status=unhealthy --resource-version=1
Delete the label named "bar". (connect with "-" minus sign)
kubectl label pods foo bar-
(2)kubectl annotate
Updates the Annotations information for one or more resources.
- Annotations consist of key/value.
- The purpose of Annotations is to store auxiliary data, especially the data operated through tools and system expansion. More details are introduced in here.
- If -- overwrite is true, existing annotations can be overwritten, otherwise an error will be reported if you try to overwrite annotations.
- If -- resource version is set, the update will use this resource version, otherwise the original resource version will be used.
Valid resource types include: all certificatesigningrequests (aka 'csr') clusterrolebindings clusterroles clusters (valid only for federation apiservers) componentstatuses (aka 'cs') configmaps (aka 'cm') controllerrevisions cronjobs daemonsets (aka 'ds') deployments (aka 'deploy') endpoints (aka 'ep') events (aka 'ev') horizontalpodautoscalers (aka 'hpa') ingresses (aka 'ing') jobs limitranges (aka 'limits') namespaces (aka 'ns') networkpolicies (aka 'netpol') nodes (aka 'no') persistentvolumeclaims (aka 'pvc') persistentvolumes (aka 'pv') poddisruptionbudgets (aka 'pdb') podpreset pods (aka 'po') podsecuritypolicies (aka 'psp') podtemplates replicasets (aka 'rs') replicationcontrollers (aka 'rc') resourcequotas (aka 'quota') rolebindings roles secrets serviceaccounts (aka 'sa') services (aka 'svc') statefulsets storageclasses thirdpartyresources
grammar
$ annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
Example Update the Pod "foo" and set the value "my frontend" of the annotation "description". If the same annotation is set multiple times, only the last set value will be used.
kubectl annotate pods foo description='my frontend'
Update the annotation of pod according to the type and name in "pod.json"
kubectl annotate -f pod.json description='my frontend'
Update the Pod"foo" and set the value "my frontend running nginx" of the annotation "description" to overwrite the existing value.
kubectl annotate --overwrite pods foo description='my frontend running nginx'
Update all pod s in the namespace
kubectl annotate pods --all description='my frontend running nginx'
Update pod 'foo' only when resource version is 1.
kubectl annotate pods foo description='my frontend running nginx' --resource-version=1
Update pod 'foo' by deleting annotations named "description"# No - overwrite flag is required.
kubectl annotate pods foo description-
(3)kubectl completion
9. Other Commands
(1)kubectl config
(2)kubectl plugin
(3)kubectl version
(4)kubectl api-versions
(5)kubectl api-resources
The version of this analysis is 1.17.4,use Calico As a network component, there are 67 different api-resources. 1. Binding: Deprecated. Used to record a object And another object Binding relationship. In fact, it is mainly used to pod and node Relationship, so in 1.7 After version, it has been changed to in pods.bindings Recorded in. 2. ComponentStatus: Is a global list(That is, it is not affected by namespace) k8s Relevant information of all components in, such as creation time, current status, etc. 3. Configmap: Is a method for recording pod Of itself or its internal configuration information API Resources can be considered through API Configuration files stored as. 4. Endpoints: Used to record each service of pod of**Real physics**ip and port The corresponding relationship of, including service yes TCP still UDP Wait. 5. Event: It is used to record events in the cluster, which can be regarded as similar to a record in the log. 6. LimitRange: Used to record data in various namespaces pod or container Restrictions on the use of each resource are generally included in pod In the definition of. 7. Namespace: Is a global list,Save all namespaces in the cluster. 8. Node: Is a global list,The of each node is recorded in detail name, labels, PodCIDR, host IP, hostname, Total resources( cpu,Memory), allocable resources, heartbeat status (network, memory, hard disk, PID quantity kubelet Etc.), kubelet Physics of port,various k8s assembly image Information, node Environmental information( os, CRI version, kubeProxy version, kubelet version Etc.). 9. PersistentVolumeClaim: Record user requirements for persistent storage. 10. PersistentVolume: Is a global object,Records the information of all persistent storage devices (similar to node) 11. Pod: Yes for use k8s The most important resources for developers, including ownerReference (Node, Demonset Etc.), containers Relevant information( image,Start command, probe,Resource information, storage information, end line, accept service Injection environment variable is (etc.), network setting( dns set up, port Settings, etc.), cluster scheduling related information (priority, tolerations,affinity,Restart rules, etc.), pod Status( hostIP,podIP,Start time, etc.) 12. PodTemplate: It is usually part of other resources, such as Jobs, DaemonSets, Replication Controllers. Its initialization has just been created pod of k8s Relevant information, generally label Wait. 13. Replication Controller: It is the most commonly used built-in system controller,To guarantee Pod The actual running quantity of meets the definition. If it is insufficient, it is responsible for creating it. If it is too much, it is responsible for notifying some pod terminate. 14. ResourceQuota: Used to record and limit a namespace The total resource consumption in is generally used for multi-user utilization namespace Limit resources. 15. Secrets: Actually pass the contents of the file base64 Exist after coding etcd Yes. stay Pod in container At startup, you can secretes Mount as a file in a certain path, so as to avoid storing important information in the image Yes. 16. ServiceAccout: Used to authorize the within the cluster pod visit apiServer. 17. Service: Very important and common resources for providing unified external services Service IP and port,Adjust traffic load balancing to multiple nodes in the cluster pod. Important configurations are: cluster IP,port,selector(Select the purpose of forwarding traffic pod),sessionAffinity Wait. The load balancing provided here is L3 TCP of 18. MutatingWebhookConfiguration: Unknown (internal) object) 19. ValidatingWebhookConfiguration: Unknown (internal) object) 20. CustomerResourceDefinitions: User defined resources are also very important resources. They are all kinds of resources k8s The basis on which plug-ins can exist, such as when they are to be implemented Clico When customizing plug-ins such as, the first thing to consider is apiServer How to process relevant request information. The definition of user-defined resources is apiServer The basis for processing resources. This topic is complex and will not be discussed in detail here. 21. APIService: definition API A resource for the service API There are two forms of requests,`/apis/GROUP/VERSION/*`This is not included in namespace In (i.e. global) and`/apis/GROUP/VERSION/namespaces/NAMESPACE/*`This is included in namespace When a request arrives apiServer After that, there must be corresponding code to deal with it GROUP and VERSION Determine a API,Respond to each API The requested code is abstracted as a service( service). Imagine a custom resource API Request arrival apiServer How to deal with it? Related service It is also custom and runs on master In, k8s It's based on APIService To correctly match the request with the correct service Association. It can be defined here service Name, security settings, priority, etc. 22. ControllerRevision: It's a beta Function for Controller Save your own historical state for easy update and rollback. 23. Daemenset: common Pod set Category, used to control each pod Status (quantity, calculate resource usage, probe Etc.) within the defined scope, and node There is at most one on the. 24. Replicaset: common Pod set But now it is basically not used directly to control each type pod Status (quantity, calculation of resource usage, probe Etc.) within the defined scope Replicasets Each in pod They should be identical and interchangeable, that is, they behave exactly the same externally, just as all hydrogen atoms (1 proton and 0 neutron) are indistinguishable. 25. Deployment: Most common Pod set Kind, can have Replicasets and Pod. Used to control the status (quantity) of owned resources, calculate resource usage, probe Etc.) within the scope of definition. 26. StatefulSet: common Pod set Type. And Deployment The difference is that it controls pod It is not interchangeable, but has constant labels throughout the life cycle. In this way, each pod You can have your own DNS Name, storage, etc pod After being deleted, this information will also be restored. 27. TokenReview: Unknown, seems to be related to apiServer of Webhook of token Authorization related. 28. LocalSubjectAccessReview: Unknown (internal) object),And a namespace for users/The group's authorization check is related. 29. SelfSubjectAccessReview: Unknown (internal) object),It is related to the current user checking whether he has permission to operate on a namespace. 30. SelfSubjectRulesReivew: Unknown (internal) object),Contains a list of operations that the current user can perform in a namespace. And apiServer Related to authorized security mode 31. SubjectAccessReviews: Unknown (internal) object),And users/The authorization check of the group is related and is not limited to a namespace. 32. HorizontalPodAutoScaler: control Pod set(such as Deployment)of pod Number of resources. Can be based on pod of CPU,Dynamic adjustment of memory and custom data pod Quantity. In[here](https://Link. Zhihu. COM /? Target = HTTPS% 3A / / kubernetes. IO / docs / tasks / run application / horizontal pod autoscale walkthrough /). 33. CronJob: Timing operation Job pod Resources. 34. Job: common Pod set A certain number of types will be created pod,Only if a specific number of pod After successful completion of this Job It ends successfully pod It will not be restarted after. 35. CertificateSigningRequests: It can be considered as an interface for Pod Wait for resources to apply for one X.509 Certificate. This certificate should be controller approve Or manually approve,Then it is signed by an appropriate object. For details, please refer to here. 36. Lease: Is one in 1.13 Resource type added in version, used for Node towards master Notify your own heartbeat information. In previous versions kebulet Yes via update NodeStatus notice master Heartbeat, later found NodeStatus It is too large and the heartbeat information is updated frequently, resulting in master The pressure is high, so it increases Lease Such resources. 37. EndpointSlice: It contains one service of Endpoint Part of the information resources. Reasons and Lease Similarly, for those with more information service(For example, there are many pod Distributed in multiple node Previous) endpoint object It may be large and frequently accessed, so there will be multiple users in this case endpointSlice Created mitigation master Pressure. 38. Event: Resources that describe events in a cluster, including message,event,reason,Detailed information such as report source. 39. Ingresse (APIGroup=extensions): Will be deprecated. 40. Ingresse (APIGroup=[http://networking.k8s.io]( https://link.zhihu.com/?target=http%3A//networking.k8s.io )): can be simply understood as a resource that defines a loadbalancer. It contains a series of rules that define the corresponding backend of different URLs, SSL termination, etc. Why does this new API replace the previous Ingress API of APIGroup=extensions? I checked many places and didn't find a specific text explanation, but it can be inferred that Ingress has officially become a part of the network module of k8s, and the corresponding server (code) has been migrated from extensions to[ http://networking.k8s.io](https://link.zhihu.com/?target=http%3A//networking.k8s.io). 41. NetworkPolicy: Defines which network traffic can go pod Resources. One NetworkPolicy You can specify a group pods,Define only if certain conditions (such as source) are met/objective IP,port,pod The network traffic of (name, etc.) can be changed accordingly pod Send and receive. 42. RuntimeClass: This is a new topic discussed in 2019 API resources.[file](https://Link. Zhihu. COM /? Target = HTTPS% 3A / / GitHub. COM / kubernetes / enhancements / blob / Master / keps / sig node / runtime class. MD% 23summary) the purpose is to expose the attributes of the Container Runtime environment to the control layer of k8s, so as to support multiple Container Runtime environments in a cluster or node. This facilitates the creation of more compatible k8s clusters in the future. 43. PodDisruptionBudget: This one API Resources enable users to pod Definition“ k8s Tolerable reality running Stateful pod The gap between quantity and expectation ". Consider a scenario where a cluster service After that, there are five identical ones pod To handle its flow, at least half of it is required pod Yes, but three of them pod Because the scheduling runs in node A Come on. If present node A The service is unavailable due to sudden failure and other conditions. There is no good way to deal with this inevitable accident (or the scheduling algorithm needs to know this) pod It should be distributed as evenly as possible on nodes, but at present k8s There is no function to enforce this scheduling). But in addition, there are many unexpected situations that can be avoided. For example, during cluster maintenance or other event processing, the Cluster Administrator may drain node A,Lead to three pod At the same time, it is closed, which affects the business. For this avoidable accident, if a group pod Because avoidable k8s Operation will be less than tolerable (at PodDisruptionBudget , then the command will be blocked and return failure. 44. PodSecurityPolicy: Defines a pod Created in cluster/function/Conditions to be met when updating. 45. ClusterRole: Defined in the cluster policy rule Some common collections of, such as`system-node`Etc. to control account permissions. 46. ClusterRoleBinding: An account is defined/Group pair ClusterRole A reference to for empowerment. 47. Roles: And front ClusterRole Similar, but as the name suggests ClusterRole It is related to cluster accounts, Role Is used for other accounts (e.g controller Used service account) 48. RoleBindings: An account is defined/Group pair Role A reference to for empowerment. 49. PriorityClass: Defined pod Mapping of priority name and corresponding value. For example`system-cluster-critical`The corresponding priority is 2000000000. The higher the value is, the higher the priority is. When the cluster is short of resources, some must be terminated pod Low priority pod Will be terminated first. Why not directly use the numerical value to represent the priority? Because it is easy to be determined arbitrarily. For example, developers A Developed a very important pod,Therefore, the value of its priority is set to 9999 in the code. However, the Cluster Administrator B May think 9999 is a small number, any one he created pod The priority of is 999999+. So need PriorityClass For unified management and comparison of priorities. 50. CSIDriver: Defines the container storage driver in the cluster API resources.[CSI](https://Link. Zhihu. COM /? Target = HTTPS% 3A / / kubernetes CSI. GitHub. IO / docs / introduction. HTML) represents the Container Storage Interface, that is, the Container Storage Interface. K8s should be able to use a variety of storage services, which are open-source by various cloud manufacturers. How can k8s know how to use these storage services? Then find the corresponding drivers through this CSIDriver resource. 51. CSINode: front CSIDriver The generated node related information exists CSINode Yes. 52. StorageClass: Defines the storage types that can exist API resources. 53. Volumeattachments: Defines a node distribution/Request to reclaim storage space API resources. 54. NetworkSets: What follows is Calico custom API Resources, not one by one, are related to network protocols/security/Management related. 55. NetworkPolicies: Calico custom API resources 56. IPPools: Calico custom API resources 57. IPAMHandles: Calico custom API resources 58. IPAMConfigs: Calico custom API resources 59. IPAMBlocks: Calico custom API resources 60. HostEndpoints: Calico custom API resources 61. GlobalNetworkSets: Calico custom API resources 62. GlobalNetworkPolicies: Calico custom API resources 63. FelixConfiguration: Calico custom API resources 64. ClusterInformation: Calico custom API resources 65. BlockAffinity: Calico custom API resources 66. BGPPeer: Calico custom API resources 67. BGPConfiguration: Calico custom API resources
Introduction to yaml file data definition in kubernetes
apiVersion: api edition kind: Resource type metadata: #metadata name: name namespace:Namespace labels: Label information (multiple) ##The tag is a key in the format of key: value. Value can only use 63 characters at most # A key can only be a combination of numbers, the mother of all,, -, and dots (.), #value can be empty, but can only start or end with numbers and letters app: Label content annotations: #Annotation (what function does not have is annotation) zhushi: "lalalalalalalal saddas" spec:Expected state containers:Container information (multiple name cloud images are allowed) - name: custom name name image: Image name - name: image: nodeSelector:#Node selector (if specified to run on a node with disk as ssd) disk: ssd imagePullPolicy:#Whether to use local or remote download image #1,Always #2,Never #3,IfNotPresent livenessProbe: #Survival probe #1,exec #command #2,httpGet #http request specifies ip:port #3,tcpSocket # readinessProbe: #Ready status probe #1,exec #command #2,httpGet #http request specifies ip:port #3,tcpSocket #
(6)kubectl options
reference resources
(1) English official- https://kubernetes.io/docs/reference/kubectl/overview/
(2) Chinese documents- http://docs.kubernetes.org.cn/683.html
(3) Detailed explanation of common Kubectl commands https://blog.csdn.net/weixin_44631350/article/details/89450781