从0到1!Ubuntu上搭建Kubernetes Cluster
创始人
2025-05-28 10:59:40

目录

一、环境准备

二、初始化工作

1. 设置root用户密码

 2. 使用xshell连接三台主机

 3. 设置主机名和修改hosts文件

4. 安装依赖软件以及关闭停用不需要使用的软件

5. 时间的同步与时区设置

6. 关闭swap分区

7. 在 kube-proxy 开启并使用 ipvs

8. 集群各主机节点内核Kernel参数的调整

三、安装docker和k8s

1. 各个节点安装docker

2. 下载 kubernetes 集群相关的软件包

四、初始化集群

1. 在主节点上初始化集群

2. 配置 kubectl

3. 安装Pod网络

4. 添加k8s-node1和k8s-node2


一、环境准备

Ubuntu镜像下载地址:Index of /ubuntu-releases/20.04/ | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror

使用VMware安装三个节点,一个作为master主节点,如下:

注意每个节点内存不少于2G,CPU不少于2个,内存30GB以上

名字IP
k8s-master192.168.65.145
k8s-node1192.168.65.142
k8s-node2192.168.65.141

本博客安装版本说明:

k8s版本:1.19.10

docker版本:19.03 

二、初始化工作

1. 设置root用户密码

zy@ubuntu:~/Desktop$ sudo passwd root
[sudo] password for zy: 
New password: 
Retype new password: 
passwd: password updated successfully

 2. 使用xshell连接三台主机

 3. 设置主机名和修改hosts文件

hostnamectl set-hostname k8s-master  #master节点上执行
hostnamectl set-hostname k8s-node1   #ndoe1节点上执行
hostnamectl set-hostname k8s-node2   #node2节点上执行

在 /etc/hosts文件后面添加:

192.168.65.145 k8s-master
192.168.65.142 k8s-node1
192.168.65.141 k8s-node2

4. 安装依赖软件以及关闭停用不需要使用的软件

 卸载系统中自带的 snapd 软件

systemctl stop snapd snapd.socket 
apt autoremove --purge -y snapd 
apt install -y linux-modules-extra-5.4.0-52-generic linux-headers-5.4.0-52

5. 时间的同步与时区设置

# 设置系统时区为中国/上海
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
timedatectl set-timezone Asia/Shanghai
bash -c "echo 'Asia/Shanghai' > /etc/timezone"
ntpdate ntp1.aliyun.com# 将当前的 UTC 时间写入硬件时钟
timedatectl set-local-rtc 0# 重启依赖于系统时间的服务
systemctl restart rsyslog.service cron.service# 查看系统时间
date -R

6. 关闭swap分区

swapoff -a && sed -i 's/^\/swap.img\(.*\)$/#\/swap.img \1/g' /etc/fstab && freeswapoff -a && sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

7. 在 kube-proxy 开启并使用 ipvs

# (1) 安装 ipvs 以及 负载均衡相关依赖
apt -y install ipvsadm ipset sysstat conntrack(2) ipvs 内核模块手动加载(所有节点配置)
mkdir ~/k8s-init/
tee ~/k8s-init/ipvs.modules <<'EOF'
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_lc
modprobe -- ip_vs_lblc
modprobe -- ip_vs_lblcr
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- ip_vs_dh
modprobe -- ip_vs_fo
modprobe -- ip_vs_nq
modprobe -- ip_vs_sed
modprobe -- ip_vs_ftp
modprobe -- ip_vs_sh
modprobe -- ip_tables
modprobe -- ip_set
modprobe -- ipt_set
modprobe -- ipt_rpfilter
modprobe -- ipt_REJECT
modprobe -- ipip
modprobe -- xt_set
modprobe -- br_netfilter
modprobe -- nf_conntrack
EOF# (3) 加载内核配置(临时|永久)注意管理员执行
chmod 755 ~/k8s-init/ipvs.modules && bash ~/k8s-init/ipvs.modules
sudo cp ~/k8s-init/ipvs.modules /etc/profile.d/ipvs.modules.sh
lsmod | grep -e ip_vs -e nf_conntrack

8. 集群各主机节点内核Kernel参数的调整

# 1.Kernel 参数调整
mkdir ~/k8s-init/cat > ~/k8s-init/kubernetes-sysctl.conf <

三、安装docker和k8s

1. 各个节点安装docker

# 1.更新apt包索引并安装包以允许apt在HTTPS上使用存储库
sudo apt-get install -y \apt-transport-https \ca-certificates \
curl \gnupg-agent \software-properties-common# 2.添加Docker官方GPG密钥 # -fsSL
curl https://download.docker.com/linux/ubuntu/gpg | apt-key add -# 3.通过搜索指纹的最后8个字符进行密钥验证
sudo apt-key fingerprint 0EBFCD88# 4.设置稳定存储库
sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \stable"# 5. 确保APT软件包索引已经更新
sudo apt update#6. 确认您要安装的Docker版本
root@ubuntu:~# apt-cache madison docker-cedocker-ce | 5:19.03.10~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packagesdocker-ce | 5:19.03.9~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages#7. 安装19.03版本
apt-get install docker-ce=5:19.03.12~3-0~ubuntu-focal docker-ce-cli=5:19.03.12~3-0~ubuntu-focal containerd.io#8. 检查docker版本
root@ubuntu:/etc/apt# docker -v
Docker version 19.03.12, build 48a66213fe#9.加速器建立
mkdir -vp /etc/docker/
sudo tee /etc/docker/daemon.json <<-'EOF'
{"registry-mirrors": ["https://xlx9erfu.mirror.aliyuncs.com"],"exec-opts": ["native.cgroupdriver=systemd"],"log-driver": "json-file","log-opts": {"max-size": "100m"},"live-restore": true,"dns": ["192.168.12.254"],"insecure-registries": ["harbor.weiyigeek.com.cn"]
}
EOF
# PS : 私有仓库配置 insecure_registries# 10.自启与启动
sudo systemctl enable --now docker 
sudo systemctl restart docker

2. 下载 kubernetes 集群相关的软件包

# (1) gpg 签名下载导入
curl https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo apt-key add -
# (2) Kubernetes 安装源
cat <

四、初始化集群

1. 在主节点上初始化集群

#apiserver-advertise-address 是master节点的地址
$ kubeadm init \
--apiserver-advertise-address=192.168.65.145 \
--image-repository registry.aliyuncs.com/google_containers \
--service-cidr=10.96.0.0/12 \
--pod-network-cidr=10.244.0.0/16

启动结果如下:

root@ubuntu:~# kubeadm init \
> --apiserver-advertise-address=192.168.65.145 \
> --image-repository registry.aliyuncs.com/google_containers \
> --service-cidr=10.96.0.0/12 \
> --pod-network-cidr=10.244.0.0/16
I0315 18:23:08.757810   35378 version.go:255] remote version is much newer: v1.26.2; falling back to: stable-1.19
W0315 18:23:09.853694   35378 configset.go:348] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
[init] Using Kubernetes version: v1.19.16
[preflight] Running pre-flight checks
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [k8s-master kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.65.145]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [k8s-master localhost] and IPs [192.168.65.145 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [k8s-master localhost] and IPs [192.168.65.145 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[kubelet-check] Initial timeout of 40s passed.
[apiclient] All control plane components are healthy after 74.004910 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.19" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node k8s-master as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node k8s-master as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: mj7yh1.kcsms343yksi1k8l
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to get nodes
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxyYour Kubernetes control-plane has initialized successfully!To start using your cluster, you need to run the following as a regular user:mkdir -p $HOME/.kubesudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/configsudo chown $(id -u):$(id -g) $HOME/.kube/configYou should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:https://kubernetes.io/docs/concepts/cluster-administration/addons/Then you can join any number of worker nodes by running the following on each as root:kubeadm join 192.168.65.145:6443 --token mj7yh1.kcsms343yksi1k8l \--discovery-token-ca-cert-hash sha256:06d33735dffa06b7de28e7837297fb982354f1667cc7d250e2a3dfdc468256cb 

2. 配置 kubectl

为用户zy配置kubectl:

su zy  
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

为了使用更便捷,启用kubectl命令的自动补全功能:

3. 安装Pod网络

root@k8s-master:~# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
The connection to the server raw.githubusercontent.com was refused - did you specify the right host or port?

我这里提示拒绝连接,可以把yaml文件弄到本地来安装:

文件内容如下:

---
kind: Namespace
apiVersion: v1
metadata:name: kube-flannellabels:pod-security.kubernetes.io/enforce: privileged
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:name: flannel
rules:
- apiGroups:- ""resources:- podsverbs:- get
- apiGroups:- ""resources:- nodesverbs:- get- list- watch
- apiGroups:- ""resources:- nodes/statusverbs:- patch
- apiGroups:- "networking.k8s.io"resources:- clustercidrsverbs:- list- watch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:name: flannel
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: flannel
subjects:
- kind: ServiceAccountname: flannelnamespace: kube-flannel
---
apiVersion: v1
kind: ServiceAccount
metadata:name: flannelnamespace: kube-flannel
---
kind: ConfigMap
apiVersion: v1
metadata:name: kube-flannel-cfgnamespace: kube-flannellabels:tier: nodeapp: flannel
data:cni-conf.json: |{"name": "cbr0","cniVersion": "0.3.1","plugins": [{"type": "flannel","delegate": {"hairpinMode": true,"isDefaultGateway": true}},{"type": "portmap","capabilities": {"portMappings": true}}]}net-conf.json: |{"Network": "10.244.0.0/16","Backend": {"Type": "vxlan"}}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:name: kube-flannel-dsnamespace: kube-flannellabels:tier: nodeapp: flannel
spec:selector:matchLabels:app: flanneltemplate:metadata:labels:tier: nodeapp: flannelspec:affinity:nodeAffinity:requiredDuringSchedulingIgnoredDuringExecution:nodeSelectorTerms:- matchExpressions:- key: kubernetes.io/osoperator: Invalues:- linuxhostNetwork: truepriorityClassName: system-node-criticaltolerations:- operator: Existseffect: NoScheduleserviceAccountName: flannelinitContainers:- name: install-cni-pluginimage: docker.io/flannel/flannel-cni-plugin:v1.1.2#image: docker.io/rancher/mirrored-flannelcni-flannel-cni-plugin:v1.1.2command:- cpargs:- -f- /flannel- /opt/cni/bin/flannelvolumeMounts:- name: cni-pluginmountPath: /opt/cni/bin- name: install-cniimage: docker.io/flannel/flannel:v0.21.3#image: docker.io/rancher/mirrored-flannelcni-flannel:v0.21.3command:- cpargs:- -f- /etc/kube-flannel/cni-conf.json- /etc/cni/net.d/10-flannel.conflistvolumeMounts:- name: cnimountPath: /etc/cni/net.d- name: flannel-cfgmountPath: /etc/kube-flannel/containers:- name: kube-flannelimage: docker.io/flannel/flannel:v0.21.3#image: docker.io/rancher/mirrored-flannelcni-flannel:v0.21.3command:- /opt/bin/flanneldargs:- --ip-masq- --kube-subnet-mgrresources:requests:cpu: "100m"memory: "50Mi"securityContext:privileged: falsecapabilities:add: ["NET_ADMIN", "NET_RAW"]env:- name: POD_NAMEvalueFrom:fieldRef:fieldPath: metadata.name- name: POD_NAMESPACEvalueFrom:fieldRef:fieldPath: metadata.namespace- name: EVENT_QUEUE_DEPTHvalue: "5000"volumeMounts:- name: runmountPath: /run/flannel- name: flannel-cfgmountPath: /etc/kube-flannel/- name: xtables-lockmountPath: /run/xtables.lockvolumes:- name: runhostPath:path: /run/flannel- name: cni-pluginhostPath:path: /opt/cni/bin- name: cnihostPath:path: /etc/cni/net.d- name: flannel-cfgconfigMap:name: kube-flannel-cfg- name: xtables-lockhostPath:path: /run/xtables.locktype: FileOrCreate

然后执行kubectl apply就可以了,如下:

root@k8s-master:~# kubectl apply -f kube-flannel.yml
namespace/kube-flannel created
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.apps/kube-flannel-ds created

4. 添加k8s-node1和k8s-node2

在k8s-node1和k8s-node2上分别执行如下命令,将其注册到Cluster中:

这句话在初始化集群时会打印在终端,直接复制执行即可。

如果没有记录,可以通过 kubeadm token list 查看

kubeadm join 192.168.65.145:6443 --token mj7yh1.kcsms343yksi1k8l \--discovery-token-ca-cert-hash sha256:06d33735dffa06b7de28e7837297fb982354f1667cc7d250e2a3dfdc468256cb 

在master上查看节点状态:

root@k8s-master:~# kubectl get nodes
NAME         STATUS   ROLES    AGE     VERSION
k8s-master   Ready    master   40m     v1.19.10
k8s-node1    Ready       2m48s   v1.19.10
k8s-node2    Ready       2m40s   v1.19.10

查看pod具体情况:

root@k8s-master:~# kubectl get pod --all-namespaces
NAMESPACE      NAME                                 READY   STATUS    RESTARTS   AGE
kube-flannel   kube-flannel-ds-d9qtr                1/1     Running   0          3m35s
kube-flannel   kube-flannel-ds-jbhdr                1/1     Running   0          3m43s
kube-flannel   kube-flannel-ds-rpqg4                1/1     Running   0          7m8s
kube-system    coredns-6d56c8448f-fdgm2             1/1     Running   0          40m
kube-system    coredns-6d56c8448f-mkgx2             1/1     Running   0          40m
kube-system    etcd-k8s-master                      1/1     Running   0          41m
kube-system    kube-apiserver-k8s-master            1/1     Running   0          41m
kube-system    kube-controller-manager-k8s-master   1/1     Running   0          41m
kube-system    kube-proxy-9rj9s                     1/1     Running   0          3m43s
kube-system    kube-proxy-sm5kd                     1/1     Running   0          40m
kube-system    kube-proxy-vgzgz                     1/1     Running   0          3m35s
kube-system    kube-scheduler-k8s-master            1/1     Running   0          41m

此时,所有节点都已经准备好了,Kubernetes Cluster创建成功!

参考地址:Kubernetes入门之Ubuntu上安装部署k8s集群

相关内容

热门资讯

河水哗哗地流着改为拟人句 河水哗哗地流着改为拟人句  拟人修辞方法,就是把事物人格化,将本来不具备人动作和感情的事物变成和人一...
天上的街市阅读答案   我们中国近代诗人郭沫若一首非常有名的作品,叫做《天上的街市》,这篇课文没有出现在我们课本上,所以...
《诗经》的六义 《诗经》的六义  《诗经》,是中国古代诗歌开端,最早的一部诗歌总集,收集了西周初年至春秋中叶(前11...
春节对联总汇 春节对联总汇  无论是在学校还是在社会中,大家都听说过或者使用过一些比较经典的对联吧,对联形式短小,...
疑问句、反问句、设问句的区别 疑问句、反问句、设问句的区别  疑问句、反问句、设问句是不同的句子类型,下面是小编收集整理的`疑问句...