一、Kubernetes是什么?
容器化应用的编排平台,以应用为中心的现代化容器编排平台;
声明式API,控制器模式
声明期望的结果状态
控制器负责实现用户期望
spec 规约
status 状态
1、架构组件及应用关系
主机类别:
Master主机
Node主机
运行Pod
容器和卷
系统组件:
Master:
API Server
Etcd
Controller Manager
Schduler
Node:
Kubelet
CRI 容器运行时接口,Docker-CE/cri-dockerd,Containerd.CRI-O
CSI 存储接口,Rook,OpenEBS
CNI 网络接口,Flannel,Calico,Cilium,WeaveNet
Pod --> Server Pod
Service:
服务发现:标签选择权 --> Pod Label
负载均衡:
Client Pod --> ServiceIP:ServicePort --> PodIP:PodPort
Client Pod --> ServiceName:ServicePort --> ServiceIP:ServicePort --> PodIP:PodPort
Kube Proxy
节点内核的netfilter框架的Hook生成规则
iptables/ipvs
AddOns:
KubeDNS:
SkyDNS --> KubeDNS --> CoreDNS
Metrics Server 资源使用情况的监控可以通过 Metrics API的形式获取,例如容器CPU和内存使用率
Ingress Controller
Ingress Nginx、Traefik、Contour、Kong、APISIX Ingress Controller
Prometheus
EFK/PLG
Distributed Tracing: Zipkin,Jaeger,Skywalking
UI:Dashboard,Kuboard
Platform for Platfrom
2、应用编排
应用编排逻辑:
把任何迁移到Kubernetes上运行:
编排和运行应用的原子单元是Pod,Pod是容器集
Image --> Registry
服务类应用:
选择一个工作负载型控制器:编排运行Pod化的应用
给这句应用创造一个Service
应用的编排:
部署、扩容/缩容、更新、卸载
工作负载型控制器:
Deployment:编排无状态应用
ReplicaSet
StatefulSet:编排有状态应用,Operator
DaemonSet:编排系统级应用
Job:一次性作业
CronJob:周期性作业
服务类应用:
对于每个独立编排的应用,还应该提供一个Service
客户端工具:
kubectl --> API Server
API Server: https (双向认证)
RESTful API
资源类型:API Server
Pod,Sevice,Deployment
按功能等标准,被划分到多个组中,成为API群组:
kubectl api-versions
每个组,可独立演进
Group_Name/Version
版本存在三个级别:
alpha 内测
beta 公测
stable 稳定
vLevelRelease_num
v1alpha1 --> v1apha2
v1beta --> v1beta2
列出资源类型:
kubectl api-resources
按组查看: --api-group=''
资源类型的实例化的结果,称对象Object
实例数据编码格式:JSON
用户可使用的形式:JSON,YAML
yaml --> json
资源的作用域
集群级别
名称空间级别
资源管理CRUD: HTTP Method
Create
Update
Read
Delete
管理风格:
指令式命令
create,delete,eidt,get
指令式对象配置
create -f file
delete
get
edit
声明式对象配置
apply -f file
增和改
删除和查询:
delete
get
1.列出API群组
root@u-k8s-master-171:~# 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
batch/v1
certificates.k8s.io/v1
coordination.k8s.io/v1
discovery.k8s.io/v1
events.k8s.io/v1
flowcontrol.apiserver.k8s.io/v1beta2
flowcontrol.apiserver.k8s.io/v1beta3
network.kubesphere.io/v1alpha1
network.kubesphere.io/v1alpha2
networking.k8s.io/v1
node.k8s.io/v1
policy/v1
rbac.authorization.k8s.io/v1
scheduling.k8s.io/v1
storage.k8s.io/v1
v1
2.列出资源类型
#NAMESPACED
#true/false 是否属于命名空间
root@u-k8s-master-171:~# 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
selfsubjectreviews authentication.k8s.io/v1 false SelfSubjectReview
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/v1beta3 false FlowSchema
prioritylevelconfigurations flowcontrol.apiserver.k8s.io/v1beta3 false PriorityLevelConfiguration
bgpconfs network.kubesphere.io/v1alpha2 false BgpConf
bgppeers network.kubesphere.io/v1alpha2 false BgpPeer
eips network.kubesphere.io/v1alpha2 false Eip
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
3.指令式命令
root@u-k8s-master-171:~# kubectl create deployment demoapp --image=nginx:laste --replicas=3 --dry-run=client -o json
4.指令式对象配置
root@u-k8s-master-171:~# kubectl create deployment demoapp --image=nginx --replicas=3 --dry-run=client -o json > deployment-demoapp.yaml
root@u-k8s-master-171:~# kubectl create -f deployment-demoapp.yaml
deployment.apps/demoapp created
root@u-k8s-master-171:~# kubectl get pods
NAME READY STATUS RESTARTS AGE
demoapp-6749fcd559-4hcn7 0/1 ContainerCreating 0 6s
demoapp-6749fcd559-9nl59 0/1 ContainerCreating 0 6s
demoapp-6749fcd559-xhvvl 0/1 ContainerCreating 0 6s
root@u-k8s-master-171:~# kubectl get pods
NAME READY STATUS RESTARTS AGE
demoapp-6749fcd559-4hcn7 1/1 Running 0 4m47s
demoapp-6749fcd559-9nl59 1/1 Running 0 4m47s
demoapp-6749fcd559-xhvvl 1/1 Running 0 4m47s
root@u-k8s-master-171:~# kubectl delete -f deployment-demoapp.yaml
2deployment.apps "demoapp" deleted34
root@u-k8s-master-171:~# kubectl get pods
5No resources found in default namespace.
5.声明式对象配置
root@u-k8s-master-171:~# kubectl apply -f deployment-demoapp.yaml
deployment.apps/demoapp created
root@u-k8s-master-171:~# kubectl get pods
NAME READY STATUS RESTARTS AGE
demoapp-6749fcd559-6jk85 0/1 ContainerCreating 0 11s
demoapp-6749fcd559-nf92p 0/1 ContainerCreating 0 11s
demoapp-6749fcd559-wf2mq 0/1 ContainerCreating 0 11s
3、资源类型
API资源类型Deployment,Controller Manager中存在一个同名的Deployment控制器
给资源类型中的字段赋值的过程,就称为资源的实例化,称为Object
大部分资源类型的一级字段相同
apiVersion:群组级版本号
最后的 v1 是核心组
kind:资源类型标识
metadata:对象元数据
name:对象名称,在同一类型下,标识符不能相同
namespace:隶属的名称空间
labels:标签集
key1:value1
key2:value2
...
annotations:注解信息
key1:value1
key2:value2
...
spec:定义对该对象的期望状态
status:有对应的控制器负责填写的字段,保存的是对象的实际状态
准入控制器:Adminssion Controller
Validating 校验
Mutating 修订/补全
1.创造资源的流程
1、选择合适的工作负载型控制器、资源类型、编排运行Pod
2、创造Service
2.资源的类型
Namespace:
资源类型
集群级别,用于提供namespace,支持那些namespace level的资源类型
root@u-k8s-master-171:~# kubectl get namespaces
NAME STATUS AGE
default Active 4d6h
kube-flannel Active 4d6h
kube-node-lease Active 4d6h
kube-public Active 4d6h
kube-system Active 4d6h
openelb-system Active 4d4h
Kubernetes的名称空间可以划分为两种类型
系统级名称攻坚:由Kubernetes集群默认创建,主要用来隔离系统的资源对象
自定义名称空间:由用户按需创建
系统级名称空间
default:默认的名称空间,为任何名称空间级别的资源提供的默认设定
kube-system:Kubernetes集群自身组件及其它的系统级组件使用的名称空间,Kubernetes自身的关键组件均部署在该名称空间中
kube-public: 公众开放的名称空间,所有用户(包括Anonymous)都可以读取内部的资源
kube-node-lease:节点租约资源所用的名称空间
环境管理
隔离
资源控制
权限控制
提高集群性能
Pod的组成形式
单容器Pod:仅含有单个容器
多容器Pod:含有多个具有“超亲密关系的容器
3.定义一个Pod
一个极简的Pod定义,仅需要为其指定一个要运行的容器即可
apiVersion:v1
kind:Pod
metadata:
name:... Pod的标识名,在名称空间中必须唯一
namespace:... 该Pod所属的名称空间,省略时使用默认名称空间default;
spec:
containers: 定义容器,它是一个列表对象,可包括多个容器的定义,至少得有一个
- name:... 容器名称,必选字段,在当前Pod中必须唯一
image:... 创造容器时使用的镜像
pause容器无需定义
apiVersion:v1
kind:Pod
metadata:
name:...
namespace:...
spec:
containers:
- name:...
image:...
root@u-k8s-master-171:~# cat mynginx.yaml
apiVersion: v1
kind: Pod
metadata:
name: mynginx
namespace: default
labels:
app: mynginx
version: v1.0
spec:
containers:
- name: mynginx
image: nginx
root@u-k8s-master-171:~# kubectl apply -f mynginx.yaml
pod/mynginx created
root@u-k8s-master-171:~# kubectl get pods
NAME READY STATUS RESTARTS AGE
demoapp-6749fcd559-7z2xs 1/1 Running 2 (61m ago) 2d6h
demoapp-6749fcd559-kzm48 1/1 Running 2 (61m ago) 2d6h
demoapp-6749fcd559-m2r4j 1/1 Running 2 (61m ago) 2d6h
mynginx 0/1 ContainerCreating 0 9s
root@u-k8s-master-171:~# kubectl get pods
NAME READY STATUS RESTARTS AGE
demoapp-6749fcd559-7z2xs 1/1 Running 2 (63m ago) 2d6h
demoapp-6749fcd559-kzm48 1/1 Running 2 (63m ago) 2d6h
demoapp-6749fcd559-m2r4j 1/1 Running 2 (63m ago) 2d6h
mynginx 1/1 Running 0 2m18s
root@u-k8s-master-171:~# kubectl get pods mynginx -o yaml
apiVersion: v1
kind: Pod
metadata:
annotations:
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"labels":{"app":"mynginx","version":"v1.0"},"name":"mynginx","namespace":"default"},"spec":{"containers":[{"image":"nginx","name":"mynginx"}]}}
creationTimestamp: "2024-03-06T13:29:52Z"
labels:
app: mynginx
version: v1.0
name: mynginx
namespace: default
resourceVersion: "154452"
uid: 7400d16b-77a6-45e3-8706-b2af36046aa3
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: mynginx
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: kube-api-access-g89sd
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: u-k8s-node2-173
preemptionPolicy: PreemptLowerPriority
priority: 0
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
tolerations:
- effect: NoExecute
key: node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds: 300
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds: 300
volumes:
- name: kube-api-access-g89sd
projected:
defaultMode: 420
sources:
- serviceAccountToken:
expirationSeconds: 3607
path: token
- configMap:
items:
- key: ca.crt
path: ca.crt
name: kube-root-ca.crt
- downwardAPI:
items:
- fieldRef:
apiVersion: v1
fieldPath: metadata.namespace
path: namespace
status:
conditions:
- lastProbeTime: null
lastTransitionTime: "2024-03-06T13:29:52Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2024-03-06T13:30:19Z"
status: "True"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2024-03-06T13:30:19Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2024-03-06T13:29:52Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: containerd://be84fcb1c9a68c55a7830c4735739794fbf4200336737e516f9a54bb35d828d7
image: docker.io/library/nginx:latest
imageID: docker.io/library/nginx@sha256:c26ae7472d624ba1fafd296e73cecc4f93f853088e6a9c13c0d52f6ca5865107
lastState: {}
name: mynginx
ready: true
restartCount: 0
started: true
state:
running:
startedAt: "2024-03-06T13:30:18Z"
hostIP: 172.29.7.173
phase: Running
podIP: 10.244.2.14
podIPs:
- ip: 10.244.2.14
qosClass: BestEffort
startTime: "2024-03-06T13:29:52Z"
4.Pod管理
资源查看:
kubectl get TYPE
列出指定类型下的所有资源对象
kubectl get TYPE NAME ...
指定资源对象
kubectl get TYPE1/NAME1 TYPE2/NAME2 ...
kubectl get all
列出所有类型下的所有资源对象
常用选项:
-n, --namespace
显示格式:
-o, json|yaml|name|wide|jsonpath|customed-columes
资源详情描述:
kubectl describe TYPE NAME
root@u-k8s-master-171:~# kubectl describe pods mynginx
删除资源对象:
kubectl delete TYPE NAME
kubectl delete TYPE1/NAME1 TYPE2/NAME2...
kubectl delete -f /PATH/T0/manifest
-f --force 强制删除
--grace-period=0 宽限期,等待多少时间
Pod的phase和重启策略
Pod的相位:
Pending -> Running -> Succeeded/Failed
Unknown
作业类应用会出现Succeded、Failed
服务类应用一般保持在Running
容器的状态:
Waiting -> Running -> Terminated -重启策略决定下一步-> Waiting/" " Unknown
重启策略:
Always:无论何种exit code,都重启容器
OnFailure:仅在错误退出时重启容器
Never:无论什么,都不重启容器
镜像下载策略:
Always:无论节点上有没有镜像都下载
IfNotPresent:如果没有镜像就去下载,标签是laste也会下载
Never:从不下载
配置容器化应用:
将配置文件放置在卷上
ConfigMap, Secret
把配置文件焙进Image
环境变量
ENTRYPOINT entrypoint.sh
指定要运行的命令,及其传递的参数
容器调试命令
kubectl exec
kubectl exec (POD|TYPE/NAME) [-c CONTAINER] [flages] -- COMMAND [args..] [options]
kubectl exec mynginx -- ifconfig
kubectl exec -it mynginx -- /bin/sh
kubectl log
kubectl logs [-f] [-p] (POD|TYPE/NAME) [-c CONTAINER] [options]
kubectl logs mynginx
kubectl logs -f mynginx
kubectl logs tail 5 mynginx
容器的环境变量:
...
spec:
containers:
- name: mynginx
image: nginx
env:
- name: he
value: hello
...
root@u-k8s-master-171:~# kubectl exec mynginx -- printenv
容器端口映射:
ports:
- name:
containerPort: 容器端口
hostPort: 主机端口
Pod要运行的命令,及其传递的参数:
command: ["/bin/sh", "-c"]
#-c :command 后面跟一个字符串,这个字符串可以是我们平常执行的任何命令,有参数选项时一定要用引号括起来
args: ["python3", "/etc/pyapp.py"]
5.配置Pod
apiVersion: v1
kind: Pod
metadata:
name: mynginx
namespace: default
labels:
app: mynginx
version: v1.0
spec:
containers:
- name: mynginx
image: nginx
imagePullPolicy: IfNotPresent #镜像下载策略
env:
- name: PORT #环境变量
value: "9909"
- name: Hello #环境变量
value: Hello-$(PORT)
command: ["/bin/sh", "-c"] #运行命令
args: ["python3", "/etc/pyapp.py"] #运行命令
restartPolicy: OnFailure #Pod重启策略,Pod级别配置
6.Pod查看日志
kubectl logs
root@u-k8s-master-171:~# kubectl logs -f mynginx
root@u-k8s-master-171:~# kubectl logs --tail 2 mynginx
2024/03/09 06:16:48 [notice] 1#1: start worker process 29
2024/03/09 06:16:48 [notice] 1#1: start worker process 30
4、探针
容器式运行的应用类似于“黑盒”,为了便于平台对其进行检测,云原生应用应该输出用于监视自身API
包括健康状态、指标、分布式跟踪和日志等
至少应该提供用于健康状态检测的API
startupProbe 启动检查
livenessProbe 存活检查
readinessProbe 就绪检查
下探针:
startupprobe:用于判断容器内应用程序是否已经启动,如果配置了startuprobe,就会先禁用其他的探测,直到它成功为止,成功后将不再进行探测,由LivenessProbe接管。
ReadinessProbe: 一般用于探测容器内的程序是否健康,它的返回值如果为success,那么就代表这个容器已经完成启动,并且程序已经是可以接受流量的状态
有些应用的启动时间很长,之前的流量就会消费失败
LivenessProbe:用于探测容器是否运行,如果探测失败,kubelet会根据配置的重启策略进行相应的处理,如果没有配置该探针,默认就是success
存活探测,主要是通过自定义的存活条件,例如,s s s 三次存活为存活
探针的探测逻辑,由用户定义
监测机制:
Exer Action:根据指定命令的结果状态码判定
TcpSocket Action:根据相应TCP套接字连接建立状态判定
HTPPGet Action:根据指定https/http服务URL的响应结果判定
配置参数:
initiaIDelaySeconds:容器启动后要等待多少秒后存活和就绪探测器才被初始化
periodSeconds:执行探测的时间间隔(单位是秒)
timeoutSeconds:探测的超时后等待多少秒
successThreshold:探测器在失败后,被视为成功的最小连续成功数。
failureThreshold:当探测失败时,Kubernetes 的重试次数。
5、Security Context
1.Pod及容器的安全上下文
一组用来决定容器是如何创建和运行的约束条件,这些条件代表创建和运行容器时使用的运行时参数
给了用户为Pod或容器定义特权和控制访问机制
2.Pod和容器的安全上下文设置主要包括以下几个方面
自主访问控制DAC
容器进程运行身份及资源访问权限
Linux Capabiliters
seccomp
AppArmor
SELinux
Privileged Mode
Privilege Escalation
3.Kubernetes支持在Pod及容器级别分别使用安全上下文
支持两个级别:
Pod级别:对当前Pod中所有容器都生效
Container级别:仅对当前容器生效
4.securityContext参数
pods.spec.securityContext:
以指定的身份运行进程:
runAsGroup:以指定组运行
runAsUser:以指定用户运行
以非root的身份运行进程:
runAsNonRoot:是否不以管理员身份运行,默认false,双重否定,可以使用
设定指定的内核参数值:
sysctls
pods.spec.containers[*].securityContext
以指定的身份运行进程:
runAsGroup:以指定组运行
runAsUser:以指定用户运行
以非root的身份运行进程:
runAsNonRoot:是否不以管理员身份运行,默认false,双重否定,可以使用
设定Capability:
capabilities:
用户级别:
root
non root
Linux把内核中的管理权限,分成了多个类别,并给每个类别一个名字;这种类别称之为Capability;
https://man7.org/linux/man-pages/man7/capabilities.7.html
使用时去掉CAP前缀
是否运行为特权容器:
privilieged:
默认oot用户是无法获得最高权限,默认的root是一个受限的root。
是否设定根文件系统为只读:
readOnlyRootFilesystem: