K8S kubectl命令总结

1. 创建 Pod

# kubectl run
kubectl run nginx --image=nginx --port=80

kubectl run -it busybox --rm=true --image=busybox:1.28.4 -- /bin/sh

2. 暴露端口

# kubectl expose
kubectl expose pod nginx --type=NodePort --port=8000 --target-port=80

Port configurations for Kubernetes Services:

  • Port: The port of this service
  • TargetPort: The target port on the pod(s) to forward traffic to
  • NodePort: The port on the node where external traffic will come in on

3. 注释

# kubectl annotate
kubectl annotate pod nginx created_at='2021-10-21 17:32:19'
kubectl annotate pod nginx created_at='2021-10-22 10:21:56' --overwrite 

4. 标签

# label
kubectl label pod nginx unhealthy=true
kubectl label pod nginx unhealthy=false --overwrite 

5. 水平自动伸缩

kubectl autoscale deployment foo --min=2 --max=10
kubectl autoscale rc foo --max=5 --cpu-percent=80

6. 创建资源

# namespace
kubectl create namespace ns1

# role
kubectl create role admin --verb=get,list,watch --resource=pods,pods/status

# rolebinding
kubectl create rolebinding admin --clusterrole=admin --user=user1 --user=user2 --group=group1

# clusterrole
kubectl create clusterrole foo --verb=get,list,watch --resource=pods,pods/status

# clusterrolebinding
kubectl create clusterrolebinding foo --clusterrole=foo --user=user1 --user=user2 --group=group1

# configmap
kubectl create configmap config1 --from-literal=key1=value1 --from-literal=key2=value2

kubectl create configmap config2 --from-file=config.txt
kubectl get configmap config2 -o yaml
apiVersion: v1
data:
  config.txt: |
    a=1
    b=2
    c=3
kind: ConfigMap
metadata:
  creationTimestamp: "2021-10-21T11:24:50Z"
  name: config2
  namespace: default
  resourceVersion: "897826"
  uid: a5be5173-5315-40dc-b65a-937d83d2bc04
  
# deployment
kubectl create deployment nginx-deploy --image=nginx --replicas=5 --port=80

# quota
kubectl create quota my-quota --hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10

# service
kubectl create service clusterip svc1 --tcp=5678:8080
kubectl create service clusterip svc2 --clusterip="None"
kubectl create service externalname svc3 --external-name bar.com
kubectl create service loadbalancer svc4 --tcp=5678:8080
kubectl create service nodeport svc5 --tcp=5678:8080

# serviceaccount
kubectl create serviceaccount my-service-account

# secret 
kubectl create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key
kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub
kubectl create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL

7. 更新资源字段

# kubectl patch
kubectl patch node k8s-node01 -p '{"spec":{"unschedulable":true}}'

kubectl patch pod nginx -p '{"spec":{"containers":[{"name":"nginx","image":"nginx:1.21.3"}]}}'

8. 滚动升级

# kubectl rollout
kubectl rollout history deployment/nginx-deploy

kubectl rollout pause deployment/nginx-deploy   # 暂停更新
kubectl rollout resume deployment/nginx-deploy  # 恢复更新

kubectl rollout status deployment/nginx-deploy

kubectl rollout undo deployment/nginx-deploy

9. 调整副本数

kubectl scale --replicas=10 deployment/nginx-deploy

10. 资源设置

# 设置资源限制
kubectl set resources deployment nginx-deploy --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi


# 设置镜像
kubectl set image deployment/nginx-deploy nginx=nginx:1.21.3

11. 命令表

OperationSyntaxDescription
alphakubectl alpha SUBCOMMAND [flags]List the available commands that correspond to alpha features, which are not enabled in Kubernetes clusters by default.
annotatekubectl annotate (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]Add or update the annotations of one or more resources.
api-resourceskubectl api-resources [flags]List the API resources that are available.
api-versionskubectl api-versions [flags]List the API versions that are available.
applykubectl apply -f FILENAME [flags]Apply a configuration change to a resource from a file or stdin.
attachkubectl attach POD -c CONTAINER [-i] [-t] [flags]Attach to a running container either to view the output stream or interact with the container (stdin).
authkubectl auth [flags] [options]Inspect authorization.
autoscalekubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]Automatically scale the set of pods that are managed by a replication controller.
certificatekubectl certificate SUBCOMMAND [options]Modify certificate resources.
cluster-infokubectl cluster-info [flags]Display endpoint information about the master and services in the cluster.
completionkubectl completion SHELL [options]Output shell completion code for the specified shell (bash or zsh).
configkubectl config SUBCOMMAND [flags]Modifies kubeconfig files. See the individual subcommands for details.
convertkubectl convert -f FILENAME [options]Convert config files between different API versions. Both YAML and JSON formats are accepted. Note - requires kubectl-convert plugin to be installed.
cordonkubectl cordon NODE [options]Mark node as unschedulable.
cpkubectl cp <file-spec-src> <file-spec-dest> [options]Copy files and directories to and from containers.
createkubectl create -f FILENAME [flags]Create one or more resources from a file or stdin.
deletekubectl delete (-f FILENAME | TYPE [NAME | /NAME | -l label | --all]) [flags]Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources.
describekubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags]Display the detailed state of one or more resources.
diffkubectl diff -f FILENAME [flags]Diff file or stdin against live configuration.
drainkubectl drain NODE [options]Drain node in preparation for maintenance.
editkubectl edit (-f FILENAME | TYPE NAME | TYPE/NAME) [flags]Edit and update the definition of one or more resources on the server by using the default editor.
execkubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]Execute a command against a container in a pod.
explainkubectl explain [--recursive=false] [flags]Get documentation of various resources. For instance pods, nodes, services, etc.
exposekubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags]Expose a replication controller, service, or pod as a new Kubernetes service.
getkubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags]List one or more resources.
kustomizekubectl kustomize <dir> [flags] [options]List a set of API resources generated from instructions in a kustomization.yaml file. The argument must be the path to the directory containing the file, or a git repository URL with a path suffix specifying same with respect to the repository root.
labelkubectl label (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]Add or update the labels of one or more resources.
logskubectl logs POD [-c CONTAINER] [--follow] [flags]Print the logs for a container in a pod.
optionskubectl optionsList of global command-line options, which apply to all commands.
patchkubectl patch (-f FILENAME | TYPE NAME | TYPE/NAME) --patch PATCH [flags]Update one or more fields of a resource by using the strategic merge patch process.
pluginkubectl plugin [flags] [options]Provides utilities for interacting with plugins.
port-forwardkubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]Forward one or more local ports to a pod.
proxykubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]Run a proxy to the Kubernetes API server.
replacekubectl replace -f FILENAMEReplace a resource from a file or stdin.
rolloutkubectl rollout SUBCOMMAND [options]Manage the rollout of a resource. Valid resource types include: deployments, daemonsets and statefulsets.
runkubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client|none] [--overrides=inline-json] [flags]Run a specified image on the cluster.
scalekubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags]Update the size of the specified replication controller.
setkubectl set SUBCOMMAND [options]Configure application resources.
taintkubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N [options]Update the taints on one or more nodes.
topkubectl top [flags] [options]Display Resource (CPU/Memory/Storage) usage.
uncordonkubectl uncordon NODE [options]Mark node as schedulable.
versionkubectl version [--client] [flags]Display the Kubernetes version running on the client and server.
waitkubectl wait ([-f FILENAME] | resource.group/resource.name | resource.group [(-l label | --all)]) [--for=delete|--for condition=available] [options]Experimental: Wait for a specific condition on one or many resources.

参考文档:https://kubernetes.io/docs/reference/kubectl/overview/#operations

### 使用 `kubectl` 启动资源的最佳实践与示例 #### 1. 创建 Pod 资源 通过 YAML 文件定义 Pod 的配置并使用 `kubectl apply` 或 `kubectl create` 命令来启动它。 以下是创建一个简单 Nginx Pod 的 YAML 配置文件 (`nginx-pod.yaml`): ```yaml apiVersion: v1 kind: Pod metadata: name: nginx-pod namespace: default spec: containers: - name: nginx-container image: nginx:latest ports: - containerPort: 80 ``` 执行以下命令启动该 Pod: ```bash kubectl apply -f nginx-pod.yaml ``` 或者也可以使用 `kubectl create` 来完成相同的操作[^3]。 #### 2. 动态创建资源 如果不想编写 YAML 文件,可以直接通过命令行动态创建资源。例如,创建一个运行 BusyBox 容器的 Pod: ```bash kubectl run busybox --image=busybox --command -- sleep infinity ``` 此命令会自动创建一个名为 `busybox` 的 Pod 并保持其处于活动状态[^4]。 #### 3. 检查 Pod 状态 在成功启动 Pod 后,可以通过以下命令查看其状态: ```bash kubectl get pods ``` 对于更详细的描述信息,可使用: ```bash kubectl describe pod <pod-name> -n <namespace> ``` 这有助于排查潜在问题或了解 Pod 当前的状态[^1]。 #### 4. 访问容器内部环境 为了调试正在运行中的 Pod,可以进入其交互式 Shell: ```bash kubectl exec -it <pod-name> -- /bin/sh ``` 如果是多容器 Pod,则需指定目标容器名称: ```bash kubectl exec -it <pod-name> -c <container-name> -- /bin/sh ``` 此外还可以复制本地文件到远程 Pod 中或反之: ```bash kubectl cp <local-path> <pod-name>:<remote-path> ``` 上述操作均支持跨命名空间访问[^2]。 #### 5. 删除已存在的资源 当不再需要某个特定资源时,应该及时清理以释放计算资源。删除之前创建好的 Pod 可采用如下方式之一实现: - 如果是从 YAML 文件部署而来则推荐再次利用原路径参数卸载整个结构体; - 对于单独实例化出来的实体则只需提供相应标识符即可。 ```bash kubectl delete -f nginx-pod.yaml ``` 或者直接按名字移除单个组件: ```bash kubectl delete pod <pod-name> ``` --- ### 总结 以上介绍了几种常见的基于 `kubectl` 工具启动 Kubernetes 集群内各类基础服务单元的方法及其配套维护手段。合理运用这些技巧能够帮助管理员更加高效便捷地管理大规模分布式应用架构下的工作负载。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值