kubectl -A用于获取所有命名空间中的资源对象,kubectl -o wide用于以更宽的格式输出资源对象的详细信息。
资源类型与别名:
- pod ->
po - deployments ->
deploy - services ->
svc - namespace ->
ns - nodes ->
no
Document:kubernetes.io/zh-cn/docs/…
1.Component
1.1 Master
-
apiserver所有服务访问的唯一入口,提供认证、授权、访问控制、API 注册和发现等机制
-
controller manager负责维护集群的状态,比如副本期望数量、故障检测、自动扩展、滚动更新等
-
scheduler负责资源的调度,按照预定的调度策略将 Pod 调度到相应的机器上
-
etcd键值对数据库,保存了整个集群的状态
1.2 Node
-
kubelet负责维护容器的生命周期,同时也负责 Volume 和网络的管理
-
kube-proxy负责为 Service 提供 cluster 内部的服务发现和负载均衡
1.3 Other
- Pod: kubernetes的最小控制单元,容器都是运行在pod中的,一个pod中可以有1个或者多个容器
- Controller: 控制器,通过它来实现对pod的管理,比如启动pod、停止pod、伸缩pod的数量等等
- Service: pod对外服务的统一入口,下面可以维护者同一类的多个pod
- Label: 标签,用于对pod进行分类,同一类pod会拥有相同的标签
- NameSpace: 命名空间,用来隔离pod的运行环境
2.Controller
在kubernetes中,有很多类型的pod控制器,每种都有自己的适合的场景,常见如下:
-
ReplicationController:比较原始的pod控制器,已经被废弃,由ReplicaSet替代
-
ReplicaSet:保证副本数量一直维持在期望值,并支持pod数量扩缩容,镜像版本升级
-
Deployment:通过控制ReplicaSet来控制Pod,并支持滚动升级、回退版本
-
Horizontal Pod Autoscaler:可以根据集群负载自动水平调整Pod的数量,实现削峰填谷
-
DaemonSet:在集群中的指定Node上运行且仅运行一个副本,一般用于守护进程类的任务
-
Job:它创建出来的pod只要完成任务就立即退出,不需要重启或重建,用于执行一次性任务
-
Cronjob:它创建的Pod负责周期性任务控制,不需要持续后台运行
-
StatefulSet:管理有状态应用
2.1 ReplicationController
简写就是RC,帮助我们动态更新pod
弃用状态
2.2 ReplicaSet
它是RC的升级,简写就是RS
通过selector帮我们动态扩容
弃用状态
-
創建ReplicaSet
kubectl create -f replicaSet.yaml -
查看ReplicaSet狀態
kubectl get rs replicaSet -n default -o wide -
修改屬性
kubectl edit rs replicaSet -n defaultkubectl scale re replicaSet --replicas=2 -n default
2.3 Deployment
簡寫为deploy,对RS进行升级
参考下图
2.3.1 Query
-
直接創建
kubectl get deploymentkubectl get deployment -n demoNameSpace
2.3.2 Create Pod
-
直接創建
kubectl create deployment web --image=nginx:1.14#不好複用 -
文件創建
kubectl create deployment web --image=nginx:1.14 -o yaml > web.yamlkubectl apply -f web.yaml -
查看
kubectl get deploy,po -o wide
2.3.3 Replicas
-
擴容
kubectl scale deploy web --replicas=10 -
Scale a replicaset named 'foo' to 3
kubectl scale --replicas=3 rs/foo -
Scale a resource specified in "foo.yaml" to 3
kubectl scale --replicas=3 -f foo.yaml -
If the deployment named mysql's current size is 2, scale mysql to 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql -
Scale multiple replication controllers
kubectl scale --replicas=5 rc/foo rc/bar rc/baz
2.3.4 Rollout
-
查看狀態和歷史記錄
kubectl rollout status deploy webkubectl rollout history deployment web -
回滾
kubectl rollout undo deploy webkubectl rollout undo deploy web --to-revision=2 -
滾動更新
-
滚动更新 pod frontend-v1
kubectl rolling-update frontend-v1 -f frontend-v2.json -
更新资源名称并更新镜像
kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 -
更新 frontend pod 中的镜像
kubectl rolling-update frontend --image=image:v2
-
2.3.5 Delete
-
删除
kubectl delete deploy web -n default
2.4 StatefulSet
缩写就是sts,特点:
- 稳定的额持久化存储
- 稳定的网络标志
- 有序部署,有序扩展
- 有序收缩,有序删除
Headless Servcie && VolumeClaimTemplate
2.4.1 Create
-
删除
kubectl create -f xxx.yaml
2.4.2 Query
-
查询
kubectl get statefulSet xxxx -
扩容
kubectl scale statefulSet xxxx --replicas=5
2.5 DaemonSet
守护进程就是在匹配到的Node上,创建一个守护进程
经典的应用场景:
- 日志收集
- 系统监控
- 系统程序
快速,自动在匹配到的容器上运行,如下图
2.5.1 Create
-
创建
kubectl create -f xxxx.yaml
2.5.2 Query
-
查询
kubectl get statefulSet xxxx -
扩容
2.6 Job
2.6.1 CronJob
apiVersion: batch/v1
kind: CronJob
metadata:
name: hello
spec:
schedule: "* * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox:1.28
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
2.6.2 Introduction
并发性规则
.spec.concurrencyPolicy 也是可选的。
Allow(默认):CronJob 允许并发任务执行。Forbid: CronJob 不允许并发任务执行;如果新任务的执行时间到了而老任务没有执行完,CronJob 会忽略新任务的执行。Replace:如果新任务的执行时间到了而老任务没有执行完,CronJob 会用新任务替换当前正在运行的任务。
2.7 HPA
-
设定
kubectl autoscale deploy nginx --cpu-percent=20 --min=2 --max=5
3. Service
东西流量service和南北流量ingress
K8s架构图
Service有三种类型:
- ClusterIp:通過集群内部IP,公開Service访问(默认)
- NodePort:通過節點IP和靜態端口公開Service,集群外部访问(包含了ClusterIp)
- LoadBalancer:使用雲平台的負載均衡向外部公開Servcie,Kuburnetes不直接提供負載均衡組件,公有云
- ExternaName: 将 Service 映射到 DNS 名称
3.1 Create
-
直接創建
kubectl expose deployment web --port=8080 --target-port=80 --type=NodePort- expose:指定这是要暴露一个deployment,后面的web是将要暴露服务的名字
- --port:指定集群内部访问的端口
- --target-port:指定容器本身端口,比如nginx是80,所以这里指定80
- --type:表明这是NodePort类型,可以被集群外部访问
-
文件創建
kubectl expose deployment web --port=8080 --target-port=80 --type=NodePort -o yaml > service.yamlkubectl apply -f service.yaml
apiVersion: v1
kind: Service
metadata:
name: demo_k8s
spec:
selector:
app: test-k8s
type: ClusterIP # 默认
ports:
- port: 8080 # 本 Service 的端口
targetPort: 8080 # 容器端口
3.2 Query
-
查詢service
kubectl get service/svc -o wide
3.3 Delete
-
删除service
kubectl delete service/svc xxxx
3.4 工作原理
service和endpoint的关系:创建service的时候,会创建一个同名的endpoint,通过targetport找到对应pod的port进行访问.访问32057,就是访问nginx的80port.
如果创建的时候不指定selector,则不会创建endpoint
3.5 servcie指向外部服务
- 创建service的时候不指定selectorl
- 手动创建endpoint(ep)
- 将endpoint和service关联
3.6 外部域名代理
type直接就是ExternalName,下面就是代理的域名
3.7 Ingress
-
创建ingress
kubectl create -f xxxx.yaml
4. Pod
Pod縮寫就是po,里面可以有多个容器,是一个容器组的概念
资源分类:
- 无状态应用:不会对本地环境产生任何影响,例如不会存储数据到本地磁盘(Nginx,Apache)
- 有状态应用:会对本地环境产生影响,例如会将数据存储到本地磁盘(Mysql)
为什么需要pod,有需求才有设计
4.1 Query
-
简单查询,查询名字
kubectl get pods/po -Akubectl get pods -o widekubectl get pods -n demoNamespacekubectl get pods --all-namespace -
详细查询
kubectl describe pods podName -n demoNameSpace
4.2 Create
-
使用deploy创建
kubectl create deploy nginx-demo --image=nginx:1.7.9 -
使用文件创建
kubectl apply -f pod01.yaml
apiVersion: apps/v1
kind: Deployment # 表示类型为Deployment
metadata:
name: demo_k8s
spec:
replicas: 5
selector:
matchLabels:
app: demo_k8s
template:
metadata:
labels:
app: demo_k8s
spec:
containers:
- name: demo_k8s
image: ccr.ccs.tencentyun.com/k8s-tutorial/test-k8s:v1
4.3 Delete
-
基于 xxx.yaml 文件删除 Pod 对象
kubectl delete -f xxx.yaml -
删除包括某个 label 的 pod 对象
kubectl delete pods -l name=<label-name> -
删除用deployment创建的pod
kubectl delete deploy xxxx
4.4 進入容器
kubectl exec -it mypod -c containerName -it -- bash
4.5 生命周期
1.preStop
在yaml文件的containers中配置钩子函数
apiVersion: v1
kind: Pod
metadata:
name: lifecycle-demo
spec:
containers:
- name: lifecycle-demo-container
image: nginx
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
preStop:
exec:
command: ["/bin/sh","-c","nginx -s quit; while killall -0 nginx; do sleep 1; done"]
2.InitContainer
在pod.yaml中添加到template/spec下面
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
labels:
app: myapp
spec:
replicas: 1
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: alpine:latest
command: ['sh', '-c', 'echo "logging" > /opt/logs.txt']
volumeMounts:
- name: data
mountPath: /opt
initContainers:
- name: logshipper
image: alpine:latest
restartPolicy: Always
command: ['sh', '-c', 'tail /opt/logs.txt']
volumeMounts:
- name: data
mountPath: /opt
volumes:
- name: data
emptyDir: {}
5. Namespace
5.1 Query
-
查看所有名称空间
kubectl get ns -
查看指定名称空间下的deployment
kubectl get deploy nginx -n default -o yaml
5.2 Create
-
创建名称空间
kubectl create namespace demo001kubectl create -f demo001.yaml
#创建一个新的namespace
apiVersion: v1
kind: Namespace
metadata:
name: demo001
5.3 output
-
查看指定名称空间下的deployment
kubectl get deploy -n default -o yaml
6. Log && Describe
-
查看pod日誌
kubectl logs mypod -n test -
pod裡面多個容器
kubectl describe pod mypodkubectl logs -f mypod -c containerName
7. Label && Taint
7.1 Label
-
添加標籤
kubectl label node my-master test123_env=prod -
查询po標籤
kubectl get po --show-labels -n namespace -
删掉标签
kubectl label node my-master test123_env-
7.2 Taint
一般情況下,pod不會安裝到master節點,如果有需要,就要配置污點或容忍
污点相当于标签,冒号后面表示影响
7.2.1 Introduction
Effect两个影响:
-
NoExecute这会影响已在节点上运行的 Pod,具体影响如下:
- 如果 Pod 不能容忍这类污点,会马上被驱逐。
- 如果 Pod 能够容忍这类污点,但是在容忍度定义中没有指定
tolerationSeconds, 则 Pod 还会一直在这个节点上运行。 - 如果 Pod 能够容忍这类污点,而且指定了
tolerationSeconds, 则 Pod 还能在这个节点上继续运行这个指定的时间长度。 这段时间过去后,节点生命周期控制器从节点驱除这些 Pod。
-
NoSchedule除非具有匹配的容忍度规约,否则新的 Pod 不会被调度到带有污点的节点上。 当前正在节点上运行的 Pod 不会被驱逐。
-
PreferNoSchedulePreferNoSchedule是“偏好”或“软性”的NoSchedule。 控制平面将尝试避免将不能容忍污点的 Pod 调度到的节点上,但不能保证完全避免。
容忍:
operator 的默认值是 Equal。
- 如果
operator是Exists(此时容忍度不能指定value),或者 - 如果
operator是Equal,则它们的value应该相等。
7.2.2 Taint Command
-
查詢節點污點
kubectl describe node my-master | grep Taints -
添加污點
kubectl taint node my-master node-role.kubernetes.io/master:NoSchedule -
删掉污點
kubectl taint node my-master node-role.kubernetes.io/master:NoSchedule-
7.2.3 Tolerations Config
和template/spec下的containers同级
tolerations:
- key: "key1"
operator: "Equal"
value: "value1"
effect: "NoSchedule"
- key: "key1"
operator: "Equal"
value: "value1"
effect: "NoExecute"
7.3 亲和性
这个配置就是和node身上的label去匹配
-
查询标签
kubectl get nodes --show-labels -
添加标签
kubectl label nodes <your-node-name> disktype=ssd -
在pod.yaml中添加亲和性配置
apiVersion: v1 kind: Pod metadata: name: nginx spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: disktype operator: In values: - ssd containers: - name: nginx image: nginx imagePullPolicy: IfNotPresent
8. Persistence
关系图如下:
8.1 PV
PV:PersistentVolume
apiVersion: v1
kind: PersistentVolume
metadata:
name: mongodata
spec:
capacity:
storage: 2Gi
volumeMode: Filesystem
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Delete
storageClassName: local-storage
local:
path: /root/data
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- node2
-
创建PV
kubectl create -f xxx.yaml -
删掉PV
kubectl get pvkubectl delete pv xxx
8.2 PVC
PVC:PersistentVolumeClaim
accessModes和storageClassName要完全匹配,才能找打PV
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mongodata
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: "local-storage"
resources:
requests:
storage: 2Gi
-
创建PVC
kubectl create -f xxx.yaml -
删掉PVC
kubectl get pvc xxxxxkubectl delete pvc xxx
8.3 Pod
apiVersion: v1
kind: Pod
metadata:
name: task-pv-pod
spec:
volumes:
- name: task-pv-storage
persistentVolumeClaim:
claimName: mongodata
containers:
- name: task-pv-container
image: nginx
ports:
- containerPort: 80
name: "http-server"
volumeMounts:
- mountPath: "/usr/share/nginx/html"
name: task-pv-storage #指向上面的volume
-
创建PO
kubectl create -f xxx.yaml -
删掉PO
kubectl get pokubectl delete po xxx
8.4 StorageClass
动态创建PV,更灵活
9. Config
9.1 ComfigMap
缩写就是cm
-
查看帮助
kubectl create cm -h -
查看cm
kubectl describe cm xxxx -
在pod.yaml中使用cm
apiVersion: v1 kind: Pod metadata: name: test-pod spec: containers: - name: test-container image: registry.k8s.io/busybox command: [ "/bin/sh", "-c", "env" ] env: # 定义环境变量 - name: SPECIAL_LEVEL_KEY valueFrom: configMapKeyRef: name: special-config-map #ConfigMap Name key: username restartPolicy: Never