Docker Swarm Mesos Google Kubernetes
2017年开始Kubernetes凭借强大的容器集群管理功能, 逐步占据市场,目前在容器编排领域一枝独秀
https://kubernetes.io/
如何设计一个容器管理平台?
分布式系统,两类角色:管理节点和工作节点
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
ETCD:分布式高性能键值数据库,存储整个集群的所有元数据
ApiServer: API服务器,集群资源访问控制入口,提供restAPI及安全访问控制
Scheduler:调度器,负责把业务容器调度到最合适的Node节点
Controller Manager:控制器管理,确保集群资源按照期望的方式运行
功能如下:
确保pod数量:它会确保Kubernetes中有指定数量的Pod在运行。如果少于指定数量的pod,Replication Controller会创建新的,反之则会删除掉多余的以保证Pod数量不变。
确保pod健康:当pod不健康,运行出错或者无法提供服务时,Replication Controller也会杀死不健康的pod,重新创建新的。
弹性伸缩 :在业务高峰或者低峰期的时候,可以通过Replication Controller动态的调整pod的数量来提高资源的利用率。同时,配置相应的监控功能(Hroizontal Pod Autoscaler),会定时自动从监控平台获取Replication Controller关联pod的整体资源使用情况,做到自动伸缩。
滚动升级:滚动升级为一种平滑的升级方式,通过逐步替换的策略,保证整体系统的稳定,在初始化升级的时候就可以及时发现和解决问题,避免问题不断扩大。
Node由master管理,node负责监控并汇报容器的状态,并根据master的要求管理容器的生命周期
定义每个命名空间(namespace)的资源配额,从而实现资源消耗总量的限制,以保证集群资源的有效利用以及稳定性
Namespace在很多情况下用于实现多租户的资源隔离,不同的业务可以使用不同的namespace进行隔离。
Service Account Controller在namespaces里管理ServiceAccount,并确保每个有效的namespaces中都存在一个名为“default”的ServiceAccount
Token controller检测service account的创建,并为它们创建secret
观察serviceAccount的删除,并删除所有相应的ServiceAccountToken Secret
观察secret 添加,并确保关联的ServiceAccount存在,并在需要时向secret 中添加一个Token。
观察secret 删除,并在需要时对应 ServiceAccount 的关联
Service Account 用来访问 kubernetes API
负责生成和维护所有Endpoints对象的控制器.它负责监听Service和对应的Pod副本的变化,如果检测到Service被删除,则删除和该Service同名的Endpoints对象。如果检测到新的Service被创建或者修改则根据该Service信息获得相关的Pod列表,然后创建或者更新Service对应的Endpoints对象。
kubelet:运行在每个节点上的主要的“节点代理”,脏活累活
kube-proxy:维护节点中的iptables或者ipvs规则
kubectl: 命令行接口,用于对 Kubernetes 集群运行命令 https://kubernetes.io/zh/docs/reference/kubectl/
除ETCD外
其他组件都是无状态的。因此从架构设计上对kubernetes系统高可用部署提供了支撑。kubeadm https://kubernetes.io/zh/docs/reference/setup-tools/kubeadm/kubeadm/
《Kubernetes安装手册(非高可用版)》
静态Pod的方式:
## etcd、apiserver、controller-manager、kube-scheduler
$ kubectl -n kube-system get po
systemd服务方式:
$ systemctl status kubelet
kubectl:二进制命令行工具
注:其他组件配置文件位置
[root@k8s-master week2]# ll /etc/kubernetes/manifests/
total 16
-rw------- 1 root root 2104 Jul 9 22:55 etcd.yaml
-rw------- 1 root root 3161 Jul 9 22:55 kube-apiserver.yaml
-rw------- 1 root root 2858 Jul 9 22:55 kube-controller-manager.yaml
-rw------- 1 root root 1413 Jul 9 22:55 kube-scheduler.yaml
可以通过删除pod,让他自动重建的方式重启,kube-proxy
[root@k8s-master week2]# kubectl -n kube-system get po |grep kube-proxy
kube-proxy-4qbsc 1/1 Running 0 15h
kube-proxy-hpkd4 1/1 Running 0 15h
kube-proxy-rk2fw 1/1 Running 0 15h
[root@k8s-master week2]# kubectl -n kube-system get po -owide|grep kube-proxy
kube-proxy-4qbsc 1/1 Running 0 15h 10.0.1.6 k8s-slave1 <none> <none>
kube-proxy-hpkd4 1/1 Running 0 15h 10.0.1.5 k8s-master <none> <none>
kube-proxy-rk2fw 1/1 Running 0 15h 10.0.1.8 k8s-slave2 <none> <none>
组件是为了支撑k8s平台的运行,安装好的软件。
资源是如何去使用k8s的能力的定义。比如,k8s可以使用Pod来管理业务应用,那么Pod就是k8s集群中的一类资源,集群中的所有资源可以提供如下方式查看:
# namespace 这一列下面为true的资源都需要指定namespace,不指定默认为default
$ kubectl api-resources
如何理解namespace:
命名空间,集群内一个虚拟的概念,类似于资源池的概念,一个池子里可以有各种资源类型,绝大多数的资源都必须属于某一个namespace。集群初始化安装好之后,会默认有如下几个namespace:
$ kubectl get namespaces
NAME STATUS AGE
default Active 84m
kube-node-lease Active 84m
kube-public Active 84m
kube-system Active 84m
kubernetes-dashboard Active 71m
# 注意与docker中资源 namespace区分,k8s中是一个虚拟的概念,类似于资源池的概念
类似于docker,kubectl是命令行工具,用于与APIServer交互,内置了丰富的子命令,功能极其强大。 https://kubernetes.io/docs/reference/kubectl/overview/
注:忘记命令就可使用kubectl -h查看命令帮助,如kubectl get pod -h
$ kubectl -h
$ kubectl get -h
$ kubectl create -h
$ kubectl create namespace -h
docker调度的是容器,在k8s集群中,最小的调度单元是Pod(豆荚)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
与容器引擎解耦
Docker、Rkt。平台设计与引擎的具体的实现解耦
多容器共享网络|存储|进程 空间, 支持的业务场景更加灵活
注:pod里面的容器都直接可以通过localhost访问
myblog/one-pod/pod.yaml
apiVersion: v1 #版本
kind: Pod # 类型/角色
metadata: # 元数据属性
name: myblog # pod名称
namespace: luffy # 在哪个namespace下
labels: # pod标签
component: myblog # 相当于component=myblog的标签
spec: #详细说明
containers: # 容器
- name: myblog # 容器名称
image: 10.0.1.5:5000/myblog:v1 # 容器镜像地址
env: #环境变量
- name: MYSQL_HOST # 指定root用户的用户名
value: "127.0.0.1" # 上行name的值
- name: MYSQL_PASSWD # 密码
value: "123456"
ports: #需要暴露的端口号列表,象征的显示此业务跑在8002端口,可以省略不写,没有影响
- containerPort: 8002
- name: mysql # 容器名称
image: mysql:5.7 # 容器使用的镜像
# command
args: # 启动容器运行的命令参数
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
ports: # 需要暴露的端口号列表
- containerPort: 3306
env: # 容器运行前需要设置的环境变量列表
- name: MYSQL_ROOT_PASSWORD
value: "123456"
- name: MYSQL_DATABASE
value: "myblog"
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "myblog",
"namespace": "luffy",
"labels": {
"component": "myblog"
}
},
"spec": {
"containers": [
{
"name": "myblog",
"image": "10.0.1.5:5000/myblog:v1",
"env": [
{
"name": "MYSQL_HOST",
"value": "127.0.0.1"
}
]
},
{
...
}
]
}
}
apiVersion | 含义 |
---|---|
alpha | 进入K8s功能的早期候选版本,可能包含Bug,最终不一定进入K8s |
beta | 已经过测试的版本,最终会进入K8s,但功能、对象定义可能会发生变更。 |
stable | 可安全使用的稳定版本 |
v1 | stable 版本之后的首个版本,包含了更多的核心对象 |
apps/v1 | 使用最广泛的版本,像Deployment、ReplicaSets都已进入该版本 |
资源类型与apiVersion对照表
Kind | apiVersion |
---|---|
ClusterRoleBinding | rbac.authorization.k8s.io/v1 |
ClusterRole | rbac.authorization.k8s.io/v1 |
ConfigMap | v1 |
CronJob | batch/v1beta1 |
DaemonSet | extensions/v1beta1 |
Node | v1 |
Namespace | v1 |
Secret | v1 |
PersistentVolume | v1 |
PersistentVolumeClaim | v1 |
Pod | v1 |
Deployment | v1、apps/v1、apps/v1beta1、apps/v1beta2 |
Service | v1 |
Ingress | extensions/v1beta1 |
ReplicaSet | apps/v1、apps/v1beta2 |
Job | batch/v1 |
StatefulSet | apps/v1、apps/v1beta1、apps/v1beta2 |
快速获得资源和版本
# 查看所有api-versions信息
$ kubectl api-versions
# 查看具体资源详细信息如
$ kubectl explain pod
$ kubectl explain Pod.apiVersion
$ kubectl explain Pod.apiVersion
$ kubectl explain Deployment.apiVersion
$ kubectl explain Service.apiVersion
前提:
# This my first django Dockerfile
# Version 1.0
# Base images 基础镜像
FROM centos:centos7.5.1804
#MAINTAINER 维护者信息
LABEL maintainer="[email protected]"
#ENV 设置环境变量
ENV LANG en_US.UTF-8
ENV LC_ALL en_US.UTF-8
#RUN 执行以下命令
RUN curl -so /etc/yum.repos.d/Centos-7.repo http://mirrors.aliyun.com/repo/Centos-7.repo && rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
RUN yum install -y python36 python3-devel gcc pcre-devel zlib-devel make net-tools nginx
#工作目录
WORKDIR /opt/myblog
#拷贝文件至工作目录
COPY . .
#拷贝nginx配置文件
COPY myblog.conf /etc/nginx
# 安装依赖的插件
RUN pip3 install -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com -r requirements.txt
RUN chmod +x run.sh && rm -rf ~/.cache/pip
# EXPOSE 映射端口
EXPOSE 8002
# 容器启动时执行命令
CMD ["./run.sh"]
详情见上一节Django项目
mkdir luffy && cd luffy
git clone https://gitee.com/agagin/python-demo.git
cd python-demo/
vim Dockerfile
docker build . -t myblog:v1 -f Dockerfile
# 准备镜像文件
[root@k8s-master 2021]# pwd
/root/2021
[root@k8s-master 2021]# ls
registry registry.tar.gz
# 使用docker镜像启动仓库服务
docker run -d -p 5000:5000 --restart always -v /root/2021/registry:/var/lib/registry --name registry registry:2
#创建MySQL配置文件
[root@k8s-master luffy]# mkdir mysql-images/ && cd mysql-images/
[root@k8s-master mysql-images]# cat my.cnf
[mysqld]
user=root
character-set-server=utf8
lower_case_table_names=1
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/
# 创建dockerfile、
[root@k8s-master mysql-images]# cat Dockerfile
FROM mysql:5.7
COPY my.cnf /etc/mysql/my.cnf
## CMD 或者ENTRYPOINT默认继承
# 构建本地镜像
[root@k8s-master mysql-images]# docker build . -t 10.0.1.5:5000/mysql:5.7-utf8
[root@k8s-master mysql-images]# docker tag myblog:v1 10.0.1.5:5000/myblog:v1
#配置加速 docker私有仓库服务器,默认是基于https传输的,所以我们需要在客户端127.0.0.1做相关设置,不使用https传输【此操作主从都需配置】
[root@k8s-master opt]# vi /etc/docker/daemon.json
[root@k8s-master opt]# cat /etc/docker/daemon.json
{
"registry-mirrors": [
"https://8xpk5wnt.mirror.aliyuncs.com"
],
"insecure-registries": [
"10.0.1.5:5000"
]
}
# 重启docker
systemctl daemon-reload
systemctl restart docker
# 推镜像
[root@k8s-master mysql-images]# docker push 10.0.1.5:5000/myblog:v1
[root@k8s-master mysql-images]# docker push 10.0.1.5:5000/mysql:5.7-utf8
# 拷贝yaml文件
[root@k8s-master week2]# pwd
/root/2021/week2
[root@k8s-master week2]# vim pod.yaml
## 创建namespace, namespace是逻辑上的资源池
$ kubectl create namespace luffy
## 使用指定文件创建Pod
$ kubectl create -f pod.yaml
## 查看pod,可以简写po
## 所有的操作都需要指定namespace,如果是在default命名空间下,则可以省略
$ kubectl -n luffy get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE
myblog 2/2 Running 0 3m 10.244.1.4 k8s-slave1
## 回顾流程
## 使用Pod Ip访问服务,3306和8002
$ curl 10.244.1.4:8002/blog/index/
## 进入容器,执行初始化, 不必到对应的主机执行docker exec
$ kubectl -n luffy exec -ti myblog -c myblog bash
/ # env
/ # python3 manage.py migrate
$ kubectl -n luffy exec -ti myblog -c mysql bash
/ # mysql -p123456
## 再次访问服务,3306和8002
$ curl 10.244.1.2:8002/blog/index/
登录k8s-slave1
节点
$ docker ps -a |grep myblog ## 发现有三个容器
## 其中包含mysql和myblog程序以及Infra容器
## 为了实现Pod内部的容器可以通过localhost通信,每个Pod都会启动Infra容器,然后Pod内部的其他容器的网络空间会共享该Infra容器的网络空间(Docker网络的container模式),Infra容器只需要hang住网络空间,不需要额外的功能,因此资源消耗极低。
## 登录master节点,查看pod内部的容器ip均相同,为pod ip
$ kubectl -n luffy exec -ti myblog -c myblog bash
/ # ifconfig
$ kubectl -n luffy exec -ti myblog -c mysql bash
/ # ifconfig
pod容器命名: k8s_
## 查看pod调度节点及pod_ip
$ kubectl -n luffy get pods -o wide
## 查看完整的yaml
$ kubectl -n luffy get po myblog -o yaml
## 查看pod的明细信息及事件
$ kubectl -n luffy describe pod myblog
#进入Pod内的容器
$ kubectl -n exec -c -ti /bin/sh
# 参数解释
# -n 指定命名空间
# exec -ti 进入交互式终端
# -c 容器的名字
#查看Pod内容器日志,显示标准或者错误输出日志
$ kubectl -n logs -f -c
$ kubectl -n logs -f --tail=100 -c
# 参数解释
# logs 查看日志
# -f 实时刷新
# --tail=100 指定行数
$ kubectl apply -f myblog-pod.yaml
# 注:对于pod来讲,如果你的yaml文件资源定义的是pod,没法直接使用apply,除非是修改镜像版本,否则失败,如修改环境变量等apply会检验不通过
#根据文件删除
$ kubectl delete -f myblog-pod.yaml
#根据pod_name删除
$ kubectl -n delete pod
若删除了Pod,由于mysql的数据都在容器内部,会造成数据丢失,因此需要数据进行持久化。
定点使用hostpath挂载,nodeSelector定点
myblog/one-pod/pod-with-volume.yaml
apiVersion: v1
kind: Pod
metadata:
name: myblog
namespace: luffy
labels:
component: myblog #相当于调度到有labels是component=myblog的机器上
spec:
volumes: # 定义卷,和container同级,所以所有container都能引用
- name: mysql-data
hostPath:
path: /opt/mysql/data
nodeSelector: # 使用节点选择器将Pod调度到指定label的节点
component: mysql
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
env:
- name: MYSQL_HOST # 指定root用户的用户名
value: "127.0.0.1"
- name: MYSQL_PASSWD
value: "123456"
ports:
- containerPort: 8002
- name: mysql
image: mysql:5.7
args:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
ports:
- containerPort: 3306
env:
- name: MYSQL_ROOT_PASSWORD
value: "123456"
- name: MYSQL_DATABASE
value: "myblog"
volumeMounts: # 挂载卷,属于container下的一个key,
- name: mysql-data # 名字必须和上面定义的相对应
mountPath: /var/lib/mysql
保存文件为pod-with-volume.yaml
,执行创建
## 若存在旧的同名服务,先删除掉,后创建
$ kubectl -n luffy delete pod myblog
## 创建
$ kubectl create -f pod-with-volume.yaml
## 此时pod状态Pending
$ kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog 0/2 Pending 0 32s
## 查看原因,提示调度失败,因为节点不满足node selector
$ kubectl -n luffy describe po myblog
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedScheduling 12s (x2 over 12s) default-scheduler 0/3 nodes are available: 3 node(s) didn't match node selector.
## 为节点打标签
$ kubectl label node k8s-slave1 component=mysql
## 再次查看,已经运行成功
$ kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE IP NODE
myblog 2/2 Running 0 3m54s 10.244.1.150 k8s-slave1
## 到k8s-slave1节点,查看/opt/mysql/data
$ ll /opt/mysql/data/
total 188484
-rw-r----- 1 polkitd input 56 Mar 29 09:20 auto.cnf
-rw------- 1 polkitd input 1676 Mar 29 09:20 ca-key.pem
-rw-r--r-- 1 polkitd input 1112 Mar 29 09:20 ca.pem
drwxr-x--- 2 polkitd input 8192 Mar 29 09:20 sys
...
## 执行migrate,创建数据库表,然后删掉pod,再次创建后验证数据是否存在
$ kubectl -n luffy exec -ti myblog python3 manage.py migrate
## 访问服务,正常
$ curl 10.244.1.150:8002/blog/index/
## 删除pod
$ kubectl delete -f pod-with-volume.yaml
## 再次创建Pod
$ kubectl create -f pod-with-volume.yaml
## 查看pod ip并访问服务
$ kubectl -n luffy get po -o wide
NAME READY STATUS RESTARTS AGE IP NODE
myblog 2/2 Running 0 7s 10.244.1.151 k8s-slave1
## 未重新做migrate,服务正常
$ curl 10.244.1.151:8002/blog/index/
使用PV+PVC连接分布式存储解决方案
# 添加
$ kubectl label nodes kube-node label_key=label_value
# 查询
$ kubectl get node --show-labels
# 过滤标签
$ kubectl -n ns_name get po -o wide -l label_key=label_value
# 删除一个label,只需在命令行最后指定的label的可以名并与一个减号相连即可:
$ kubectl label nodes k8s-slave1 label_key-
# 修改一个label的值,需要加上--overwrite参数
$ kubectl label nodes k8s-slave1 label_key=apache --overwrite
# 或者你可以直接kubectl edit就可编辑这个node的配置,保存退出就可以了
检测容器服务是否健康的手段,若不健康,会根据设置的重启策略(restartPolicy)进行操作,两种检测机制可以分别单独设置,若不设置,默认认为Pod是健康的。
两种机制:
LivenessProbe探针
存活性探测:用于判断容器是否存活,即Pod是否为running状态,如果LivenessProbe探针探测到容器不健康,则kubelet将kill掉容器,并根据容器的重启策略是否重启,如果一个容器不包含LivenessProbe探针,则Kubelet认为容器的LivenessProbe探针的返回值永远成功。
...
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
livenessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10 # 容器启动后第一次执行探测是需要等待多少秒
periodSeconds: 10 # 执行探测的频率
timeoutSeconds: 2 # 探测超时时间
...
ReadinessProbe探针
可用性探测:用于判断容器是否正常提供服务,即容器的Ready是否为True,是否可以接收请求,如果ReadinessProbe探测失败,则容器的Ready将为False, Endpoint Controller 控制器将此Pod的Endpoint从对应的service的Endpoint列表中移除,不再将任何请求调度此Pod上,直到下次探测成功。(剔除此pod不参与接收请求不会将流量转发给此Pod)。
...
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
readinessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10
timeoutSeconds: 2
periodSeconds: 10
...
三种类型:
示例:
完整文件路径 myblog/one-pod/pod-with-healthcheck.yaml
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
env:
- name: MYSQL_HOST # 指定root用户的用户名
value: "127.0.0.1"
- name: MYSQL_PASSWD
value: "123456"
ports:
- containerPort: 8002
livenessProbe: # 注意添加位置
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10 # 容器启动后第一次执行探测是需要等待多少秒
periodSeconds: 10 # 执行探测的频率
timeoutSeconds: 2 # 探测超时时间
readinessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10
timeoutSeconds: 2
periodSeconds: 10
[root@k8s-master week2]# kubectl delete -f pod-with-volume.yaml
pod "myblog" deleted
[root@k8s-master week2]# vim pod-with-volume.yaml
[root@k8s-master week2]# kubectl create -f pod-with-volume.yaml
pod/myblog created
[root@k8s-master week2]# kubectl -n luffy get po -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE
myblog 1/2 Running 0 29s 10.244.1.15 k8s-slave1
# 进入容器
$ kubectl -n luffy exec -ti myblog -c myblog bash
[root@myblog myblog]# python3 manage.py migrate
$ kubectl -n luffy get po
[root@k8s-master week2]# kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog 2/2 Running 3 6m6s
K8S将在Pod开始启动10s(initialDelaySeconds)后利用HTTP访问8002端口的/blog/index/,如果超过2s或者返回码不在200~399内,则健康检查失败
Pod的重启策略(RestartPolicy)应用于Pod内的所有容器,并且仅在Pod所处的Node上由kubelet进行判断和重启操作。当某个容器异常退出或者健康检查失败时,kubelet将根据RestartPolicy的设置来进行相应的操作。
Pod的重启策略包括Always、OnFailure和Never,默认值为Always。
演示重启策略:
apiVersion: v1
kind: Pod
metadata:
name: test-restart-policy
spec:
restartPolicy: Always
containers:
- name: busybox
image: busybox
args:
- /bin/sh
- -c
- sleep 10
执行结果
$ kubectl apply -f test-restartpolicy.yaml
# 会出现如下几种状态
$ kubectl get po -owide -w
test-restart-policy 0/1 Completed 0 98s 10.244.2.4 k8s-slave2
test-restart-policy 1/1 Running 1 118s 10.244.2.4 k8s-slave2
test-restart-policy 0/1 Completed 1 2m8s 10.244.2.4 k8s-slave2
test-restart-policy 0/1 CrashLoopBackOff 1 2m18s 10.244.2.4 k8s-
可以看出,若容器正常退出,Pod的状态会是Completed,非正常退出,状态为CrashLoopBackOff
spec:
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
imagePullPolicy: IfNotPresent
设置镜像的拉取策略,默认为IfNotPresent
为了保证充分利用集群资源,且确保重要容器在运行周期内能够分配到足够的资源稳定运行,因此平台需要具备
Pod的资源限制的能力。 对于一个pod来说,资源最基础的2个的指标就是:CPU和内存。
Kubernetes提供了个采用requests和limits 两种类型参数对资源进行预分配和使用限制。
完整文件路径:myblog/one-pod/pod-with-resourcelimits.yaml
...
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
env:
- name: MYSQL_HOST # 指定root用户的用户名
value: "127.0.0.1"
- name: MYSQL_PASSWD
value: "123456"
ports:
- containerPort: 8002
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
...
node节点的资源限制查看
$ kubectl describe no k8s-slave1
requests:
limits:
对于 CPU,我们知道计算机里 CPU 的资源是按“时间片”
的方式来进行分配的,系统里的每一个操作都需要 CPU 的处理,所以,哪个任务要是申请的 CPU 时间片越多,那么它得到的 CPU 资源就越多。
然后还需要了解下 CGroup 里面对于 CPU 资源的单位换算:
1 CPU = 1000 millicpu(1 Core = 1000m)
这里的 m
就是毫、毫核的意思,Kubernetes 集群中的每一个节点可以通过操作系统的命令来确认本节点的 CPU 内核数量,然后将这个数量乘以1000,得到的就是节点总 CPU 总毫数。比如一个节点有四核,那么该节点的 CPU 总毫量为 4000m。
docker run
命令和 CPU 限制相关的所有选项如下:
选项 | 描述 |
---|---|
--cpuset-cpus="" |
允许使用的 CPU 集,值可以为 0-3,0,1 |
-c ,--cpu-shares=0 |
CPU 共享权值(相对权重) |
cpu-period=0 |
限制 CPU CFS 的周期,范围从 100ms~1s,即[1000, 1000000] |
--cpu-quota=0 |
限制 CPU CFS 配额,必须不小于1ms,即 >= 1000,绝对限制 |
docker run -it --cpu-period=50000 --cpu-quota=25000 ubuntu:16.04 /bin/bash
将 CFS 调度的周期设为 50000,将容器在每个周期内的 CPU 配额设置为 25000,表示该容器每 50ms 可以得到 50% 的 CPU 运行时间。
注意:若内存使用超出限制,会引发系统的OOM机制,因CPU是可压缩资源,不会引发Pod退出或重建
目前完善后的yaml,myblog/one-pod/pod-completed.yaml
apiVersion: v1
kind: Pod
metadata:
name: myblog
namespace: luffy
labels:
component: myblog
spec:
volumes:
- name: mysql-data
hostPath:
path: /opt/mysql/data
nodeSelector: # 使用节点选择器将Pod调度到指定label的节点
component: mysql
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
env:
- name: MYSQL_HOST # 指定root用户的用户名
value: "127.0.0.1"
- name: MYSQL_PASSWD
value: "123456"
ports:
- containerPort: 8002
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
livenessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10 # 容器启动后第一次执行探测是需要等待多少秒
periodSeconds: 15 # 执行探测的频率
timeoutSeconds: 2 # 探测超时时间
readinessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10
timeoutSeconds: 2
periodSeconds: 15
- name: mysql
image: mysql:5.7
args:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
ports:
- containerPort: 3306
env:
- name: MYSQL_ROOT_PASSWORD
value: "123456"
- name: MYSQL_DATABASE
value: "myblog"
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
readinessProbe:
tcpSocket:
port: 3306
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
tcpSocket:
port: 3306
initialDelaySeconds: 15
periodSeconds: 20
volumeMounts:
- name: mysql-data
mountPath: /var/lib/mysql
为什么要优化
解决问题一,需要拆分yaml
myblog/two-pod/mysql.yaml
apiVersion: v1
kind: Pod
metadata:
name: mysql
namespace: luffy
labels:
component: mysql
spec:
hostNetwork: true # 声明pod的网络模式为host模式,效果同docker run --net=host
volumes:
- name: mysql-data
hostPath:
path: /opt/mysql/data
nodeSelector: # 使用节点选择器将Pod调度到指定label的节点
component: mysql
containers:
- name: mysql
image: mysql:5.7
args:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
ports:
- containerPort: 3306
env:
- name: MYSQL_ROOT_PASSWORD
value: "123456"
- name: MYSQL_DATABASE
value: "myblog"
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
readinessProbe:
tcpSocket:
port: 3306
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
tcpSocket:
port: 3306
initialDelaySeconds: 15
periodSeconds: 20
volumeMounts:
- name: mysql-data
mountPath: /var/lib/mysql
myblog.yaml
apiVersion: v1
kind: Pod
metadata:
name: myblog
namespace: luffy
labels:
component: myblog
spec:
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
imagePullPolicy: IfNotPresent
env:
- name: MYSQL_HOST # 指定root用户的用户名
value: "10.0.1.6" # mysql的地址
- name: MYSQL_PASSWD
value: "123456"
ports:
- containerPort: 8002
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
livenessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10 # 容器启动后第一次执行探测是需要等待多少秒
periodSeconds: 15 # 执行探测的频率
timeoutSeconds: 2 # 探测超时时间
readinessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10
timeoutSeconds: 2
periodSeconds: 15
创建测试
## 先删除旧pod
$ kubectl -n luffy delete po myblog
## 分别创建mysql和myblog
$ kubectl create -f mysql.yaml
$ kubectl create -f myblog.yaml
## 查看pod,注意mysqlIP为宿主机IP,因为网络模式为host
$ kubectl -n luffy get po -o wide
NAME READY STATUS RESTARTS AGE IP NODE
myblog 1/1 Running 0 41s 10.244.1.152 k8s-slave1
mysql 1/1 Running 0 52s 172.21.51.67 k8s-slave1
## 访问myblog服务正常
$ curl 10.244.1.152:8002/blog/index/
解决问题二,环境变量中敏感信息带来的安全隐患
为什么要统一管理环境变量
k8s提供两类资源,configMap和Secret,可以用来实现业务配置的统一管理, 允许将配置文件与镜像文件分离,以使容器化的应用程序具有可移植性 。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
configMap,通常用来管理应用的配置文件或者环境变量,myblog/two-pod/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: myblog
namespace: luffy # 指定namespace,直接引用此命名空间下的,而不能去读取别的命名空间的configMap
data:
MYSQL_HOST: "10.0.1.6"
MYSQL_PORT: "3306"
创建并查看configMap:
$ kubectl create -f configmap.yaml
$ kubectl -n luffy get cm myblog -oyaml
或者可以使用命令的方式,从文件中创建,比如:
configmap.txt
$ cat configmap.txt
MYSQL_HOST=10.0.1.6
MYSQL_PORT=3306
$ kubectl -n luffy create configmap myblog --from-env-file=configmap.txt
环境变量和非环境变量配置文件的创建区别
[root@k8s-master week2]# cat configmap.txt
MYSQL_HOST=10.0.1.6
MYSQL_PORT=3306
kubectl create configmap my-config --from-env-file=path/to/bar.env
kubectl create configmap my-config --from-file=path/to/bar
# 环境变量形式
[root@k8s-master week2]# kubectl -n luffy create configmap myblog --from-env-file=configmap.txt
# 非环境变量形式
[root@k8s-master week2]# cat config.ini
[mysql]
aaa=bbb
ccc=xxx
[root@k8s-master week2]# kubectl -n luffy create configmap demo --from-file=config.ini
kubectl -n luffy get configmap
kubectl -n luffy get configmap myblog -oyaml
kubectl -n luffy get configmap demo -oyaml
# 对比
[root@k8s-master week2]# kubectl -n luffy get configmap myblog -oyaml
apiVersion: v1
data:
MYSQL_HOST: 10.0.1.5
MYSQL_PORT: "3306"
kind: ConfigMap
metadata:
creationTimestamp: "2021-06-13T23:12:58Z"
managedFields:
- apiVersion: v1
fieldsType: FieldsV1
fieldsV1:
f:data:
.: {}
f:MYSQL_HOST: {}
f:MYSQL_PORT: {}
manager: kubectl-create
operation: Update
time: "2021-06-13T23:12:58Z"
name: myblog
namespace: luffy
resourceVersion: "479878"
selfLink: /api/v1/namespaces/luffy/configmaps/myblog
uid: 4c9045fd-0cb3-4cb5-8562-7b808363c249
[root@k8s-master week2]# kubectl -n luffy get configmap demo -oyaml
apiVersion: v1
data:
config.ini: |
[mysql]
aaa=bbb
ccc=xxx
kind: ConfigMap
metadata:
creationTimestamp: "2021-06-13T23:13:14Z"
managedFields:
- apiVersion: v1
fieldsType: FieldsV1
fieldsV1:
f:data:
.: {}
f:config.ini: {}
manager: kubectl-create
operation: Update
time: "2021-06-13T23:13:14Z"
name: demo
namespace: luffy
resourceVersion: "479916"
selfLink: /api/v1/namespaces/luffy/configmaps/demo
uid: a5ac2b59-ae22-4645-af1b-500b501fd15f
命令查看帮助
[root@k8s-master week2]# kubectl -n luffy get configmap myblog -oyaml
# 翻译结果
Examples:
# Create a new configmap named my-config based on folder bar
kubectl create configmap my-config --from-file=path/to/bar
# Create a new configmap named my-config with specified keys instead of file basenames on disk
kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt
--from-file=key2=/path/to/bar/file2.txt
# Create a new configmap named my-config with key1=config1 and key2=config2
kubectl create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2
# Create a new configmap named my-config from the key=value pairs in the file
kubectl create configmap my-config --from-file=path/to/bar
# Create a new configmap named my-config from an env file
kubectl create configmap my-config --from-env-file=path/to/bar.env
列子:
# 根据文件夹栏创建一个名为my-config的新配置映射
# 使用指定的键而不是磁盘上的文件基名创建一个名为 my-config 的新配置映射
# 创建一个名为 my-config 的新配置映射,key1=config1 和 key2=config2
# 从文件中的 key=value 对创建一个名为 my-config 的新配置映射
# 从 env 文件创建一个名为 my-config 的新配置映射
[root@k8s-master week2]# kubectl create secret -h
Create a secret using specified subcommand.
Available Commands:
docker-registry Create a secret for use with a Docker registry
generic Create a secret from a local file, directory or literal value
tls Create a TLS secret
Usage:
kubectl create secret [flags] [options]
Use "kubectl --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
使用指定的子命令创建一个秘密。
可用命令:
docker-registry 创建一个用于 Docker 注册表的密钥
generic 从本地文件、目录或文字值创建一个秘密
tls 创建一个 TLS 秘密
用法:
kubectl 创建秘密 [标志] [选项]
使用“kubectl --help”获取有关给定命令的更多信息。
使用“kubectl options”获取全局命令行选项列表(适用于所有命令)。
myblog/two-pod/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: myblog
namespace: luffy
type: Opaque
data:
MYSQL_USER: cm9vdA== #注意加-n参数, echo -n root|base64
MYSQL_PASSWD: MTIzNDU2
不加-n 多一个换行符
[root@k8s-master week2]# echo -n root|base64
cm9vdA==
[root@k8s-master week2]# echo -n 123456|base64
MTIzNDU2
# 反解
[root@k8s-master week2]# echo cm9vdA==|base64 -d
root
创建并查看:
$ kubectl create -f secret.yaml
$ kubectl -n luffy get secret
如果不习惯这种方式,可以通过如下方式:
$ cat secret.txt
MYSQL_USER=root
MYSQL_PASSWD=123456
$ kubectl -n luffy create secret generic myblog --from-env-file=secret.txt
[root@k8s-master week2]# kubectl -n luffy get secret
NAME TYPE DATA AGE
default-token-thqxq kubernetes.io/service-account-token 3 87m
myblog Opaque 2 24m
[root@k8s-master week2]# kubectl -n luffy get secret myblog -oyaml
apiVersion: v1
data:
MYSQL_PASSWD: MTIzNDU2
MYSQL_USER: cm9vdA==
kind: Secret
metadata:
creationTimestamp: "2021-07-11T03:10:18Z"
managedFields:
- apiVersion: v1
fieldsType: FieldsV1
fieldsV1:
f:data:
.: {}
f:MYSQL_PASSWD: {}
f:MYSQL_USER: {}
f:type: {}
manager: kubectl-create
operation: Update
time: "2021-07-11T03:10:18Z"
name: myblog
namespace: luffy
resourceVersion: "15853"
selfLink: /api/v1/namespaces/luffy/secrets/myblog
uid: 6da85352-0000-4127-9604-18484a8787b3
type: Opaque
修改后的mysql的yaml,资源路径:myblog/two-pod/mysql-with-config.yaml
...
spec:
containers:
- name: mysql
args:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
env: #环境变量
- name: MYSQL_USER
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_USER
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_PASSWD
- name: MYSQL_DATABASE
value: "myblog"
...
整体修改后的myblog的yaml,资源路径:myblog/two-pod/myblog-with-config.yaml
apiVersion: v1
kind: Pod
metadata:
name: myblog
namespace: luffy
labels:
component: myblog
spec:
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
imagePullPolicy: IfNotPresent
env:
- name: MYSQL_HOST
valueFrom:
configMapKeyRef:
name: myblog
key: MYSQL_HOST
- name: MYSQL_PORT
valueFrom:
configMapKeyRef:
name: myblog
key: MYSQL_PORT
- name: MYSQL_USER
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_USER
- name: MYSQL_PASSWD
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_PASSWD
ports:
- containerPort: 8002
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
livenessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10 # 容器启动后第一次执行探测是需要等待多少秒
periodSeconds: 15 # 执行探测的频率
timeoutSeconds: 2 # 探测超时时间
readinessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10
timeoutSeconds: 2
periodSeconds: 15
在部署不同的环境时,pod的yaml无须再变化,只需要在每套环境中维护一套ConfigMap和Secret即可。但是注意configmap和secret不能跨namespace使用,且更新后,pod内的env不会自动更新,重建后方可更新。
[root@k8s-master week2]# vim mysql.yaml
[root@k8s-master week2]# vim myblog.yaml
[root@k8s-master week2]# kubectl -n luffy delete -f myblog.yaml
pod "myblog" deleted
[root@k8s-master week2]# kubectl -n luffy delete -f mysql.yaml
pod "mysql" deleted
[root@k8s-master week2]# kubectl -n luffy create -f myblog.yaml
[root@k8s-master week2]# kubectl -n luffy create -f mysql.yaml
[root@k8s-master week2]# kubectl -n luffy get po -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
myblog 1/1 Running 0 31m 10.244.1.9 k8s-slave1
mysql 1/1 Running 0 74m 10.0.1.6 k8s-slave1
[root@k8s-master week2]# curl 10.244.1.9:8002/blog/index/
我的博客列表:</h3>
拿来主义,从机器中已有的资源中拿
$ kubectl -n kube-system get po,deployment,ds
学会在官网查找, https://kubernetes.io/docs/home/
从kubernetes-api文档中查找, https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.16/#pod-v1-core
kubectl explain 查看具体字段含义
Pod的状态如下表所示:
状态值 | 描述 |
---|---|
Pending | API Server已经创建该Pod,等待调度器调度 |
ContainerCreating | 拉取镜像启动容器中 |
Running | Pod内容器均已创建,且至少有一个容器处于运行状态、正在启动状态或正在重启状态 |
Succeeded|Completed | Pod内所有容器均已成功执行退出,且不再重启 |
Failed|Error | Pod内所有容器均已退出,但至少有一个容器退出为失败状态 |
CrashLoopBackOff | Pod内有容器启动失败,比如配置文件丢失导致主进程启动失败 |
Unknown | 由于某种原因无法获取该Pod的状态,可能由于网络通信不畅导致 |
生命周期示意图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
启动和关闭示意:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
初始化容器:
...
initContainers:
- command:
- /sbin/sysctl
- -w
- vm.max_map_count=262144
image: alpine:3.6
imagePullPolicy: IfNotPresent
name: elasticsearch-logging-init
resources: {}
securityContext:
privileged: true
- name: fix-permissions
image: alpine:3.6
command: ["sh", "-c", "chown -R 1000:1000 /usr/share/elasticsearch/data"]
securityContext:
privileged: true
volumeMounts:
- name: elasticsearch-logging
mountPath: /usr/share/elasticsearch/data
...
验证Pod生命周期:
apiVersion: v1
kind: Pod
metadata:
name: pod-lifecycle
namespace: luffy
labels:
component: pod-lifecycless
spec:
initContainers:
- name: init
image: busybox
command: ['sh', '-c', 'echo $(date +%s): INIT >> /loap/timing']
volumeMounts:
- mountPath: /loap
name: timing
containers:
- name: main
image: busybox
command: ['sh', '-c', 'echo $(date +%s): START >> /loap/timing;
sleep 10; echo $(date +%s): END >> /loap/timing;']
volumeMounts:
- mountPath: /loap
name: timing
livenessProbe:
exec:
command: ['sh', '-c', 'echo $(date +%s): LIVENESS >> /loap/timing']
readinessProbe:
exec:
command: ['sh', '-c', 'echo $(date +%s): READINESS >> /loap/timing']
lifecycle:
postStart:
exec:
command: ['sh', '-c', 'echo $(date +%s): POST-START >> /loap/timing']
preStop:
exec:
command: ['sh', '-c', 'echo $(date +%s): PRE-STOP >> /loap/timing']
volumes:
- name: timing
hostPath:
path: /tmp/loap
创建pod测试:
$ kubectl create -f pod-lifecycle.yaml
## 查看demo状态
$ kubectl -n luffy get po -o wide -w
## 查看调度节点的/tmp/loap/timing
$ cat /tmp/loap/timing
1585424708: INIT
1585424746: START
1585424746: POST-START
1585424754: READINESS
1585424756: LIVENESS
1585424756: END
须主动杀掉 Pod 才会触发
pre-stop hook
,如果是 Pod 自己 Down 掉,则不会执行pre-stop hook
,且杀掉Pod进程前,进程必须是正常运行状态,否则不会执行pre-stop钩子
做了哪些工作:
只使用Pod, 面临的问题:
控制器又称工作负载是用于实现管理pod的中间层,确保pod资源符合预期的状态,pod的资源出现故障时,会尝试 进行重启,当根据重启策略无效,则会重新新建pod的资源。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
myblog/deployment/deploy-mysql.yaml
apiVersion: apps/v1 # 版本
kind: Deployment # 类型
metadata: # 元数据
name: mysql # deployment的名称
namespace: luffy
spec: # 详细说明
replicas: 1 #指定Pod副本数
selector: # 【指定Pod的选择器】,
matchLabels: # 匹配标签,
app: mysql # 与上面selector相对应,选择器会选择 pod里面带有 app=mysql这样label的pod
template: # 定义下面的一个标签模板
metadata: # 元数据
labels: #给Pod打label,与matchLabels是一起使用的,意思就是给pod定义一个matchLabel相匹配的标签
app: mysql # 定义一个app=mysql的标签
spec:
hostNetwork: true
volumes:
- name: mysql-data
hostPath:
path: /opt/mysql/data
nodeSelector: # 使用节点选择器将Pod调度到指定label的节点
component: mysql
containers:
- name: mysql
image: mysql:5.7
args:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
ports:
- containerPort: 3306
env:
- name: MYSQL_USER
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_USER
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_PASSWD
- name: MYSQL_DATABASE
value: "myblog"
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
readinessProbe:
tcpSocket:
port: 3306
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
tcpSocket:
port: 3306
initialDelaySeconds: 15
periodSeconds: 20
volumeMounts:
- name: mysql-data
mountPath: /var/lib/mysql
deploy-myblog.yaml:
apiVersion: apps/v1 # 版本
kind: Deployment # 类型
metadata: #元数据
name: myblog # deployment的名称
namespace: luffy
spec: # 详细说明
replicas: 1 #指定Pod副本数
selector: #指定Pod的选择器
matchLabels: # 匹配标签,
app: myblog # 与下面选择器相对应,选择器选择 pod里面带有 app=myblog这样label的pod
template: # 模板
metadata:
labels: #给Pod打label,与matchLabels是一起使用的,意思就是给pod定义一个matchLabel相匹配的标签
app: myblog
spec: # 到这以后基本都是pod的写法,注意这两个spec的位置,空格。
containers:
- name: myblog
image: 10.0.1.5:5000/myblog:v1
imagePullPolicy: IfNotPresent
env:
- name: MYSQL_HOST
valueFrom:
configMapKeyRef:
name: myblog
key: MYSQL_HOST
- name: MYSQL_PORT
valueFrom:
configMapKeyRef:
name: myblog
key: MYSQL_PORT
- name: MYSQL_USER
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_USER
- name: MYSQL_PASSWD
valueFrom:
secretKeyRef:
name: myblog
key: MYSQL_PASSWD
ports:
- containerPort: 8002
resources:
requests:
memory: 100Mi
cpu: 50m
limits:
memory: 500Mi
cpu: 100m
livenessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10 # 容器启动后第一次执行探测是需要等待多少秒
periodSeconds: 15 # 执行探测的频率
timeoutSeconds: 2 # 探测超时时间
readinessProbe:
httpGet:
path: /blog/index/
port: 8002
scheme: HTTP
initialDelaySeconds: 10
timeoutSeconds: 2
periodSeconds: 15
注:
[root@k8s-master week2]# vim mysql-deploy.yaml
[root@k8s-master week2]# vim myblog-deploy.yaml
[root@k8s-master week2]# kubectl delete -f mysql.yaml
[root@k8s-master week2]# kubectl delete -f myblog.yaml
$ kubectl create -f deploy-mysql.yaml
$ kubectl create -f deploy-myblog.yaml
# kubectl api-resources
$ kubectl -n luffy get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
myblog 1/1 1 1 2m22s
mysql 1/1 1 1 2d11h
* `NAME` 列出了集群中 Deployments 的名称。
* `READY`显示当前正在运行的副本数/期望的副本数。
* `UP-TO-DATE`显示已更新以实现期望状态的副本数。
* `AVAILABLE`显示应用程序可供用户使用的副本数。
* `AGE` 显示应用程序运行的时间量。
# 查看pod
$ kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog-7c96c9f76b-qbbg7 1/1 Running 0 109s
mysql-85f4f65f99-w6jkj 1/1 Running 0 2m28s
# 查看replicaSet
$ kubectl -n luffy get rs
# 删除pod发现deployment会自动重新创建、
[root@k8s-master week2]# kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog-5d9b76df88-bxbfh 1/1 Running 0 5m12s
mysql-7446f4dc7b-jp2ps 1/1 Running 0 67m
[root@k8s-master week2]# kubectl delete po myblog-5d9b76df88-tbzj4 -n luffy
pod "myblog-5d9b76df88-tbzj4" deleted
[root@k8s-master week2]# kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog-5d9b76df88-bxbfh 1/1 Running 0 8m20s
mysql-7446f4dc7b-jp2ps 1/1 Running 0 70m
假如deployment在,却没有拉起pod怎么办?
# 查看kube-controller-manager-k8s-master日志,正常他会生成pod元数据,去查看为什么没有生成
$ kubectl -n kube-system logs -f kube-controller-manager-k8s-master
面试题
# kube-controller-manager和scheduler谁在前,谁在后?
kube-controller-manager在前,因为它负载是生成pod元数据,写到etcd中,schedule才能去调度
schedule是负责调度pod,如果没有pod没法调度
controller实时检测pod状态,并保障副本数一直处于期望的值。
## 删除pod,观察pod状态变化
$ kubectl -n luffy delete pod myblog-7c96c9f76b-qbbg7
# 观察pod
$ kubectl get pods -o wide
## 设置两个副本, 或者通过kubectl -n luffy edit deploy myblog的方式,最好通过修改文件,然后apply的方式,这样yaml文件可以保持同步
$ kubectl -n luffy scale deploy myblog --replicas=2
deployment.extensions/myblog scaled
# 观察pod
$ kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE
myblog-7c96c9f76b-qbbg7 1/1 Running 0 11m
myblog-7c96c9f76b-s6brm 1/1 Running 0 55s
mysql-85f4f65f99-w6jkj 1/1 Running 0 11m
K8S 有个特色功能叫 pod eviction,它在某些场景下如节点 NotReady,或者资源不足时,把 pod 驱逐至其它节点,这也是出于业务保护的角度去考虑的。
Kube-controller-manager: 周期性检查所有节点状态,当节点处于 NotReady 状态超过一段时间后,驱逐该节点上所有 pod。
pod-eviction-timeout
:NotReady 状态节点超过该时间后,执行驱逐,默认 5 min,适用于k8s 1.13版本之前TaintBasedEvictions 与TaintNodesByCondition
功能,即taint-based-evictions,即节点若失联或者出现各种异常情况,k8s会自动为node打上污点,同时为pod默认添加如下容忍设置:[root@k8s-master week2]# kubectl -n luffy get po myblog-5d9b76df88-7b4qh -oyaml|grep -A 8 "tolerations"
tolerations:
- effect: NoExecute
key: node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds: 300
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds: 300
tolerations:
- effect: NoExecute
key: node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds: 300
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds: 300
即各pod可以独立设置驱逐容忍时间。
Kubelet: 周期性检查本节点资源,当资源不足时,按照优先级驱逐部分 pod
memory.available
:节点可用内存nodefs.available
:节点根盘可用存储空间nodefs.inodesFree
:节点inodes可用数量imagefs.available
:镜像存储盘的可用空间imagefs.inodesFree
:镜像存储盘的inodes可用数量$ df -TH
存储盘满了,会去检查/var/lib/docker,或者docker所在目录,在没有设置的情况下使用率超过百分之80会出发kubelet的一些操作,比如清理image,检查到快满了会操作一些docker相关的操作,一旦去清理会全部把本地的镜像删除。还会有一个操作,假如镜像删除不了,会去驱逐你的pod,将pod赶到别的机器上去,也是处于保护业务的一种考虑。本质上说就是为了业务的稳定运行。
修改服务,重新打tag模拟服务更新。
更新方式:
修改yaml文件,使用kubectl -n luffy apply -f deploy-myblog.yaml
来应用更新
kubectl -n luffy edit deploy myblog
在线更新
kubectl -n luffy set image deploy myblog myblog=10.0.1.5:5000/myblog:v2 --record
注
kubectl -n luffy set image deploy myblog myblog=10.0.1.5:5000/myblog:v2 --record
# 参数解释
# set image 设置镜像
# 给名字叫myblog的deploy,设置镜像
# myblog=10.0.1.5:5000/myblog:v2,myblog为容器名称=镜像地址,指定替换哪个容器的镜像
# --record 记录 不写也可以更改
可以 kubectl -n luffy set image -h 查看
修改文件测试:
注
修改内容测试,v2
[root@k8s-master ~]# vim /root/2021/python-demo/blog/templates/index.html
[root@k8s-master python-demo]# pwd
/root/2021/python-demo
[root@k8s-master python-demo]# docker build . -t 10.0.1.5:5000/myblog:v2 -f Dockerfile
[root@k8s-master python-demo]# docker push 10.0.1.5:5000/myblog:v2
[root@k8s-master python-demo]# kubectl -n luffy edit deploy myblog
deployment.apps/myblog edited
改成v2
image: 10.0.1.5:5000/myblog:v2
注意查看pod的变化
[root@k8s-master python-demo]# kubectl -n luffy get po -owide -w
NAME READY STATUS RESTARTS AGE IP NODE
myblog-5d9b76df88-7b4qh 1/1 Running 0 29m 10.244.0.7 k8s-master
myblog-5d9b76df88-bxbfh 1/1 Running 0 36m 10.244.1.16 k8s-slave1
mysql-7446f4dc7b-jp2ps 1/1 Running 0 98m 10.0.1.6 k8s-slave1
# 可以通过查看yaml文件看更新策略
$ kubectl -n luffy get deploy -oyaml |more
...
spec:
replicas: 2 #指定Pod副本数
selector: #指定Pod的选择器
matchLabels:
app: myblog
strategy:
rollingUpdate:
maxSurge: 25% # 最大允许3个pod出现,replicas指定pod副本数是2,所以2+2*0.25=2.5,向上取整是2
maxUnavailable: 25% # 最多允许2+2*0.5(向下取整是0):所以是2+0=2
type: RollingUpdate #指定更新方式为滚动更新,默认策略,通过get deploy yaml查看
...
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
策略控制:
在Deployment rollout时,需要保证Available(Ready) Pods数不低于 desired pods number - maxUnavailable; 保证所有的非异常状态Pods数不多于 desired pods number + maxSurge。
以myblog为例,使用默认的策略,更新过程:
#查看滚动更新事件
$ kubectl -n luffy describe deploy myblog
...
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal ScalingReplicaSet 11s deployment-controller Scaled up replica set myblog-6cf56fc848 to 1
Normal ScalingReplicaSet 11s deployment-controller Scaled down replica set myblog-6fdcf98f9 to 1
Normal ScalingReplicaSet 11s deployment-controller Scaled up replica set myblog-6cf56fc848 to 2
Normal ScalingReplicaSet 6s deployment-controller Scaled down replica set myblog-6fdcf98f9 to 0
$ kubectl get rs
NAME DESIRED CURRENT READY AGE
myblog-6cf56fc848 2 2 2 16h
myblog-6fdcf98f9 0 0 0 16h
除了滚动更新以外,还有一种策略是Recreate,直接在当前的pod基础上先删后建:
...
strategy:
type: Recreate
...
我们课程中的mysql服务应该使用Recreate来管理:
$ kubectl -n luffy edit deploy mysql
...
selector:
matchLabels:
app: mysql
strategy:
type: Recreate
template:
metadata:
creationTimestamp: null
labels:
app: mysql
...
通过滚动升级的策略可以平滑的升级Deployment,若升级出现问题,需要最快且最好的方式回退到上一次能够提供正常工作的版本。为此K8S提供了回滚机制。
revision:更新应用时,K8S都会记录当前的版本号,即为revision,当升级出现问题时,可通过回滚到某个特定的revision,默认配置下,K8S只会保留最近的几个revision,可以通过Deployment配置文件中的spec.revisionHistoryLimit属性增加revision数量,默认是10。
查看当前:
$ kubectl -n luffy rollout history deploy myblog ##CHANGE-CAUSE为空
$ kubectl delete -f deploy-myblog.yaml ## 方便演示到具体效果,删掉已有deployment
记录回滚:
$ kubectl apply -f deploy-myblog.yaml --record
$ kubectl -n luffy set image deploy myblog myblog=172.21.51.143:5000/myblog:v2 --record=true
查看deployment更新历史:
$ kubectl -n luffy rollout history deploy myblog
deployment.extensions/myblog
REVISION CHANGE-CAUSE
1 kubectl create --filename=deploy-myblog.yaml --record=true
2 kubectl set image deploy myblog myblog=172.21.51.143:5000/demo/myblog:v1 --record=true
回滚到具体的REVISION:
$ kubectl -n luffy rollout undo deploy myblog --to-revision=1
deployment.extensions/myblog rolled back
# 访问应用测试
通过以前的学习,我们已经能够通过Deployment来创建一组Pod来提供具有高可用性的服务。虽然每个Pod都会分配一个单独的Pod IP,然而却存在如下两个问题:
service是一组pod的服务抽象,相当于一组pod的LB,负责将请求分发给对应的pod。service会为这个LB提供一个IP,一般称为cluster IP 。使用Service对象,通过selector进行标签选择,找到对应的Pod:
myblog/deployment/svc-myblog.yaml
apiVersion: v1
kind: Service
metadata:
name: myblog
namespace: luffy
spec:
ports:
- port: 80 # 这是映射到这个ClusterIP上的端,可以自定义
protocol: TCP # 协议是tcp
targetPort: 8002 # 容器内的端口是8002
selector: # 节点选择器
app: myblog # 选择app=myblog的pod
type: ClusterIP # k8s中svc有三种类型,分别ClusterIP、NodePort、LoadBanlancer
# 查看labes
[root@k8s-master ~]# kubectl -n luffy get po --show-labels
NAME READY STATUS RESTARTS AGE LABELS
myblog-5d9b76df88-k9cqs 1/1 Running 0 110s app=myblog,pod-template-hash=5d9b76df88
myblog-5d9b76df88-wthjt 1/1 Running 0 12h app=myblog,pod-template-hash=5d9b76df88
mysql-7446f4dc7b-5t9db 1/1 Running 0 16h app=mysql,pod-template-hash=7446f4dc7b
# 可以看出selector选择器可以管理如下的pod
[root@k8s-master ~]# kubectl -n luffy get po -l app=myblog
NAME READY STATUS RESTARTS AGE
myblog-5d9b76df88-k9cqs 1/1 Running 0 3m19s
myblog-5d9b76df88-wthjt 1/1 Running 0 12h
操作演示:
## 别名
$ alias kd='kubectl -n luffy'
## 创建服务
$ kd create -f svc-myblog.yaml
$ kd get po --show-labels
NAME READY STATUS RESTARTS AGE LABELS
myblog-5c97d79cdb-jn7km 1/1 Running 0 6m5s app=myblog
mysql-85f4f65f99-w6jkj 1/1 Running 0 176m app=mysql
$ kd get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.99.174.93 80/TCP 7m50s
$ kd describe svc myblog
Name: myblog
Namespace: demo
Labels:
Annotations:
Selector: app=myblog
Type: ClusterIP #这是一个虚拟ip,可以通过80端口访问他
IP: 10.99.174.93
Port: 80/TCP
TargetPort: 8002/TCP
Endpoints: 10.244.0.68:8002
Session Affinity: None
Events:
## 扩容myblog服务
$ kd scale deploy myblog --replicas=2
deployment.extensions/myblog scaled
## 再次查看
$ kd describe svc myblog
Name: myblog
Namespace: demo
Labels:
Annotations:
Selector: app=myblog
Type: ClusterIP
IP: 10.99.174.93
Port: 80/TCP
TargetPort: 8002/TCP
Endpoints: 10.244.0.68:8002,10.244.1.158:8002
Session Affinity: None
Events:
注释:
# 创建服务
[root@k8s-master week2]# kubectl -n luffy create -f svc-myblog.yaml
[root@k8s-master week2]# kubectl -n luffy get po --show-labels
NAME READY STATUS RESTARTS AGE LABELS
myblog-5d9b76df88-txhbn 1/1 Running 1 99m app=myblog,pod-template-hash=5d9b76df88
myblog-5d9b76df88-wthjt 1/1 Running 1 14h app=myblog,pod-template-hash=5d9b76df88
mysql-58d95d459c-xtcjl 1/1 Running 0 66m app=mysql,pod-template-hash=58d95d459c
[root@k8s-master week2]# kubectl -n luffy get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.104.72.57 80/TCP 102m
[root@k8s-master week2]# kubectl -n luffy get pod -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
myblog-5d9b76df88-txhbn 1/1 Running 1 100m 10.244.0.11 k8s-master
myblog-5d9b76df88-wthjt 1/1 Running 1 14h 10.244.1.20 k8s-slave1
mysql-58d95d459c-xtcjl 1/1 Running 0 66m 10.244.1.21 k8s-slave1
[root@k8s-master week2]# kubectl -n luffy describe svc myblog
Name: myblog
Namespace: luffy
Labels:
Annotations:
Selector: app=myblog
Type: ClusterIP
IP: 10.104.72.57 # 访问这个地址的80 端口,会请求转发到下面的Endpoints对应的两个地址+端口上
Port: 80/TCP
TargetPort: 8002/TCP
Endpoints: 10.244.0.11:8002,10.244.1.20:8002
Session Affinity: None
Events:
# 可以看到访问 clusterIP的80 端口会转发到下面的Endpoints地址上,也就是myblog——pod上去
[root@k8s-master week2]# curl 10.104.72.57/blog/index/
<!DOCTYPE html>
"en">
"UTF-8">
首页</title>
</head>
我的博客列表:</h3>
</br>
</br>
" /blog/article/edit/0 ">写博客</a>
</body>
# 删除一个pod,自动重建ip地址会发现改变
[root@k8s-master week2]# kubectl -n luffy get po -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
myblog-5d9b76df88-txhbn 1/1 Running 1 104m 10.244.0.11 k8s-master
myblog-5d9b76df88-wthjt 1/1 Running 1 14h 10.244.1.20 k8s-slave1
mysql-58d95d459c-xtcjl 1/1 Running 0 70m 10.244.1.21 k8s-slave1
[root@k8s-master week2]# kubectl -n luffy delete po myblog-5d9b76df88-txhbn
pod "myblog-5d9b76df88-txhbn" deleted
# ip已经从原来的11变成了12
[root@k8s-master week2]# kubectl -n luffy get po -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
myblog-5d9b76df88-l69gj 1/1 Running 0 45s 10.244.0.12 k8s-master
myblog-5d9b76df88-wthjt 1/1 Running 1 14h 10.244.1.20 k8s-slave1
mysql-58d95d459c-xtcjl 1/1 Running 0 72m 10.244.1.21 k8s-slave1
# 再次查看,svc后端的地址也会更新成12
[root@k8s-master week2]# kubectl -n luffy describe svc myblog
Name: myblog
Namespace: luffy
Labels:
Annotations:
Selector: app=myblog
Type: ClusterIP
IP: 10.104.72.57
Port: 80/TCP
TargetPort: 8002/TCP
Endpoints: 10.244.0.12:8002,10.244.1.20:8002
Session Affinity: None
Events:
# 会与endpoints绑定,创建svc是默认创建一个同名endpoints
[root@k8s-master week2]# kubectl -n luffy get endpoints myblog
NAME ENDPOINTS AGE
myblog 10.244.0.12:8002,10.244.1.20:8002 113m
Service与Pod如何关联:
service对象创建的同时,会创建同名的endpoints对象,若服务设置了readinessProbe, 当readinessProbe检测失败时,endpoints列表中会剔除掉对应的pod_ip,这样流量就不会分发到健康检测失败的Pod中
$ kd get endpoints myblog
NAME ENDPOINTS AGE
myblog 10.244.0.68:8002,10.244.1.158:8002 7m
Service Cluster-IP如何访问:
$ kd get svc myblog
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.99.174.93 80/TCP 13m
$ curl 10.99.174.93/blog/index/
为mysql服务创建service:
apiVersion: v1
kind: Service
metadata:
name: mysql
namespace: luffy
spec:
ports:
- port: 3306
protocol: TCP
targetPort: 3306
selector:
app: mysql
type: ClusterIP
访问mysql:
$ kubectl apply -f svc-mysql.yaml
[root@k8s-master week2]# kubectl -n luffy get svc mysql
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
mysql ClusterIP 10.106.120.127 3306/TCP 102m
[root@k8s-master week2]# curl 10.106.120.127:3306
5.7.34m]
4>ÿÿaRSFqx
kMmysql_native_password!ÿ#08S01Got packets out of order
目前使用hostNetwork部署,通过宿主机ip+port访问,弊端:
服务均属于k8s集群,尽可能使用k8s的网络访问,因此可以对目前myblog访问mysql的方式做改造:
在k8s集群中,组件之间可以通过定义的Service名称实现通信。
演示服务发现:
## 演示思路:在myblog的容器中直接通过service名称访问服务,观察是否可以访问通
# 先查看服务
$ kd get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.99.174.93 80/TCP 59m
mysql ClusterIP 10.108.214.84 3306/TCP 35m
# 进入myblog容器
$ kd exec -ti myblog-5c97d79cdb-j485f bash
[root@myblog-5c97d79cdb-j485f myblog]# curl mysql:3306
5.7.29 )→ (mysql_native_password ot packets out of order
[root@myblog-5c97d79cdb-j485f myblog]# curl myblog/blog/index/
我的博客列表
虽然podip和clusterip都不固定,但是service name是固定的,而且具有完全的跨集群可移植性,因此组件之间调用的同时,完全可以通过service name去通信,这样避免了大量的ip维护成本,使得服务的yaml模板更加简单。因此可以对mysql和myblog的部署进行优化改造:
注:为什么在myblog容器内 curl mysql:3306 也能通?
[root@k8s-master week2]# kubectl -n luffy get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.104.72.57 80/TCP 116m
mysql ClusterIP 10.106.120.127 3306/TCP 104m
[root@k8s-master week2]# kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog-5d9b76df88-l69gj 1/1 Running 0 7m43s
myblog-5d9b76df88-wthjt 1/1 Running 1 14h
[root@k8s-master week2]# kubectl -n luffy exec -ti myblog-5d9b76df88-l69gj -- bash
[root@myblog-5d9b76df88-l69gj myblog]# curl 10.106.120.127:3306
5.7.34ͱxn) ÿÿ~Y[#Nj8%|9mysql_native_password!ÿ#08S01Got packets out of order
依次回去如下解析
[root@myblog-5d9b76df88-l69gj myblog]# cat /etc/resolv.conf
nameserver 10.96.0.10 # 所有的pod这一行都是一样的,下面的则是同一个namespace下是相同的内容
search luffy.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
# 定义一个search,会一次去做解析,如果不同就继续下挨个匹配
luffy.svc.cluster.local
svc.cluster.local
cluster.local
[root@myblog-5d9b76df88-l69gj myblog]# curl mysql.luffy.svc.cluster.local:3306
5.7.34K8Op RWÿÿxJQ6B?v:A42mysql_native_password!ÿ#08S01Got packets out of order
【为什么会通,还要看namespace,一般namespace的端口是53】
[root@myblog-5d9b76df88-l69gj myblog]# curl 10.96.0.10:53
curl: (52) Empty reply from server
# 既然能通,那么10.96.0.10是从哪来的
# 参数解释
-A 跨整个namespace查询,等于 --all-namespace
[root@k8s-master ~]# kubectl get service -A|grep "10.96.0.10"
kube-system kube-dns ClusterIP 10.96.0.10 53/UDP,53/TCP,9153/TCP 2d12
# 怎么查看这个svc是哪个pod
[root@k8s-master ~]# kubectl -n kube-system describe svc kube-dns
Name: kube-dns
Namespace: kube-system
Labels: k8s-app=kube-dns
kubernetes.io/cluster-service=true
kubernetes.io/name=KubeDNS
Annotations: prometheus.io/port: 9153
prometheus.io/scrape: true
Selector: k8s-app=kube-dns # 用它搜索查找pod
Type: ClusterIP
IP: 10.96.0.10
Port: dns 53/UDP
TargetPort: 53/UDP
Endpoints: 10.244.0.4:53,10.244.0.5:53
Port: dns-tcp 53/TCP
TargetPort: 53/TCP
Endpoints: 10.244.0.4:53,10.244.0.5:53
Port: metrics 9153/TCP
TargetPort: 9153/TCP
Endpoints: 10.244.0.4:9153,10.244.0.5:9153
Session Affinity: None
Events:
[root@k8s-master ~]# kubectl -n kube-system get po -l k8s-app=kube-dns -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
coredns-6d56c8448f-csr4b 1/1 Running 1 2d12h 10.244.0.4 k8s-master
coredns-6d56c8448f-jh2gm 1/1 Running 1 2d12h 10.244.0.5 k8s-master
# 所有的pod这一行的namespace都是一样的,下面的则是同一个namespace下是相同的内容
[root@k8s-master week2]# kubectl -n luffy get pod
NAME READY STATUS RESTARTS AGE
myblog-5d9b76df88-85k24 1/1 Running 0 7m41s
myblog-5d9b76df88-t26t4 1/1 Running 0 8m48s
mysql-7446f4dc7b-7kpj8 1/1 Running 0 8m43s
[root@k8s-master week2]# kubectl -n luffy exec -ti myblog-5d9b76df88-85k24 -- cat /etc/resolv.conf
nameserver 10.96.0.10
search luffy.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
[root@k8s-master week2]# kubectl -n luffy exec -ti myblog-5d9b76df88-t26t4 -- cat /etc/resolv.conf
nameserver 10.96.0.10
search luffy.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
[root@k8s-master week2]# kubectl -n luffy exec -ti mysql-7446f4dc7b-7kpj8 -- cat /etc/resolv.conf
nameserver 1.2.4.8 # host模式启动的和宿主机是一样的
意味着在容器内可以通过curl mysql:3306 去访问
修改deploy-mysql.yaml
spec:
hostNetwork: true # 去掉此行
volumes:
- name: mysql-data
hostPath:
path: /opt/mysql/data
ports:
- containerPort: 3306
hostPort: 3306 # 去掉此行
protocol: TCP
修改configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: myblog
namespace: luffy
data:
MYSQL_HOST: "mysql" # 此处替换为mysql
MYSQL_PORT: "3306"
注:若是yaml文件,直接修改重建,若是txt文件操作如下
[root@k8s-master week2]# vim configmap.txt
[root@k8s-master week2]# cat configmap.txt
MYSQL_HOST=mysql
MYSQL_PORT=3306
[root@k8s-master week2]# kubectl delete cm myblog -n luffy
configmap "myblog" deleted
[root@k8s-master week2]# kubectl create cm -h
# 找到如下行
kubectl create configmap my-config --from-env-file=path/to/bar.env
执行如下:
kubectl -n luffy create configmap myblog --from-env-file=configmap.txt
应用修改:
$ kubectl delete -f deployment-mysql.yaml
## myblog不用动,会自动因健康检测不过而重启
# 删除如上两行,重新构建,发现mysql的ip由原来的宿主机ip变成了pod_ip
[root@k8s-master week2]# kubectl get po -n luffy -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
myblog-5d9b76df88-85k24 1/1 Running 0 18m 10.244.0.7 k8s-master
myblog-5d9b76df88-t26t4 1/1 Running 0 19m 10.244.1.6 k8s-slave1
mysql-7446f4dc7b-7kpj8 1/1 Running 0 19m 10.244.1.7 k8s-slave1
# 对别这步骤之前的mysql_pod地址
[root@k8s-master week2]# kubectl get po -n luffy -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
myblog-5d9b76df88-85k24 1/1 Running 0 18m 10.244.0.7 k8s-master
myblog-5d9b76df88-t26t4 1/1 Running 0 19m 10.244.1.6 k8s-slave1
mysql-7446f4dc7b-7kpj8 1/1 Running 0 19m 10.0.1.6 k8s-slave1
# 再次进入容器发现curl 10.0.1.6:3306发现已经不通了,curl pod_id:3306却是通的,说明此时已经变成k8s内部的网络
[root@k8s-master week2]# kubectl -n luffy exec -ti myblog-5d9b76df88-85k24 -- curl 10.0.1.6:3306
5.7.34zruLd-Wÿÿ%*Vxkmysql_native_password!ÿ#08S01Got packets out of order
[root@k8s-master week2]# kubectl -n luffy exec -ti myblog-5d9b76df88-85k24 -- curl 10.0.1.7:3306
5.7.34zruLd-Wÿÿ%*Vxkmysql_native_password!ÿ#08S01Got packets out of order
[root@k8s-master week2]# kubectl describe svc mysql -n luffy
Name: mysql
Namespace: luffy
Labels:
Annotations:
Selector: app=mysql
Type: ClusterIP
IP: 10.107.191.182
Port: 3306/TCP
TargetPort: 3306/TCP
Endpoints: 10.0.1.6:3306
Session Affinity: None
Events:
[root@k8s-master week2]# kubectl -n luffy exec -ti myblog-5d9b76df88-t26t4 -- env | grep -i mysql
MYSQL_HOST=10.0.1.6
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWD=123456
# 回顾这么做的原因:
# 目前使用hostNetwork部署,通过宿主机ip+port访问,弊端:
#- 服务使用hostNetwork,使得宿主机的端口大量暴漏,存在安全隐患
#- 容易引发端口冲突
#服务均属于k8s集群,尽可能使用k8s的网络访问,因此可以对目前myblog访问mysql的方式做改造:
#- 为mysql创建一个固定clusterIp的Service,把clusterIp配置在myblog的环境变量中
#- 利用集群服务发现的能力,组件之间通过service name来访问
总结:这样做既不用担心pod来回变的问题,还能以一个固定的方式 mysql:3306 的方式访问,这个mysql名称是可以固定的,这样一来,两套一模一样的对象,configmap也无需变动,可以在多套环境中来回移植。
服务发现实现:
CoreDNS
是一个Go
语言实现的链式插件DNS服务端
,是CNCF成员,是一个高性能、易扩展的DNS服务端
。
$ kubectl -n kube-system get po -o wide|grep dns
coredns-d4475785-2w4hk 1/1 Running 0 4d22h 10.244.0.64
coredns-d4475785-s49hq 1/1 Running 0 4d22h 10.244.0.65
# 查看myblog的pod解析配置
$ kubectl -n luffy exec -ti myblog-5c97d79cdb-j485f bash
[root@myblog-5c97d79cdb-j485f myblog]# cat /etc/resolv.conf
nameserver 10.96.0.10
search luffy.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
## 10.96.0.10 从哪来
$ kubectl -n kube-system get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kube-dns ClusterIP 10.96.0.10 53/UDP,53/TCP 51d
## 启动pod的时候,会把kube-dns服务的cluster-ip地址注入到pod的resolve解析配置中,同时添加对应的namespace的search域。 因此跨namespace通过service name访问的话,需要添加对应的namespace名称,
service_name.namespace
$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 443/TCP 26h
cluster-ip为虚拟地址,只能在k8s集群内部进行访问,集群外部如果访问内部服务,实现方式之一为使用NodePort方式。NodePort会默认在 30000-32767 ,不指定的会随机使用其中一个。
myblog/deployment/svc-myblog-nodeport.yaml
apiVersion: v1
kind: Service
metadata:
name: myblog-np
namespace: luffy
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8002
selector:
app: myblog
type: NodePort
查看并访问服务:
$ kd create -f svc-myblog-nodeport.yaml
service/myblog-np created
$ kd get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.99.174.93 80/TCP 102m
myblog-np NodePort 10.105.228.101 80:30647/TCP 4s
mysql ClusterIP 10.108.214.84 3306/TCP 77m
#集群内每个节点的NodePort端口都会进行监听
$ curl 172.21.51.143:30647/blog/index/
我的博客列表
$ curl 172.21.51.143:30647/blog/index/
我的博客列表
## 浏览器访问
思考:
NodePort的端口监听如何转发到对应的Pod服务?
CLUSTER-IP为虚拟IP,集群内如何通过虚拟IP访问到具体的Pod服务?
运行在每个节点上,监听 API Server 中服务对象的变化,再通过创建流量路由规则来实现网络的转发。参照
有三种模式:
IPtables模式示意图:
$ iptables-save |grep -v myblog-np|grep "luffy/myblog"
-A KUBE-SERVICES ! -s 10.244.0.0/16 -d 10.99.174.93/32 -p tcp -m comment --comment "demo/myblog: cluster IP" -m tcp --dport 80 -j KUBE-MARK-MASQ
-A KUBE-SERVICES -d 10.99.174.93/32 -p tcp -m comment --comment "demo/myblog: cluster IP" -m tcp --dport 80 -j KUBE-SVC-WQNGJ7YFZKCTKPZK
$ iptables-save |grep KUBE-SVC-WQNGJ7YFZKCTKPZK
-A KUBE-SVC-WQNGJ7YFZKCTKPZK -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-GB5GNOM5CZH7ICXZ
-A KUBE-SVC-WQNGJ7YFZKCTKPZK -j KUBE-SEP-7GWC3FN2JI5KLE47
$ iptables-save |grep KUBE-SEP-GB5GNOM5CZH7ICXZ
-A KUBE-SEP-GB5GNOM5CZH7ICXZ -p tcp -m tcp -j DNAT --to-destination 10.244.1.158:8002
$ iptables-save |grep KUBE-SEP-7GWC3FN2JI5KLE47
-A KUBE-SEP-7GWC3FN2JI5KLE47 -p tcp -m tcp -j DNAT --to-destination 10.244.1.159:8002
面试题: k8s的Service Cluster-IP能不能ping通
在kube-proxy的iptables模式是不能ping通,此ip没有网卡,是一个虚拟ip,只是通过iptables规则来做转发的,没有规则去处理ICMP协议,在IPVS模式下可以ping通,所有的clusterIp会被设置在node上的kube-ipvs0的虚拟网卡上,这个时候去ping是可以通的。
简单来说:在kube-proxy的iptables模式下,这个ip是一个虚拟ip,没绑定网卡,只是通过iptables规则来做转发的,没有对ICMP的包做处理。在IPVS模式下可以平台,所有的clusterip会被绑定在node上的kube-ipvs0的虚拟网卡上,所以它可以ping通。
iptables转换ipvs模式
# 内核开启ipvs模块,集群各节点都执行
cat > /etc/sysconfig/modules/ipvs.modules <#!/bin/bash
ipvs_modules="ip_vs ip_vs_lc ip_vs_wlc ip_vs_rr ip_vs_wrr ip_vs_lblc ip_vs_lblcr ip_vs_dh ip_vs_sh ip_vs_nq ip_vs_sed ip_vs_ftp nf_conntrack_ipv4"
for kernel_module in \${ipvs_modules}; do
/sbin/modinfo -F filename \${kernel_module} > /dev/null 2>&1
if [ $? -eq 0 ]; then
/sbin/modprobe \${kernel_module}
fi
done
EOF
chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules && lsmod | grep ip_vs
# 安装ipvsadm工具
$ yum install ipset ipvsadm -y
# 修改kube-proxy 模式
$ kubectl -n kube-system edit cm kube-proxy
...
kind: KubeProxyConfiguration
metricsBindAddress: ""
mode: "ipvs"
nodePortAddresses: null
oomScoreAdj: null
...
# 重建kube-proxy
$ kubectl -n kube-system get po |grep kube-proxy|awk '{print $1}'|xargs kubectl -n kube-system delete po
# 查看日志,确认使用了ipvs模式
$ kubectl -n kube-system logs -f kube-proxy-ft6n6
I0605 08:47:52.334298 1 node.go:136] Successfully retrieved node IP: 172.21.51.143
I0605 08:47:52.334430 1 server_others.go:142] kube-proxy node IP is an IPv4 address (172.21.51.143), assume IPv4 operation
I0605 08:47:52.766314 1 server_others.go:258] Using ipvs Proxier.
...
# 清理iptables规则
$ iptables -F -t nat
$ iptables -F
# 查看规则生效
$ ipvsadm -ln
对于Kubernetes的Service,无论是Cluster-Ip和NodePort均是四层的负载,集群内的服务如何实现七层的负载均衡,这就需要借助于Ingress,Ingress控制器的实现方式有很多,比如nginx, Contour, Haproxy, trafik, Istio。几种常用的ingress功能对比和选型可以参考这里
Ingress-nginx是7层的负载均衡器 ,负责统一管理外部对k8s cluster中Service的请求。主要包含:
ingress-nginx-controller:根据用户编写的ingress规则(创建的ingress的yaml文件),动态的去更改nginx服务的配置文件,并且reload重载使其生效(是自动化的,通过lua脚本来实现);
Ingress资源对象:将Nginx的配置抽象成一个Ingress对象
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-wildcard-host
spec:
rules:
- host: "foo.bar.com"
http:
paths:
- pathType: Prefix
path: "/bar"
backend:
service:
name: service1
port:
number: 80
- host: "bar.foo.com"
http:
paths:
- pathType: Prefix
path: "/foo"
backend:
service:
name: service2
port:
number: 80
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
1)ingress controller通过和kubernetes api交互,动态的去感知集群中ingress规则变化
2)然后读取ingress规则(规则就是写明了哪个域名对应哪个service),按照自定义的规则,生成一段nginx配置
3)再写到nginx-ingress-controller的pod里,这个Ingress controller的pod里运行着一个Nginx服务,控制器把生成的nginx配置写入/etc/nginx/nginx.conf文件中
4)然后reload一下使配置生效。以此达到域名分别配置和动态更新的问题。
官方文档
$ wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/mandatory.yaml
## 或者使用myblog/deployment/ingress/mandatory.yaml
## 修改部署节点
$ grep -n5 nodeSelector mandatory.yaml
212- spec:
213- hostNetwork: true #添加为host模式
214- # wait up to five minutes for the drain of connections
215- terminationGracePeriodSeconds: 300
216- serviceAccountName: nginx-ingress-serviceaccount
217: nodeSelector:
218- ingress: "true" #替换此处,来决定将ingress部署在哪些机器
219- containers:
220- - name: nginx-ingress-controller
221- image: quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0
222- args:
创建ingress
# 为k8s-master节点添加label
$ kubectl label node k8s-master ingress=true
$ kubectl apply -f mandatory.yaml
使用示例:myblog/deployment/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myblog
namespace: luffy
spec:
rules:
- host: myblog.luffy.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myblog
port:
number: 80
ingress-nginx动态生成upstream配置:
$ kubectl -n ingress-nginx exec -ti nginx-ingress-xxxxxxx bash
# ps aux
# cat /etc/nginx/nginx.conf|grep myblog -A10 -B1
...
## start server myblog.luffy.com
server {
server_name myblog.luffy.com ;
listen 80 ;
listen [::]:80 ;
listen 443 ssl http2 ;
listen [::]:443 ssl http2 ;
set $proxy_upstream_name "-";
ssl_certificate_by_lua_block {
certificate.call()
}
location / {
set $namespace "luffy";
set $ingress_name "myblog";
set $service_name "myblog";
set $service_port "80";
set $location_path "/";
rewrite_by_lua_block {
lua_ingress.rewrite({
force_ssl_redirect = false,
ssl_redirect = true,
force_no_ssl_redirect = false,
use_port_in_redirects = false,
})
--
balancer.log()
monitor.call()
plugins.run()
}
port_in_redirect off;
set $balancer_ewma_score -1;
set $proxy_upstream_name "luffy-myblog-80";
set $proxy_host $proxy_upstream_name;
set $pass_access_scheme $scheme;
set $pass_server_port $server_port;
set $best_http_host $http_host;
set $pass_port $pass_server_port;
set $proxy_alternative_upstream_name "";
--
proxy_next_upstream_timeout 0;
proxy_next_upstream_tries 3;
proxy_pass http://upstream_balancer;
proxy_redirect off;
}
}
## end server myblog.luffy.com
...
注
[root@k8s-master week2]# kubectl -n ingress-nginx get po
NAME READY STATUS RESTARTS AGE
nginx-ingress-controller-66bff489bb-tktqc 1/1 Running 0 178m
[root@k8s-master week2]# kubectl -n ingress-nginx exec -ti nginx-ingress-controller-66bff489bb-tktqc -- bash
bash-5.0$ ps aux
PID USER TIME COMMAND
1 www-data 0:00 /usr/bin/dumb-init -- /nginx-ingress-controller --configmap=ingress-nginx/nginx-configura
7 www-data 1:34 /nginx-ingress-controller --configmap=ingress-nginx/nginx-configuration --tcp-services-co
39 www-data 0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /etc/nginx/nginx.conf
1154 www-data 0:00 nginx: worker process
1155 www-data 0:00 nginx: worker process
1156 www-data 0:00 nginx: worker process
1298 www-data 0:00 nginx: cache manager process
1689 www-data 0:00 bash
1696 www-data 0:00 ps aux
[root@k8s-master week2]# kubectl -n luffy describe ing myblog
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
Name: myblog
Namespace: luffy
Address:
Default backend: default-http-backend:80 ("default-http-backend" not found>)
Rules:
Host Path Backends
---- ---- --------
myblog.luffy.com
/ myblog:80 (10.244.0.7:8002,10.244.1.6:8002)
Annotations:
Events:
域名解析服务,将 myblog.luffy.com
解析到ingress的地址上。ingress是支持多副本的,高可用的情况下,生产的配置是使用lb服务(内网F5设备,公网elb、slb、clb,解析到各ingress的机器,如何域名指向lb地址)
本机,添加如下hosts记录来演示效果。
10.0.1.5 myblog.luffy.com
然后,访问 http://myblog.luffy.com/blog/index/
HTTPS访问:
#自签名证书
$ openssl req -x509 -nodes -days 2920 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/CN=*.luffy.com/O=ingress-nginx"
# 证书信息保存到secret对象中,ingress-nginx会读取secret对象解析出证书加载到nginx配置中
$ kubectl -n luffy create secret tls tls-myblog --key tls.key --cert tls.crt
注
[root@k8s-master 2021]# mkdir cert && cd cert
[root@k8s-master cert]# openssl req -x509 -nodes -days 2920 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/CN=*.luffy.com/O=ingress-nginx"
Generating a 2048 bit RSA private key
..................................................................................+++
...................................................................................................................+++
writing new private key to 'tls.key'
-----
[root@k8s-master cert]# kubectl -n luffy create secret tls tls-myblog --key tls.key --cert tls.crt
secret/tls-myblog created
# 若是购买的整数,可以直接执行第二步
[root@k8s-master 2021]# kubectl -n luffy get secrets
NAME TYPE DATA AGE
default-token-h9fbc kubernetes.io/service-account-token 3 5h22m
myblog Opaque 2 5h2m
tls-myblog kubernetes.io/tls 2 4m44s
修改yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myblog
namespace: luffy
spec:
rules:
- host: myblog.luffy.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myblog
port:
number: 80
tls:
- hosts:
- myblog.luffy.com
secretName: tls-myblog
注:
复制上面的yaml文件
[root@k8s-master week2]# vim ingress.yaml
[root@k8s-master week2]# kubectl create -f ingress.yaml
ingress.networking.k8s.io/myblog created
然后,访问 https://myblog.luffy.com/blog/index/
多path转发示例:
目标:
myblog.luffy.com -> 172.21.51.143 -> /foo/aaa service1:4200/foo/aaa
/bar service2:8080
/ myblog:80/
实现:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: simple-fanout-example
namespace: luffy
spec:
rules:
- host: myblog.luffy.com
http:
paths:
- path: /foo
pathType: Prefix
backend:
service:
name: service1
port:
number: 4200
- path: /bar
pathType: Prefix
backend:
service:
name: service2
port:
number: 8080
- path: / # 相当于默认,逐条匹配
pathType: Prefix
backend:
service:
name: myblog
port:
number: 80
注: 演示多路径转发效果
# 复制上面内容,创建
[root@k8s-master week2]# vim ingress-2.yaml
[root@k8s-master week2]# kubectl create -f ingress-2.yaml
ingress.networking.k8s.io/simple-fanout-example created
[root@k8s-master week2]# kubectl -n luffy get ing
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
NAME CLASS HOSTS ADDRESS PORTS AGE
myblog myblog.luffy.com 80 3h6m
simple-fanout-example myblog.luffy.com 80 10s
# 查看describe
[root@k8s-master week2]# kubectl -n luffy describe ing simple-fanout-example
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
Name: simple-fanout-example
Namespace: luffy
Address:
Default backend: default-http-backend:80 ("default-http-backend" not found>)
Rules:
Host Path Backends
---- ---- --------
myblog.luffy.com
/foo service1:4200 ("service1" not found>)
/bar service2:8080 ("service2" not found>) # 没有这个服务所有提示not found
/ myblog:80 (10.244.0.7:8002,10.244.1.6:8002)
Annotations:
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal CREATE 87s nginx-ingress-controller Ingress luffy/simple-fanout-example
nginx的URL重写
目标:
nginx.luffy.com -> 172.21.51.143 -> /api/v1 -> nginx-v1 service
/api/v2 -> nginx-v2 service
实现:
$ cat nginx-v1-dpl.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-v1
namespace: luffy
spec:
replicas: 1
selector:
matchLabels:
app: nginx-v1
template:
metadata:
labels:
app: nginx-v1
spec:
containers:
- image: nginx:alpine
name: nginx-v1
command: ["/bin/sh", "-c", "echo 'this is nginx-v1'>/usr/share/nginx/html/index.html;nginx -g 'daemon off;'"]
$ cat nginx-v1-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-v1
namespace: luffy
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: nginx-v1
type: ClusterIP
# 创建nginx-v2
$ kubectl apply -f .
$ cat ingress-rewrite.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx-rewrite
namespace: luffy
annotations: # 声明nginx的URL重写规则
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: nginx.luffy.com
http:
paths:
- path: /api/v1/(.*)
pathType: Prefix
backend:
service:
name: nginx-v1
port:
number: 80
- path: /api/v2/(.*)
pathType: Prefix
backend:
service:
name: nginx-v2
port:
number: 80
# 访问测试
$ http://nginx.luffy.com/api/v1/
$ http://nginx.luffy.com/api/v2/
操作如下:
v1:
[root@k8s-master 2021]# mkdir rewrite
[root@k8s-master 2021]# cd rewrite/
[root@k8s-master rewrite]# vim nginx-v1-dpl.yaml
[root@k8s-master rewrite]# kubectl create -f nginx-v1-dpl.yaml
deployment.apps/nginx-v1 created
[root@k8s-master rewrite]# vim nginx-v1-svc.yaml
[root@k8s-master rewrite]# kubectl create -f nginx-v1-svc.yaml
service/nginx-v1 created
[root@k8s-master rewrite]# kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog-5d9b76df88-85k24 1/1 Running 0 5h15m
myblog-5d9b76df88-t26t4 1/1 Running 0 5h16m
mysql-7446f4dc7b-7kpj8 1/1 Running 0 5h16m
nginx-v1-56df8b47c4-9mw2t 1/1 Running 0 82s
[root@k8s-master rewrite]# kubectl -n luffy get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.108.7.69 80/TCP 140m
mysql ClusterIP 10.107.191.182 3306/TCP 5h11m
nginx-v1 ClusterIP 10.102.163.132 80/TCP 43s
[root@k8s-master rewrite]# curl 10.102.163.132:80
this is nginx-v1
v2:
[root@k8s-master rewrite]# ls
nginx-v1-dpl.yaml nginx-v1-svc.yaml
[root@k8s-master rewrite]# sed -i 's/nginx-v1/nginx-v2/g' *
[root@k8s-master rewrite]# kubectl apply -f .
deployment.apps/nginx-v2 created
service/nginx-v2 created
[root@k8s-master rewrite]# kubectl -n luffy get po
NAME READY STATUS RESTARTS AGE
myblog-5d9b76df88-85k24 1/1 Running 0 5h18m
myblog-5d9b76df88-t26t4 1/1 Running 0 5h19m
mysql-7446f4dc7b-7kpj8 1/1 Running 0 5h19m
nginx-v1-56df8b47c4-9mw2t 1/1 Running 0 4m23s
nginx-v2-6f967c65cf-xslj5 1/1 Running 0 33s
[root@k8s-master rewrite]# kubectl -n luffy get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
myblog ClusterIP 10.108.7.69 80/TCP 143m
mysql ClusterIP 10.107.191.182 3306/TCP 5h13m
nginx-v1 ClusterIP 10.102.163.132 80/TCP 3m26s
nginx-v2 ClusterIP 10.103.90.95 80/TCP 43s
[root@k8s-master rewrite]# curl 10.103.90.95:80
this is nginx-v2
[root@k8s-master rewrite]# vim ingress-rewrite.yaml
[root@k8s-master rewrite]# kubectl create -f ingress-rewrite.yaml
ingress.networking.k8s.io/nginx-rewrite created
[root@k8s-master rewrite]# kubectl -n luffy describe ing nginx-rewrite
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
Name: nginx-rewrite
Namespace: luffy
Address:
Default backend: default-http-backend:80 ("default-http-backend" not found>)
Rules:
Host Path Backends
---- ---- --------
nginx.luffy.com
/api/v1/(.*) nginx-v1:80 (10.244.2.6:80)
/api/v2/(.*) nginx-v2:80 (10.244.1.7:80)
Annotations: nginx.ingress.kubernetes.io/rewrite-target: /$1
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal CREATE 33s nginx-ingress-controller Ingress luffy/nginx-rewrite
# 添加hosts文件解析 10.0.1.5 nginx.luffy.com
# 访问:
http://nginx.luffy.com/api/v1/
http://nginx.luffy.com/api/v2/