Introduction
kubectl is the most direct and gradual way for k8s operation
Basic format: kubectl [command] [TYPE] [NAME] [flags] command subcommand TYPE resource type NAME resource name flags command parameter
0x00 Kubeadm
/Init/// Init initialization configuration parameter --apiserver-advertise-address (string) The IP address that the API server advertises that it is listening to --apiserver-bind-port(int32) API server binding port, default 6443 --apiserver-cert-extra-sans (stringSlice) Optional additional Subject Alternative Name for API Server service certificate, can be IP and DNS name --certificate-key (string) The key used to encrypt the control plane certificate in the kubeadm-certs Secret --control-plane-endpoint(string) Specify a stable IP address or DNS name for the control plane --image-repository(string) Select the container repository used to pull the control plane image, the default is k8s.gcr.io --kubernetes-version(string) Select a specific k8s version for the control plane, default stable-1 --cri-socket (string) Specify the path to the CRI socket to connect to --node-name (string) specify the name of the node --pod-network-cidr(string) The IP address segment that can be used by the well-known Pod network. If this parameter is set, the control plane will automatically assign CIDRS to each node --service-cidr(string) Specify an additional IP address segment for the virtual IP of the service, default 10.96.0.0/12 --service-dns-domain(string) Specify another domain name for the service, default cluster.local --token(string) used to establish bi-directional communication between control plane nodes and worker nodes --token-ttl(duration) The duration before the token is automatically deleted, set to 0 to never expire --upload-certs upload control plane certificates to kubeadm-certs Secret Example 1: cat << EOF > ./kubeadm-config.yaml apiVersion: v1 kind: ClusterConfiguration kubernetesVersion: v${K8SVERSION} imageRespository: registry.cn-hangzhou.aliyuncs.com/google_containers controlPlaneEndpoint: "${APISERVER_NAME}:6443" networking: serverSubnet: "10.99.0.0/16" podSubnet: "${POD_SUBNET}" dnsDomain: "cluster.local" EOF # After the execution is completed, it will display the cluster master node joining and node node joining prompts kubeadm init --config=kubeadm-config.yaml --upload-certs Example 2: kubeadm init --apiserver-advertise-address=0.0.0.0 \ --apiserver-cert-extra-sans=127.0.0.1 \ --image-repository=registry.aliyuncs.com/google_container \ --ignore-preflight-errors=all \ --kubernetes-version=v1.23.5 \ --service-cidr=10.96.0.0/16\ --pod-network-cidr=10.244.0.0/16\ --token-ttl=24h0m0s \ --control-plane-endpoint=192.168.2.175\ --upload-certs Example 3: kubeadm init phase upload-certs --upload-certs kubeadm init phase control-plane all --config=configfile.yaml kubeadm init phase etcd local --config=configfile.yaml kubeadm init --skip-phase=control-phase,etcd --config=configfile.yaml Example 4: kubeadm init phase upload-certs --upload-certs --certificate-key=SOME_VALUE --config=SOME_YAML_FILE /Token/// Token authentication related information create creates a bootstrap token on the server delete deletes the bootstrap token on the server generate Generate and print a bootstrap token, but don't create it on the server list lists bootstrap tokens on the server --dry-run Whether to start the running mode --print-join-command print node join command Example 1: kubeadm token create --print-join-command kubeadm token create $(kubeadm token generate) --print-join-command -ttl=0 Example 2: kubeadm token list Example 3: kubeadm token generate /Config/// Config The basic environment depends on the configuration images: --config(string) Path to kubeadm configuration file --image-repository(string) container repository --kubernetes-version(string) select a specific k8s version -o, --experimental-output (string) default value "text", optional text|json|yaml|go-template-file|template|template|templatefile|jsonpath|jsonfile-as-json|jsonpath-file --cri-socket (string) The socket path of the CRI to connect to, this option is only used when multiple CRIs are installed or non-standard CRI sockets print: Print the configuration information provided when the master is initialized or when the node joins migrate: converts a local old version of a configuration object to the latest supported version without changing anything in the cluster Example 1: specify mirror source kubeadm config images list --image-repository mirrororgcrio --kubernetes-version=1.18.3 Example 2: specify mirror source kubeadm config images pull --image-repository registry.cn-hangzhou.aliyuncs.com/google_containers --kubernetes-version=1.23.5 for i in $(kubeadm config images list --kubernetes-version=1.23.5 --image-repository registry.cn-hangzhou.aliyuncs.com/google_containers -v 5);do ctr -n k8s.io images pull ${i} done Example 3: Get build configuration kubeadm config view # deprecated kubectl get cm -o yaml -n kube-system kubeadm-config # official suggestion Example 4: Print kubeadm init initialization list, Master's initialization list kubeadm config print init-dafaults Example 5: Print the kubeadm join configuration object list, which is the initialization list of Node kubeadm config print join-defaults Example 6: Convert the local old version of the configuration object to the latest supported version, for example, the v1.23.1 version becomes the current latest v1.23.5 version kubeadm config migrate --new-config output new configuration file --old-config read old initialization configuration file kubeadm config migrate --old-config=kubeadm-config-init.yaml apiVersion: kubeadm.k8s.io/v1beta3 bootstrapTokens: -groups: - system: bootstrappers: kubeadm: default-node-token token: abcdef.0123456789abcdef ttl: 24h0m0s usages: -signing - authentication kind:InitConfiguration localAPIEndpoint: advertiseAddress: 10.10.107.225 bindPort: 6443 nodeRegistration: criSocket: /run/containerd/containerd.sock imagePullPolicy: IfNotPresent name: node taints: - effect: NoSchedule key: node-role.kubernetes.io/master --- apiServer: timeoutForControlPlane: 4m0s apiVersion: kubeadm.k8s.io/v1beta3 certificatesDir: /etc/kubernetes/pki clusterName: kubernetes controllerMananger: {} dns: {} etcd: local: dataDir: /var/lib/etcd imageRepository: registry.cn-hangzhou.aliyuncs.com/google_containers kind: Cluster Configuration kubernetesVersion: v1.23.5 networking: dnsDomain: cluster.local serviceSubnet: 10.96.0.0/12 scheduler: {} /Join/// Join cluster or node join initialization --control-plane control panel address --certificate-key certificate key --discovery-token-ca-cert-hash CA certificate SHA256 hash value --token bootstarp authentication token --cri-socket Path to Cri socket --config Path to kubeadm configuration file Example 1: The master node joins the cluster control plane kubeadm join apiserver.test:6443 --token hzlzrr.uwuegx4locpu36oc \ --discovery-token-ca-cert-hash sha256:xxx --control-plane --certificate-key xxx Example 2: Node node joins the control plane of the cluster kubeadm join apiserver.test:6443 --token hzlzrr.uwuegx4locpu36oc\ --discovery-token-ca-cert-hash sha256:xxx --cri-socket /run/containerd/containerd.sock Example 3: Use the configuration file to configure the node information to join kubeadm join --config node.yaml /Reset/// # reset node operation kubeadm reset -f /Upgrade/// # cluster upgrade kubeadm upgrade [flags]|[command] flags: --add-dir-header true Add the file directory to the log information --log-file log file --log-file-max-size file size --rootfs host file path --skip-headers true skip log headers prefix --skip-log-headers true will avoid headers when turned on -v log level Example: # Check for upgradeable versions kubeadm upgrade plan # Update the specified version kubeadm upgrade apply v1.18.5 --config kubeadm-config.yaml # don't change any state, just output what will be done kubeadm upgrade node --dry-run command: apply upgrades k8s to the specified version diff shows the diff that will be applied to an existing static pod manifest Upgrade commands for nodes in a node cluster plan checks the version that can be upgraded to, and verifies whether the current cluster can be upgraded. If you need to skip the internet check, please pass in the specified version
0x01 Kubectl
/autocomplete/// # Automatic completion To set the automatic completion of the current shell in bash, you must first install the bash-completion package source < (kubectl completion bash) # add to environment variable echo "source <(kubectl completion bash)" >> ~/.bashrc # zsh shell auto-completion echo "if [ $commands[kubectl] ]; then source <(kubectl completion zsh); fi" >> ~/.zshrc # Add to the startup configuration file to use a shorthand alias for kubectl, which can also be used with completion cat >> ~/.bashrc << 'END' alias k=kubectl complete -F __start_kubectl k END Example: k get cs /api-version/// kubectl api-versions # currently available versions /api-resources/// kubectl api-resoucres # Get a complete list of supported resources /apply/// # apply Use this command to reapply when the resource list is re-modified # 1, use kubectl apply to create the deployment kubectl apply -f deployment.yaml # Reapply configuration kubectl apply -f https://weiyigeek.top/k8s/deployment.yaml # 2, execute the deployment command of the deployment/service operation kubectl apply -f nginx-deployment.yaml kubectl apply -f redis-master-service.yaml # 3, Update k8s ConfigMap or Secret without deleting existing ones kubectl -n default create secret tls weiyigeek.top --cert=2023.weiyigeek.top.pem --key=2023.weiyigeek.top.key -o yaml --dry-run=client | kubectl apply -f - /attach/// # Interactive operation pod kubectl attach load-generator -c load-generator -i -t /cluster-info/// # k8s cluster information kubectl cluster-info /config/// # set external cluster & amp; & amp; delete external cluster kubectl config set-cluster k8s-cluster --server=https://slb-vip.k8s:16443 --certificate-authority=/etc/kuberbetes/pki/ca.crt --embed-certs=true kubectl config delete-cluster k8s-cluster # set context & amp; & amp; delete context kubectl config set-context devops-ctx --cluster=k8s-cluster --user=devopsuser --namespace=devops kubctl config delete-context devops-ctx # set user & amp; & amp; delete user kubectl config set-credentials devopsuser --client-key=/etc/kubernetes/pki/user/devopsuser-key.pem --client-certificate=/etc/kubernetes/pki/user/devopsuser-key.pem --user= devopsuser --embed-certs=true kubectl config delete-user devopsuser # Get the global context kubectl config get-context # Get the current context kubectl config current-context # Switch to the specified context kubectl config use-context devops-ctx /cp/// # Copy the files in the Pod to the specified directory kubectl cp weiyigeek/users-0:/usr/local/tomcat/logs /tmp/logs kubectl cp devops/test-28-1vw8p-vlr29-fxvqs:/home/jenkins/.ssh /tmp /create/// # Create a Pod according to the corresponding list kubectl create -f nginx-pod.yaml # Generate a deployment list according to the command kubectl create deployment javs-demo --image=WeiyiGeek/java-demo --dry-run -o yaml > deploy.yaml /cordon/// # Node limit join resource kubectl cordon node-1 # Prohibit newly created Pods from running on this node /describe/// # Display detailed information about resources # Format: kubectl describe resource type resource name # 1, View the information of the Pod named nginx-deployment-xxx kubectl describe pod nginx-deployment-xxx # 2, View deployment information kubectl describe deployment nginx-deployment # 3, View node information kubectl describe node master-03 /delete/// # delete nodes and resources # You can delete related nodes and resource objects Pods, Svc, Nodes, Namespace, ConfigMap, Deployment, Rs, Rc, sts # Format: kubectl delete [TYPE] Flags kubectl delete node k8s-master-1 kubectl -n kube-system delete Pods calico-xxx # delete container group kubectl delete pods cloudagile-mariadb-0 -n intelligence-data-lab -grace-period=0 --force #Forcibly delete specific pods kubectl get pods --field-selector=status.phase=Failed --all-namespace | awk `{system("kubectl delete pod "$2" -n " $1)}` # Delete failed Pods in the cluster kubectl get pods --all-namespaces | grep Terminating||grep -w "0/1" | awk `system("kubectl delete pod "$2" -n "$1" --grace-period=0 --force") ` /drain/// # Node component cleanup # Example 1, forcefully delete the local data of the node and the running container kubectl drain master-02 --delete-local-data --force --ignore-daemonsets kubectl get nodes master-02 # Example 2, forcibly delete Pods in terminal state or abnormal state, the waiting time is 0 kubectl delete pod -n ingress-nginx --force --grace-period=0 ingress-nginx-controller-xxx /exec/// # Execute commands in the container environment in the Pod # Format: kubectl exec PodName operation command | kubectl exec -n namespace -it Pod name -c container name -- /bin/sh # Example, run bash in a Pod named nginx-pod-xxxx kubectl exec -it nginx-deployment-xxx /bin/bash # Example, enter one of the multiple containers of the Pod, for example, enter the Blog container of the Pod named xxx kubectl exec -n test -it xxx -c Blog -- /bin/bash /expose/// # Reserve resources publicly for new SVC services # Find resources such as deployment, service, replica set, replication controller or pod by name, and expose them as new k8s services # Format: 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] # parameter list --dry-run[=false] If set to true, the trial run operation is not really executed --external-ip="" Mount accessible nodes not managed by k8s --filename resource file to expose the service --generator="service/v2" Generate according to SVC API template --labels="" Create service-specific labels --load-balancer-ip="" load balancer ip, if not specified, k8s will assign the default value --name="" newly created object name --port="" SVC port --target-port="" proxy port --protocol="" protocol --type="" service type, range: ClusterIP, NodePort, LoadBalancer, ExternalName, Default # Example: Create a service named nginx-external for nginx deployment, which serves on port 80 and points to port 8080 of the Pod container kubectl expose deployment nginx --name nginx-external --type=ClusterIP --port=80 --target-port=8000 # Example: Create an alias service nginx-web-external for the nginx-web service, whose type is NodePort, pay attention to the random port here kubectl expose service -n devtest nginx-web --name nginx-web-external --type=NodePort --port=80 --target-port=80 # View execution results kubectl get svc -n devtest nginx-web-external /get/// # Display k8s-related resource object information Pod, Svc, Nodes, NameSpace, ConfigMap, Deployment, Rs, Rc, sts # Syntax: kubectl get resource type # parameters -l Get a list of related labels tags -o formatted output --namespace specify namespace lookup --template format with go-template # example kubectl get deployments kubectl get pods # Get the default namespace kubectl get pods --all-namespace kubectl get pods -l app=nginx # Get the specified labels kubectl get pods -n kube-system -l "app.kubernetes.io/name=kubernetes-dashhoard,app.kubernetes.io/instance=kubernetes-dashboard" -o jsonpath="{.item[0].metedata.name }" # filter to get kubectl get pods --namespace kube-system -o jsonpath="{..image}" # only output image name kubectl get pods --all-namespace -o=jsonpath="{..image}" -l app=redis kubectl get pods --all-namespace -o jsonpath="{..image}" | tr -s '[[:space]]' '\ ' | sort | uniq -c # Replace spaces with new lines, and sort the result, then count kubectl get pod -n weiyigeek -l ref=info-student -o jsonpath="{.items[*].status.podIP}" | tr -s '[[:space]]' '\ ' > ip.txt # interpret ip for x in $(cat ip.txt); do echo -n "$x -";curl -v http://${x}:8080;echo "";done # Use the absolute path of the image field in the Pod to find the image name in the container, which can avoid the repeated image kubectl get pods --all-namespace -o jsonpath="{.items[*].spec.containers[*].image}" | tr -s '[[:space:]]' '\ ' | uniq - c | sort -r kubectl get pods -o jsonpath="{.items[*].spec.containers[*].image}" | tr -s '[[:space:]]' '\ ' | uniq -c | sort -r # If you search for a Pod by name, since there is only one Pod in the returned result, the .items[*] part should be removed from the jsonpath kubectl get pods redis-master-deployment-xxx -o jsonpath="{.spec.containers[*].image}" | tr -s '[[:space:]]' '\ ' | uniq -c | sort -c # Find output results by pod can be traversed by range kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{","}{ end}{end}' | sort kubectl get pods --all-namespace -o go-template --template="{<!-- -->{range .items}}{<!-- -->{range .spec.containers}}{< !-- -->{.image}}{<!-- -->{end}}{<!-- -->{end}}" # View node resource type kubectl get nodes kubectl get nodes -o wide # View Deployments kubectl get deployments -A kubectl get deployments -n kube-system # View Service kubectl get services -o wide kubectl get svc -o wide # View configuration file information kubectl get cm kubeadm-config -n kube-system -o yaml # View election information kubectl get ep kube-controller-manager -n kube-system -o yaml # check copy kubectl get rs /logs/// # Output Pod logs # parameters -c, --container="" -f, --follow[=false] Whether to continue to output logs --interactive[=true] If true, prompt the user for input when required --limit-bytes=0 the maximum number of bytes to output the log -p, --previous[=false] If true, output the log of the container that has been running in the Pod but is currently terminated --since=0 only return relative time ranges --since-time="" Return the format after the specified time --tail=-1 The latest log number to display --timestamps[=false] include timestamps in logs # example kubectl logs -f nginx-deployment-xxx # Output the log of the stopped container web-1 in pod-ruby kubectl logs -p -c ruby web-1 # Continuously output the log of web-1 of the ruby container kubectl logs -f -c ruby web-1 # Output the first 20 logs of nginx kubectl logs --tail=20 nginx # Output the logs of the last hour in nginx kubectl logs --since=1h nginx /run/// # Run a Pod application # example kubectl run helloworld --image=hello-world # Create Pods independently /replace/// # replace resource with filename or stdin # parameters -f, --filename=[] --force=false force --wait=false if true, wait for the resource to disappear before returning #Example: kubectl replace -f ./pod.json # Replace existing resources with json files cat pod.json | kubectl replace -f - # replace a pod based on the json passed to stdin kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - # Upgrade the container image version to v4 kubectl replace --force -f ./pod.json # force replacement /port-forward/// # Use the name of the resource for local port forwarding # Forward one or local port to pod, this command requires the node to install socat, use the resource type/name (such as deployment/mydeployment) to select the pod, if the resource type is omitted, the default is pod # grammar: kubectl port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] # parameters --address=[localhost] # Addresses to monitor, separated by commas --pod-running-timeout=1m0s # Waiting time length, such as 5s, 2m, 3h # Example: kubectl port-forword pod/mypod :5000 # Listen on a local random port and forward to pod's 5000 kubectl port-forword service/myservice 8443:https # The local listening port 8443 is forwarded to the targetPORT of the service port named https in the pod selected by the service kubectl port-forword --address 127.0.0.1,10.10.107.191 pod/redis-master-xxx 7000:6379 # Map redis-master Pod's 6379 to 127.0.0.1,10.10.107.191's 7000 /label/// # Label information, through the label setting to control the affinity of the Pod to the node # Node role name setting kubectl label node weiyigeek-23 node-role.kubernetes.io/work=test # cancel the node role name kubectl label node weiyigeek-23 node-role.kubernetes.io/work /top/// # Linux top kubectl top node /scale/// # Dynamically update the number of replicas kubectl -n app scale statefulset/xk-student --replicas=0 /set/// # configure application resources kubectl set SUBCOMMAND [options] SUBCOMMAND: env Update template environment variables image update template image address resources Update the requests/limits of resources on the pod templates of the object selector set the selector of the resource serviceaccount update resource service account subject to update a user, group, or service account in a role binding or cluster role binding # case kubectl set image deployment/nginx busybox=busybox:latest nginx=nginx:1.21.0 # Set the nginx resource managed by the deployment controller, and replace the nginx image with 1.21.0 kubectl set image deployments,rc nginx=nginx:1.19.1 --all # Update all deployment and rc nginx container images to 1.19 kubectl set image daemonset abc *=nginx:1.9.1 # Update the image of all containers of abc of the daemon to nginx:1.9 /wait/// # Wait for a specific condition on one or more resources # This command will occupy multiple resources, by using the -for flag to wait to see the specified condition resource in the status field of each given object, and will output a success message to the standard indicating when the specified condition is met, and can Change the output destination with -o # example kubectl wait --namespace ingress-nginx --for=condition=ready pod --selector=app.kubernetes.io/component=controller --timeout=120s # Waiting for the ingress-related resource Pod status to be Ready, use the label selector, The timeout is 120s kubectl wait --for=condition=Ready pod/busbox1 # Wait for pod busybox to contain a status condition of type Ready kubectl delete pod/busybox kubectl wait --for=delete pod/busybox --timeout=60s # After issuing the delete command, wait for the pod busybox to be deleted, with a timeout of 60s kubectl wait --for=jsonpath='{.status.phase}'=Running pod/busybox # wait for busybox to contain the running status phase /rollout/// # rolling update kubectl rollout status deployment neginx-deployment # View the current update status kubectl rollout history deployment/nginx-deployment kubectl rollout undo deployment/nginx-deployment # View historical versions that can be rolled back kubectl rollout undo deployment/nginx-deployment --to-revision=2 # Roll back to a certain version kubectl rollout pause deployment/nginx-deployment # Pause the update of deployment
Follow-up will continue to complete