点击上方👆蓝色字体关注博主
心若改变,你的态度跟着改变;态度改变,你的习惯跟着改变;习惯改变,你的性格跟着改变;性格改变,你的人生跟着改变。
《亚伯拉罕·马斯洛》
准备工作
1.1、Replication Controller
vim myhello-rc.yaml
apiVersion: v1
kind: ReplicationController # 副本控制器 RC
metadata:
namespace: default
name: myhello-rc # RC名称,全局唯一
labels:
name: myhello-rc
spec:
replicas: 5 # Pod副本期待数量
selector:
name: myhello-rc-pod
template: # pod的定义模板
metadata:
labels:
name: myhello-rc-pod
spec:
containers: # Pod 内容的定义部分
- name: myhello #容器的名称
image: nongtengfei/hello:1.0.0 #容器对应的 Docker Image
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
env: # 注入到容器的环境变量
- name: env1
value: "k8s-env1"
- name: env2
value: "k8s-env2"
vim myhello-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: myhello-svc
labels:
name: myhello-svc
spec:
type: NodePort # 对外提供端口
ports:
- port: 80
protocol: TCP
targetPort: 80
name: http
nodePort: 30000
selector:
name: myhello-rc-pod
kubectl apply -f myhello-svc.yaml -f myhello-rc.yaml
1.2、Deployment
vim myapp-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-deployment
labels:
name: myapp-deploy
spec:
replicas: 5
selector:
matchLabels:
name: myapp-deploy-pod
template:
metadata:
labels:
name: myapp-deploy-pod
spec:
#nodeSelector:
#nodetype: worker
containers: # Pod 内容的定义部分
- name: myhello #容器的名称
image: nongtengfei/hello:1.0.0 #容器对应的 Docker Image
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
env: # 注入到容器的环境变量
- name: env1
value: "k8s-env1"
- name: env2
value: "k8s-env2"
resources:
requests:
cpu: 100m
- name: myredis #容器的名称
image: redis #容器对应的 Docker Image
imagePullPolicy: IfNotPresent
ports:
- containerPort: 6379
env: # 注入到容器的环境变量
- name: env1
value: "k8s-env1"
- name: env2
value: "k8s-env2"
resources:
requests:
cpu: 100m
vim myapp-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-svc
labels:
name: myapp-svc
spec:
type: NodePort # 对外提供端口
ports:
- port: 80
protocol: TCP
targetPort: 80
name: http
nodePort: 30001
selector:
name: myapp-deploy-pod
kubectl apply -f myapp-svc.yaml -f myapp-deployment.yaml
1.3、DaemonSet
vim myapp-ds.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: myapp-ds
namespace: default
labels:
app: myapp-ds
spec:
selector:
matchLabels:
app: myapp-ds
template:
metadata:
labels:
app: myapp-ds
spec:
tolerations:
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
containers: # Pod 内容的定义部分
- name: myhello #容器的名称
image: nongtengfei/hello:1.0.0 #容器对应的 Docker Image
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
env: # 注入到容器的环境变量
- name: env1
value: "k8s-env1"
- name: env2
value: "k8s-env2"
vim myapp-ds-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-ds-svc
labels:
name: myapp-ds-svc
spec:
type: NodePort # 对外提供端口
ports:
- port: 8080
protocol: TCP
targetPort: 80
name: http
nodePort: 30002
selector:
app: myapp-ds
kubectl apply -f myapp-ds-svc.yaml -f myapp-ds.yaml
1.4、查看创建的svc和pod
$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 45h
myapp-ds-svc NodePort 10.96.41.180 <none> 8080:30002/TCP 4m3s
myapp-svc NodePort 10.98.20.127 <none> 80:30001/TCP 6m32s
myhello-svc NodePort 10.106.252.61 <none> 80:30000/TCP 14m
$ kubectl get pod
NAME READY STATUS RESTARTS AGE
myapp-deployment-5659dbddd8-l6m87 0/2 Pending 0 6m41s
myapp-deployment-5659dbddd8-lxxls 0/2 Pending 0 6m41s
myapp-deployment-5659dbddd8-pqqlx 0/2 Pending 0 6m41s
myapp-deployment-5659dbddd8-xb8xp 0/2 Pending 0 6m41s
myapp-deployment-5659dbddd8-zjgsx 0/2 Pending 0 6m41s
myapp-ds-2zqf9 1/1 Running 0 2m43s
myhello-rc-2tjmr 0/1 Pending 0 12m
myhello-rc-44ksd 0/1 Pending 0 12m
myhello-rc-86g79 0/1 Pending 0 12m
myhello-rc-df225 0/1 Pending 0 12m
myhello-rc-lfbzb 0/1 Pending 0 12m
1.5、kubectl 命令自动补全设置
# 安装自动补全插件
sudo apt-get install -y bash-completion
# 添加.bashrc文件内容
echo "source <(kubectl completion bash)" >> ~/.bashrc
# 加载最新的.bashrc
source ~/
kubectl语法
kubectl [command] [TYPE] [NAME] [flags]
kubectl get pod pod1
kubectl get pods pod1
kubectl get po pod1
kubectl get pods
kubectl get pod pod1 pod2 pod3
kubectl get pod/pod1 pod/pod2 rc/rc1 svc/svc1
c)用一个或多个文件指定资源:-f file1 -f file2 -f file<#>
kubectl get -f myhello-rc.yaml -f myhello-svc.yaml
kubectl get -f myhello-rc.yaml -f myhello-svc.yaml -o wide
kubectl get -f myhello-rc.yaml -f myhello-svc.yaml --output json
基础操作命令
3.1、api-resources
# 打印支持的API Resource
kubectl api-resources
# 打印更多信息
kubectl api-resources -o wide
# 根据name 排序
kubectl api-resources --sort-by=name
# 仅打印支持命名空间的资源
kubectl api-resources --namespaced=true
# 打印不支持命名空间的资源
kubectl api-resources --namespaced=false
# 根据分组打印该分组的资源,例如:apps、authorization.k8s.io 等
kubectl api-resources --api-group=apps
$ kubectl api-resources
NAME SHORTNAMES APIVERSION NAMESPACED KIND
bindings v1 true Binding
componentstatuses cs v1 false ComponentStatus
configmaps cm v1 true ConfigMap
endpoints ep v1 true Endpoints
events ev v1 true Event
limitranges limits v1 true LimitRange
namespaces ns v1 false Namespace
nodes no v1 false Node
persistentvolumeclaims pvc v1 true PersistentVolumeClaim
persistentvolumes pv v1 false PersistentVolume
pods po v1 true Pod
podtemplates v1 true PodTemplate
replicationcontrollers rc v1 true ReplicationController
resourcequotas quota v1 true ResourceQuota
secrets v1 true Secret
serviceaccounts sa v1 true ServiceAccount
services svc v1 true Service
mutatingwebhookconfigurations admissionregistration.k8s.io/v1 false MutatingWebhookConfiguration
validatingwebhookconfigurations admissionregistration.k8s.io/v1 false ValidatingWebhookConfiguration
customresourcedefinitions crd,crds apiextensions.k8s.io/v1 false CustomResourceDefinition
apiservices apiregistration.k8s.io/v1 false APIService
controllerrevisions apps/v1 true ControllerRevision
daemonsets ds apps/v1 true DaemonSet
deployments deploy apps/v1 true Deployment
replicasets rs apps/v1 true ReplicaSet
statefulsets sts apps/v1 true StatefulSet
tokenreviews authentication.k8s.io/v1 false TokenReview
localsubjectaccessreviews authorization.k8s.io/v1 true LocalSubjectAccessReview
selfsubjectaccessreviews authorization.k8s.io/v1 false SelfSubjectAccessReview
selfsubjectrulesreviews authorization.k8s.io/v1 false SelfSubjectRulesReview
subjectaccessreviews authorization.k8s.io/v1 false SubjectAccessReview
horizontalpodautoscalers hpa autoscaling/v2 true HorizontalPodAutoscaler
cronjobs cj batch/v1 true CronJob
jobs batch/v1 true Job
certificatesigningrequests csr certificates.k8s.io/v1 false CertificateSigningRequest
leases coordination.k8s.io/v1 true Lease
endpointslices discovery.k8s.io/v1 true EndpointSlice
events ev events.k8s.io/v1 true Event
flowschemas flowcontrol.apiserver.k8s.io/v1beta2 false FlowSchema
prioritylevelconfigurations flowcontrol.apiserver.k8s.io/v1beta2 false PriorityLevelConfiguration
ingressclasses networking.k8s.io/v1 false IngressClass
ingresses ing networking.k8s.io/v1 true Ingress
networkpolicies netpol networking.k8s.io/v1 true NetworkPolicy
runtimeclasses node.k8s.io/v1 false RuntimeClass
poddisruptionbudgets pdb policy/v1 true PodDisruptionBudget
clusterrolebindings rbac.authorization.k8s.io/v1 false ClusterRoleBinding
clusterroles rbac.authorization.k8s.io/v1 false ClusterRole
rolebindings rbac.authorization.k8s.io/v1 true RoleBinding
roles rbac.authorization.k8s.io/v1 true Role
priorityclasses pc scheduling.k8s.io/v1 false PriorityClass
csidrivers storage.k8s.io/v1 false CSIDriver
csinodes storage.k8s.io/v1 false CSINode
csistoragecapacities storage.k8s.io/v1 true CSIStorageCapacity
storageclasses sc storage.k8s.io/v1 false StorageClass
volumeattachments storage.k8s.io/v1 false VolumeAttachment
fly@k8s-master1:~/k8sCtlConfig$
3.2、api-versions
kubectl api-versions
$ kubectl api-versions
admissionregistration.k8s.io/v1
apiextensions.k8s.io/v1
apiregistration.k8s.io/v1
apps/v1
authentication.k8s.io/v1
authorization.k8s.io/v1
autoscaling/v1
autoscaling/v2
autoscaling/v2beta2
batch/v1
certificates.k8s.io/v1
coordination.k8s.io/v1
discovery.k8s.io/v1
events.k8s.io/v1
flowcontrol.apiserver.k8s.io/v1beta1
flowcontrol.apiserver.k8s.io/v1beta2
networking.k8s.io/v1
node.k8s.io/v1
policy/v1
rbac.authorization.k8s.io/v1
scheduling.k8s.io/v1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
3.3、create
kubectl create -f FILENAME
# 基于文件创建资源
kubectl create -f myhello-rc.yaml -f myhello-svc.yaml -f myapp-deployment.yaml -f
myapp-svc.yaml -f myapp-ds.yaml
# 将文件内容以标准输入,传入kubectl create
cat myhello-rc.yaml | kubectl create -f -
# 编辑文件,以编辑结果为输入参数
kubectl create -f myhello-rc.yaml --edit -o json
3.4、expose
kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP|SCTP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]
# 为副本控制器myhello-rc 创建service,端口为8000,容器端口为80
kubectl expose rc myhello-rc --port=8000 --target-port=80 --name=myhello-svc-8000
# 通过replication controller 定义文件来创建service
kubectl expose -f myhello-rc.yaml --port=8000 --target-port=80 --name=myhellosvc-8000-file
# 根据指定的pod 创建service,并指定service名称
kubectl expose pod <podname> --port=444 --name=myhello-svc-444
# 通过service 创建新的service
kubectl expose service myhello-svc --port=8080 --target-port=80 --name=myhello-svc-8080
# 查看所有service
kubectl get svc
# 查看某个service详情
kubectl describe svc <svcname>
3.5、run
kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client] [--overrides=inline-json] [--command] -- [COMMAND] [args...]
# 通过镜像运行一个名为 nginx 的pod
kubectl run nginx --image=nginx
# 通过镜像运行一个名为myhello 的pod
kubectl run myhello --image=nongtengfei/hello:1.0.0
# 指定端口号、环境变量、labels
kubectl run redis --image=redis --port=6379 --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default" --labels="app=redis,env=prod"
# 只打印命令执行的结果,而不做实际操作
kubectl run nginx --image=nginx --dry-run=client
# 运行一个busybox容器,并进入交互,同时设置其重启策略为Never
kubectl run -i -t busybox --image=busybox --restart=Never
# 启动nginx pod 采用自定义启动命令和启动参数
# kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
kubectl run nginx2 --image=nginx --command -- echo 123456
# 查看默认命名空间下所有pod
kubectl get pod
# 获取单个pod并以yaml格式输出
kubectl get pod <podname> -o yaml
# 输出某个pod内所有容器的日志
kubectl logs pod/<podname> --all-containers=true
# 输出 pod/myhello-rc-dtshm 内 myhello容器的日志
kubectl logs pod/myhello-rc-dtshm -c myhello
3.6、set
kubectl set SUBCOMMAND
3.6.1、env
kubectl set env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N
# 为rc/myhello-rc 添加环境变量 STORAGE_DIR=/local
kubectl set env rc/myhello-rc STORAGE_DIR=/local
# 查看 rc/myhello-rc 环境变量列表
kubectl set env rc/myhello-rc --list
# 列出所有pod的环境变量列表
kubectl set env pods --all --list
# 设置环境变量,并以yaml格式打印出来
kubectl set env rc/myhello-rc STORAGE_DIR=/data1 -o yaml
# 为所有rc设置环境变量为 EVN=prod
kubectl set env rc --all ENV=prod
# 将所有rc上环境变量 ENV移除
kubectl set env rc --all ENV-
# 移除 deployments/myapp-deployment 对象中,容器名为 myhello 的环境变量 env1
kubectl set env deployments/myapp-deployment --containers="myhello" env1-
# 根据文件,移除资源上的环境变量
kubectl set env -f myhello-rc.yaml env1-
3.6.2、image
kubectl set image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N
# 将deployment/myapp-deployment 中myhello 容器的镜像更改为 nongtengfei/hello:1.0.1
kubectl set image deployment/myapp-deployment myhello=nongtengfei/hello:1.0.1
# 根据文件修改镜像,--local表示不向apiserver发送请求,仅本地修改并输出yaml格式内容
kubectl set image -f myapp-deployment.yaml myhello=nongtengfei/hello:1.0.1 --local -o yaml
# 修改 deployment/myapp-deployment myhello 容器和myredis容器的镜像
kubectl set image deployment/myapp-deployment myhello=nongtengfei/hello:1.0.1 myredis=redis:alpine
# 修改ds/myapp-ds myhello 容器镜像
kubectl set image ds/myapp-ds myhello=nongtengfei/hello:1.0.2
3.6.3、resources
kubectl set resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --requests=REQUESTS]
# 设置单个容器的资源
kubectl set resources deployment myapp-deployment -c=myhello --limits=cpu=200m,memory=512Mi
# 设置myapp-deployment部署下所有容器资源
kubectl set resources deployment myapp-deployment --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
# 移除资源限制,设置为0即不限制
kubectl set resources deployment myapp-deployment --limits=cpu=0,memory=0 --requests=cpu=0,memory=0
# 根据文件设置资源,打印出结果,且不向apiserver发送请求
kubectl set resources -f myapp-deployment.yaml --limits=cpu=200m,memory=512Mi --local -o yaml
3.6.4、selector
kubectl set selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resourceversion=version]
# 将service myhello-svc 的label selector 修改为 env=proc
kubectl set selector svc myapp-svc env=proc
kubectl set selector svc myapp-svc name=myapp-deploy-pod
# 查看service 对象明细
kubectl describe svc myapp-svc
3.7、explain(重点)
kubectl explain RESOURCE
# 获取资源及其字段的文档
kubectl explain pods
# 获取资源特定字段的文档
kubectl explain pods.spec.containers
3.8、get
kubectl get [(-o|--output=)json|yaml|name|go-template|go-templatefile|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file|customcolumns|custom-columns-file|wide] (TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags]
# 获取默认命名空间下所有Pod
kubectl get pods
# 获取更多Pod信息
kubectl get pods -o wide
# 获取副本控制器 myhello-rc
kubectl get replicationcontroller myhello-rc
# 获取处于apps.v1 api组下所有 deployment,并以json格式答应
kubectl get deployments.v1.apps -o json
# 获取单个Pod,以json格式数据
kubectl get -o json pod myhello-rc-278jg
# 根据文件获取对象
kubectl get -f myapp-deployment.yaml -o json
# 返回对象指定的值
kubectl get -o template deployment/myapp-deployment --template={{.status.readyReplicas}}
# 自定义返回字段,分别指定了列名为:CONTAINER 和 IMAGE
kubectl get pod -o customcolumns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
# 获取 所有rc 和 service
kubectl get rc,services
# 获取一个或多个资源
kubectl get rc/myhello-rc service/myhello-svc deployment/myapp-deployment
3.9、edit
kubectl edit (RESOURCE/NAME | -f FILENAME)
# 修改myhello-svc service
kubectl edit svc/myhello-svc
# 以打开为json文件的方式修改
kubectl edit svc/myhello-svc -o json
# 修改资源配置,并将修改后的内容添加到注解
kubectl edit deployment/myapp-deployment -o yaml --save-config
3.10、delete
# 通过定义文件删除资源
kubectl delete -f myhello-rc.yaml
# 指定所有后缀名为yaml的文件,删除这些文件定义的资源
kubectl delete -f '*.yaml'
# 以文件内容为参数,删除资源
cat myhello-rc.yaml | kubectl delete -f -
# 删除名称为 myhello-pod 或 myhello-svc 的pod 和 service
kubectl delete pod,service myhello-pod myhello-svc
# 删除标签为 myhello-pod的pod和service
kubectl delete pods,services -l name=myhello-rc-pod
# 最小延迟删除Pod
kubectl delete pod <podname> --now
# 强制删除 Pod
kubectl delete pod <podname> --force
# 删除所有Pod
kubectl delete pods --all
3.11、label
kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
# 为pod/nginx添加标签
kubectl label pods nginx status=unhealthy
# 修改已存在的label
kubectl label --overwrite pods nginx status=healthy
# 为当前命名空间下所有pod添加标签
kubectl label pods --all status=unhealthy
# 根据资源定义文件添加标签
kubectl label -f myapp-deployment.yaml status=unhealthy
# 删除当前命名空间下所有Pod的status标签
kubectl label pods --all status-
# 删除指定label
kubectl label pods nginx status-
# 根据资源定义文件删除资源标签
kubectl label -f myapp-deployment.yaml status-
# 为节点添加标签
kubectl label node k8s-master1 nodetype=master
kubectl label node k8s-node1 nodetype=worker
kubectl label node k8s-node2 nodetype=worker
kubectl label nodes k8s-node2 nodetype-
# 为pod指定部署的节点
nodeSelector:
nodetype: worker
3.12、annotate
kubectl annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
# 为资源类型为 rc 的 myhello-rc 添加注解 description='my hello rc'
kubectl annotate rc myhello-rc description='my hello rc'
# 为文件myhello-rc.yaml所定义的资源 添加注解 description1='my hello rc1'
kubectl annotate -f myhello-rc.yaml description1='my hello rc1'
# 重写 myhello-rc 的description 注解
kubectl annotate --overwrite rc myhello-rc description='this a replication
controller'
# 为当前命名空间下所有pod 添加注解
kubectl annotate pods --all description='myhello running golang program'
# 更新指定resourceVersion 的单一资源对象
kubectl annotate rc myhello-rc description3='my hello rc3' --resourceversion=10564
# 删除注解
kubectl annotate pods --all description
期待哪些云原生技术内容呢?
云原生不仅涵盖核心概念,更注重实战演练,通过丰富的代码示例、案例分析和动手实验,快速掌握云原生技能,并能够将其应用到实际项目中。
本文总结
小结
通常不会去单独的配置pod,都是通过某一类副本控制器资源去部署pod。原因:如果单独配置pod,当集群升级时需要将当前节点上的所有pod排空,那么会产生问题,因为pod没有任何副本控制器在控制它,集群对他没有预期,当节点排空后,pod将不会被调度和重生。
在线问&答
问
云原生如何学习?
云原生技术正在改变着软件开发和部署的方式。《云原生》集合和《云原生系列》专栏将深入浅出地讲解docker容器、Kubernetes、微服务、DevOps 等核心概念,并分享实践经验,助您快速掌握云原生开发和运维技能。
答
问
Linux 后端开发要掌握哪些内容?
《后端高级开发》合集专注于Linux环境下的C/C++后端开发技术,该集合涵盖并发编程、C/C++、Linux、网络协议、中间件、云原生、数据库、分布式架构等开发技术。
答
往期文章推荐
Lion 莱恩呀
微信号:关注获取
扫码关注查看更多内容
点击下方👇在看,传递技术知识