一、Kubeadm方式部署
1、配置hosts
cat >> /etc/hosts << EOF
192.168.140.129 master
192.168.140.130 node1
192.168.140.131 node2
185.199.109.133 raw.githubusercontent.com
EOF
2、关闭交换分区(swap)
[root@master ~]# swapoff -a # 临时关闭
[root@master ~]# sed -ri 's/.*swap.*/#&/' /etc/fstab # 永久关闭,需要重启才生效
3、修改内核参数
# 加载 br_netfilter 模块
[root@master ~]# modprobe br_netfilter
# 验证模块是否加载成功:
[root@master ~]# lsmod |grep br_netfilter
# 修改内核参数
cat > /etc/sysctl.d/k8s.conf <<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF
# 使修改的内核参数生效
[root@master ~]# sysctl -p /etc/sysctl.d/k8s.conf
4、安装iptables(可选)
[root@master ~]# yum install iptables-services -y
#禁用 iptables
[root@master ~]# service iptables stop && systemctl disable iptables
#清空防火墙规则
[root@master ~]# iptables -F
5、安装和配置docker
[root@master ~]# wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
[root@master ~]# yum -y install docker-ce-20.10.9-3.el7
[root@master ~]# systemctl enable --now docker && systemctl status docker
# 指定镜像仓库,并修改docker文件驱动为systemd,默认为cgroupfs,kubelet默认使用systemd,两者必须一致才可以
cat > /etc/docker/daemon.json << EOF
{
"registry-mirrors": ["https://b9pmyelo.mirror.aliyuncs.com","https://rsbud4vc.mirror.aliyuncs.com","https://registry.docker-cn.com","https://docker.mirrors.ustc.edu.cn","https://dockerhub.azk8s.cn","http://hub-mirror.c.163.com","http://qtid6917.mirror.aliyuncs.com", "https://rncxm540.mirror.aliyuncs.com"],
"exec-opts": ["native.cgroupdriver=systemd"]
}
EOF
[root@master ~]# systemctl daemon-reload && systemctl restart docker && systemctl status docker
6、配置k8s yum源
cat > /etc/yum.repos.d/kubernetes.repo << EOF
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF
7、安装k8s组件(master,node都要装)
[root@master ~]# yum install -y kubelet-1.23.3 kubeadm-1.23.3 kubectl-1.23.3
启动kubelet服务
[root@master ~]# systemctl enable --now kubelet以上步骤所有节点都需要执行
8、在master上执行初始化
kubeadm init \
--apiserver-advertise-address=[master_IP] \
--image-repository registry.aliyuncs.com/google_containers \
--kubernetes-version v1.23.3 \
--service-cidr=10.96.0.0/12 \
--pod-network-cidr=10.244.0.0/16
9、node节点执行kubectl get nodes报错:
[root@node ~]# kubectl get nodes
The connection to the server localhost:8080 was refused - did you specify the right host or port?
原因:
kubectl命令需要使用kubernetes-admin来运行,需要admin.conf文件(conf文件是通过“ kubeadmin init”命令在主节点/etc/kubernetes 中创建),但是从节点没有conf文件,也没有设置 KUBECONFIG =/root/admin.conf环境变量,所以需要复制conf文件到从节点,并设置环境变量就OK了
解决方法:
[root@node ~]# scp root@master:/etc/kubernetes/admin.conf /etc/kubernetes/
[root@node ~]# mkdir -p $HOME/.kube
[root@node ~]# cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@node ~]# chown $(id -u):$(id -g) $HOME/.kube/config
[root@node ~]# export KUBECONFIG=/etc/kubernetes/admin.conf
10、配置NetworkManager
[root@master ~]# cat > /etc/NetworkManager/conf.d/calico.conf <<EOF
[keyfile]
unmanaged-devices=interface-name:cali*;interface-name:tunl*;interface-name:vxlan.calico;interface-name:wireguard.cali
EOF
11、安装calico组件
[root@master ~]# wget --no-check-certificate https://docs.projectcalico.org/manifests/calico.yaml
[root@master ~]# sed -i 's#docker.io/##g' calico.yaml
[root@master ~]# kubectl apply -f calico.yaml
12、calico官方安装方法
# 安装tigera-operator
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/tigera-operator.yaml
# 安装calico
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/custom-resources.yaml注意:安全完calico网络组件后,节点状态才会由NotReady变为Ready
13、安装rancher dashboard
docker run --privileged -d --restart=unless-stopped -p 80:80 -p 443:443 rancher/rancher
查看join命令在master上执行
kubeadm token create --print-join-command
二、Sealos方式部署K8S
1、下载并解压sealos
tar zxvf sealos_4.1.3_linux_amd64.tar.gz
cp sealos /usr/bin/
2、导入镜像,只在节点master1上导入即可
sealos load -i /app/k8s-1.21/k8s-1.21.0.tar
sealos load -i /app/k8s-1.21/calico-3.22.1.tar
3、部署k8s集群
方式一:
# 生成集群部署文件
sealos gen labring/kubernetes:v1.21.0 labring/calico:v3.22.1 \
--masters x.x.x.x,x.x.x.x \
--nodes x.x.x.x,x.x.x.x \
--passwd 'password' > Clusterfile
# 开始部署集群
sealos apply -f /root/Clusterfile
方式二:
sealos run labring/kubernetes:v1.21.0 labring/calico:v3.22.1 \
--masters x.x.x.x,x.x.x.x \
--nodes x.x.x.x,x.x.x.x \
-p 'password'
4、查看node节点状态,Ready为正常
kubectl get nodes -o wide
5、去除节点的污点,否则pod不调度到有污点标记的节点
kubectl describe node NODE_NAME | grep Taint # 查看节点是否有污点
kubectl taint node NODE_NAME node-role.kubernetes.io/master:NoSchedule # 在节点上增加污点
kubectl taint node NODE_NAME node-role.kubernetes.io/master:NoSchedule- # 去掉节点污点
kubectl taint node master1 node-role.kubernetes.io/master:NoSchedule-
kubectl taint node node1 node-role.kubernetes.io/master:NoSchedule-
6、重启coredns
kubectl rollout restart deploy coredns -n kube-system
7、修改internal-ip,在KUBELET_EXTRA_ARGS参数的最后加上node节点eth1的IP地址
vim /var/lib/kubelet/kubelet-flags.env
KUBELET_EXTRA_ARGS="--pod-infra-container-image=k8s.gcr.io/pause:3.4.1 --container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --image-service-endpoint=unix:///var/run/image-cri-shim.sock --node-ip=x.x.x.x"
#重启kubelet服务
systemctl daemon-reload
systemctl restart kubelet
#确认k8s集群节点的internal-ip是否已经修改
kubectl get nodes -o wide
8、sealos常用命令
添加节点
sealos add --masters x.x.x.x --nodes x.x.x.x
sealos add --masters x.x.x.x-x.x.x.x --nodes x.x.x.x-x.x.x.x
删除节点
sealos delete --nodes x.x.x.x
sealos delete --masters x.x.x.x --nodes x.x.x.x
清理集群
sealos reset
三、K8S常用yaml配置文件
![](https://i-blog.csdnimg.cn/blog_migrate/b8897c79b81124a819b01b8e11ddab9d.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/b089d61e6d7c6779aaf6835ae000670e.gif)
# yaml格式的pod文件完整内容:
apiVersion: v1 #必选,版本号,例如v1
kind: Pod #必选,指定创建资源的角色/类型
metadata: #必选,资源的元数据/属性
name: string #必选,资源的名字,在同一个namespace中必须唯一
namespace: string #必选,Pod所属的命名空间
labels: #自定义标签,使这个标签在service网络中备案,以便被获知
- name: string #自定义标签名字
annotations: #设置自定义注解列表
- name: string #设置自定义注解名字
spec: #必选,设置该资源的详细定义
nodeName: k8s-node01 # 指定节点名称,该参数会将pod部署到指定的node节点
containers: #必选,Pod中容器列表
- name: string #必选,容器名称
image: string #必选,容器的镜像名称
imagePullPolicy: [Always | Never | IfNotPresent] #获取镜像的策略 Alawys表示下载镜像 IfnotPresent表示优先使用本地镜像,否则下载镜像,Nerver表示仅使用本地镜像
command: [string] #容器的启动命令列表,如不指定,使用打包时使用的启动命令
args: [string] #容器的启动命令参数列表
workingDir: string #容器的工作目录
volumeMounts: #挂载到容器内部的存储卷配置
- name: string #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名
mountPath: string #存储卷在容器内mount的绝对路径,应少于512字符
readOnly: boolean #是否为只读模式
ports: #需要暴露的端口库号列表
- name: string #端口号名称
containerPort: int #容器需要监听的端口号
hostPort: int #容器所在主机需要监听的端口号,默认与Container相同
protocol: string #端口协议,支持TCP和UDP,默认TCP
env: #容器运行前需设置的环境变量列表
- name: string #环境变量名称
value: string #环境变量的值
resources: #资源限制和请求的设置
limits: #资源限制的设置
cpu: string #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数
memory: string #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数
requests: #资源请求的设置
cpu: string #Cpu请求,容器启动的初始可用数量
memory: string #内存清楚,容器启动的初始可用数量
livenessProbe: #对Pod内个容器健康检查的设置,当探测无响应几次后将自动重启该容器,检查方法有exec、httpGet和tcpSocket,对一个容器只需设置其中一种方法即可
exec: #对Pod容器内检查方式设置为exec方式
command: [string] #exec方式需要制定的命令或脚本
httpGet: #对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port
path: string
port: number
host: string
scheme: string
HttpHeaders:
- name: string
value: string
tcpSocket: #对Pod内个容器健康检查方式设置为tcpSocket方式
port: number
initialDelaySeconds: 0 #容器启动完成后首次探测的时间,单位为秒
timeoutSeconds: 0 #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒
periodSeconds: 0 #对容器监控检查的定期探测时间设置,单位秒,默认10秒一次
successThreshold: 0
failureThreshold: 0
securityContext:
privileged:false
restartPolicy: [Always | Never | OnFailure]#Pod的重启策略,Always表示一旦不管以何种方式终止运行,kubelet都将重启,OnFailure表示只有Pod以非0退出码退出才重启,Nerver表示不再重启该Pod
nodeSelector: obeject #设置NodeSelector表示将该Pod调度到包含这个label的node上,以key:value的格式指定
imagePullSecrets: #Pull镜像时使用的secret名称,以key:secretkey格式指定
- name: string
hostNetwork:false #是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络
volumes: #在该pod上定义共享存储卷列表
- name: string #共享存储卷名称 (volumes类型有很多种)
emptyDir: {} #类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值
hostPath: string #类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录
path: string #Pod所在宿主机的目录,将被用于同期中mount的目录
secret: #类型为secret的存储卷,挂载集群与定义的secre对象到容器内部
scretname: string
items:
- key: string
path: string
configMap: #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部
name: string
items:
- key: string
path: string
![](https://i-blog.csdnimg.cn/blog_migrate/50441060453f2b8724d234bf669bf07a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/653e10613ef6b81043458d95184db2df.gif)
# yaml格式的Deployment文件完整内容:
apiVersion: extensions/v1beta1
kind: Deployment
metadata: ----------------------------------------#元数据
annotations: -------------------------------------#注释信息
deployment.kubernetes.io/revision: '1'
k8s.kuboard.cn/ingress: 'false'
k8s.kuboard.cn/service: NodePort
k8s.kuboard.cn/workload: nextcloud
labels:-------------------------------------------#标签信息
k8s.kuboard.cn/layer: ''
k8s.kuboard.cn/name: nextcloud
name: nextcloud-----------------------------------#名称
namespace: nextcloud------------------------------#命名空间
spec:-----------------------------------------------#定义容器模板,该模板可以包含多个容器
replicas: 3---------------------------------------#副本数量
selector:-----------------------------------------#标签选择器
matchLabels:
k8s.kuboard.cn/layer: ''
k8s.kuboard.cn/name: nextcloud
strategy:-----------------------------------------#滚动升级策略
type: RollingUpdate-----------------------------#类型
rollingUpdate:----------------------------------#由于replicas为3,则整个升级,pod个数在2-4个之间
maxSurge: 25%---------------------------------#滚动升级时会先启动25%pod
maxUnavailable: 25%---------------------------#滚动升级时允许的最大Unavailable的pod个数
template: #镜像模板
metadata: ------------------------------------#元数据
labels:---------------------------------------#标签
k8s.kuboard.cn/layer: ''
k8s.kuboard.cn/name: nextcloud
spec: ------------------------------------------#定义容器模板,该模板可以包含多个容器
containers: ----------------------------------#容器信息
- name: nextcloud --------------------------#容器名称
image: '172.16.20.100/library/nextcloud:yan' #镜像名称
imagePullPolicy: Always ------------------#镜像下载策略
ports:
- name: http
containerPort: 80
protocol: TCP
env
resources: -------------------------------#CPU内存限制
limits: --------------------------------#限制cpu内存
cpu: 200m
memory: 200m
requests: ------------------------------#请求cpu内存
cpu: 100m
memory: 100m
securityContext: -------------------------#安全设定
privileged: true -----------------------#开启享有特权
volumeMounts: ----------------------------#挂载volumes中定义的磁盘
- name: html ---------------------------#挂载容器1
mountPath: /var/www/html
- name: session ------------------------#挂载容器1
mountPath: /var/lib/php/session
volumes: ------------------------------------#在该pod上定义共享存储卷列表
- name: html -------------------------------#共享存储卷名称 (volumes类型有很多种)
persistentVolumeClaim: -------------------#volumes类型为pvc
claimName: html -----------------------#关联pvc名称
- name: session
persistentVolumeClaim:
claimName: session
restartPolicy: Always ------------------------#Pod的重启策略
#Always表示一旦不管以何种方式终止运行,kubelet都将重启,
#OnFailure表示只有Pod以非0退出码退出才重启,
#Nerver表示不再重启该Pod
schedulerName: default-scheduler -------------#指定pod调度到节点
![](https://i-blog.csdnimg.cn/blog_migrate/c18a9f9e6c96558013309cb6cdf69a90.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6e451380015d2607c6e6832c90a40065.gif)
# yaml格式的Service文件完整内容:
apiVersion: v1
kind: Service
metadata: ---------------------------------#元数据
annotations: -----------------------------#注释信息
k8s.kuboard.cn/workload: nextcloud
labels: ----------------------------------#标签信息
k8s.kuboard.cn/layer: ''
k8s.kuboard.cn/name: nextcloud
name: nextcloud --------------------------#名称
namespace: nextcloud ---------------------#命名空间
spec: --------------------------------------#定义Service模板
clusterIP: 10.0.181.206 ------------------#指定svcip地址 不指定则随机
=================================================================================================
#NodePort类型:集群外网络
type: NodePort ---------------------------#类型为NodePort
ports:
- name: mnwwwp
nodePort: 30001 ----------------------#当type = NodePort时,指定映射到物理机的端口号
port: 80 -----------------------------#服务监听的端口号
protocol: TCP ------------------------#端口协议,支持TCP和UDP,默认TCP
targetPort: 80 -----------------------#需要转发到后端Pod的端口号
==================================================================================================
#ClusterIP类型: 集群内网络
type: ClusterIP --------------------------#
ports:
- name: mnwwwp
port: 80
protocol: TCP
targetPort: 80
- name: j5smwx
port: 22
protocol: TCP
targetPort: 22
selector: -------------------------------#label selector配置,将选择具有label标签的Pod作为管理
k8s.kuboard.cn/layer: ''
k8s.kuboard.cn/name: nextcloud
sessionAffinity: None --------------------#是否支持session
四、K8S常用命令
# kubectl cp命令只支持从本地复制到Pod或从Pod复制到本地,不支持直接在两个Pod之间复制文件
kubectl cp <namespace>/<pod-name>:/var/logs/app.log /tmp/app.log
# 进入pod
kubectl -n [namespace] exec -it [podname] -- /bin/bash
参考链接:
https://asciinema.org/ # 终端录制,安装前需要安装epel源
https://zhuanlan.zhihu.com/p/625125823
https://zhuanlan.zhihu.com/p/639042196
https://www.cnblogs.com/shuiyao3/p/17290271.html
https://www.cnblogs.com/fengdejiyixx/p/16576021.html
https://blog.csdn.net/ma_jiang/article/details/124962352 # K8S Calico网络插件
https://docs.tigera.io/calico/latest/getting-started/kubernetes/quickstart # 官网calico安装
https://sealos.io/docs/lifecycle-management/quick-start/
https://blog.csdn.net/xiaoliizi/article/details/126998976 # 使用sealos部署k8s集群
https://github.com/wheatMr/sealos
https://github.com/labring/sealos
https://github.com/KubeOperator/KubeOperator
https://icloudnative.io/posts/kubesphere/
https://www.kubesphere.io/zh/docs/v3.3/quick-start/all-in-one-on-linux/ #在linux上安装Kubernetes和KubeSphere
https://blog.csdn.net/qq_25775675/article/details/121671679 # Kubernetes调度器-固定节点
https://support.huaweicloud.com/function-cce/index.html # k8s介绍
https://www.cnblogs.com/zoujiaojiao/p/17021724.html # k8s中使用nsenter命令进入容器网络命名空间