千家信息网

kubernetes环境的搭建步骤

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,这篇文章主要介绍"kubernetes环境的搭建步骤",在日常操作中,相信很多人在kubernetes环境的搭建步骤问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"kub
千家信息网最后更新 2026年11月01日kubernetes环境的搭建步骤

这篇文章主要介绍"kubernetes环境的搭建步骤",在日常操作中,相信很多人在kubernetes环境的搭建步骤问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"kubernetes环境的搭建步骤"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

环境准备


部署集群没有特殊说明均使用 root 用户执行命令

硬件信息

IPHOSTNAMEMEMDISKEXPLAIN
192.168.1.61k8s-master8G40Gk8s 控制平台节点
192.168.1.154k8s-node116G40Gk8s 工作节点1
192.168.1.62k8s-node216G40Gk8s 工作节点2
192.168.1.207k8s-node316G40Gk8s 工作节点3

软件信息

SoftWareVersion
CentOSCentOS Linux release 8.2.2004 (Core)
Kubernetesv1.20.1
Dockerv20.10.1

保证环境正确性

PurposeCommands
保证集群各节点互通ping -c
保证MAC地址唯一ip link 或者 ifconfig -a
保证集群内主机名唯一查询 hostnamectl status , 或者 hostnamectl set-hostname
保证系统产品UUID唯一dmidecode -s system-uuid 或者 sudo cat /sys/class/dmi/id/product_uuid
# 修改MAC地址参考命令如下:# 1、关闭网卡ifconfig eth0 down# 2、修改macifconfig eth0 hw ether 00:E0:18:EE:ED# 3、开启网卡ifconfig eth0 up

⚠如果 product_uuid 不唯一,请考虑重装 CentOS 系统!!

确保端口开放正常

k8s-master 节点端口检查:

协议方向端口范围作用使用者
TCP入站6443*Kubernetes API 服务器所有组件
TCP入站2379-2380etcd server client APIkube-apiserver,etcd
TCP入站10250Kubelet APIKubelet 自身、控制平面组件
TCP入站10251Kube-schedulerkube-scheduler 组件
TCP入站10252kube-controller-managerkube-controller-manager 组件

k8s-node* 节点端口检查:

协议方向端口范围作用使用者
TCP入站10250Kubelet-APIkubelet 组件、控制平面组件
TCP入站30000-32767NodePort服务***所有组件

如果你对主机的防火墙配置不是很自信,则可以关掉防火墙:

systemctl disable --now firewalld 或者清除 iptables 规则(iptables -F)【慎用】

配置主机互信

分别在各节点配置 hosts 映射:

cat >> /etc/hosts <

K8s-master 生成 ssh 密钥,分发公钥到各节点:

# 生成 ssh 密钥,直接一路回车ssh-keygen -t rsa# 复制刚刚生成的密钥到各节点可信列表中,需分别输入各主机密码ssh-copy-id root@k8s-masterssh-copy-id root@k8s-node1ssh-copy-id root@k8s-node2ssh-copy-id root@k8s-node3

禁用 swap

swap 仅当内存不够时会使用硬盘块充当额外内存,硬盘的IO较内存差距极大,禁用swap以提供性能,各节点均需执行:

swapoff -ased -i 's/.*swap.*/#&/' /etc/fstab

关闭 SELinux

关闭SELinux,否则kubelet 挂载目录时可能报错 Permission denied,可以设置为permissive或disabled,permissive会提示warn信息 ,各节点均需执行:

setenforce 0sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config

设置系统时区、同步时间

timedatectl set-timezone Asia/Shanghaisystemctl enable --now chronyd# 查看同步状态, 输出[root@ecs-2aae ~]# timedatectl status               Local time: Sun 2020-12-27 21:59:02 CST           Universal time: Sun 2020-12-27 13:59:02 UTC                 RTC time: Sun 2020-12-27 13:58:31                Time zone: Asia/Shanghai (CST, +0800)System clock synchronized: yes              NTP service: active          RTC in local TZ: no[root@ecs-2aae ~]# ## # systemctl clok synchronronize: yes 表示时钟已同步# NTP service: active 表示开启了时钟同步服务############################################################## 将当前的 UTC 时间写入硬件时钟timedatectl set-local-rtc 0# 重启依赖于系统时间的服务器systemctl restart rsyslog && systemctl restart crond

部署Docker


所有节点均需安装部署 docker, 可参见《CentOS8 安装docker》

部署Kubernetes集群


无特殊说明,各节点均需执行如下步骤

添加kubernetes 源

cat < /etc/yum.repos.d/kubernetes.repo[kubernetes]name=Kubernetesbaseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64enabled=1gpgcheck=0repo_gpgcheck=0EOF

安装kubeadm、kubelet、kubectl

各节点均需安装 kubeadm、kubelet,kubectl仅 k8s-master 节点续约安装(作为 worker 节点, kubectl 无法使用, 可以不装)

yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetessystemctl enable --now kubelet

配置自动补全命令

#安装bash自动补全插件yum install bash-completion -y#设置kubectl与kubeadm命令补全,下次login生效kubectl completion bash > /etc/bash_completion.d/kubectlkubeadm completion bash > /etc/bash_completion.d/kubeadm

预拉取kubernetes镜像 (第一种方式)

由于国内网络因素,kubernetes镜像需要从mirrors站点或通过dockerhub用户推送的镜像拉取:

#查看指定k8s版本需要哪些镜像[root@ecs-2aae ~]# kubeadm config images listk8s.gcr.io/kube-apiserver:v1.20.1k8s.gcr.io/kube-controller-manager:v1.20.1k8s.gcr.io/kube-scheduler:v1.20.1k8s.gcr.io/kube-proxy:v1.20.1k8s.gcr.io/pause:3.2k8s.gcr.io/etcd:3.4.13-0k8s.gcr.io/coredns:1.7.0[root@ecs-2aae ~]#

在 /opt/soft/kuberetes 目录下,新建脚本pull-k8s-images.sh,内容如下:

#!/bin/bash# Script For Quick Pull K8S Docker Images# by WUXH  KUBE_VERSION=v1.20.1PAUSE_VERSION=3.2CORE_DNS_VERSION=1.7.0ETCD_VERSION=3.4.13-0# pull kubernetes images from hub.docker.comdocker pull kubeimage/kube-proxy:$KUBE_VERSIONdocker pull kubeimage/kube-controller-manager:$KUBE_VERSIONdocker pull kubeimage/kube-apiserver:$KUBE_VERSIONdocker pull kubeimage/kube-scheduler:$KUBE_VERSION# pull aliyuncs mirror docker imagesdocker pull registry.cn-hangzhou.aliyuncs.com/google_containers/pause:$PAUSE_VERSIONdocker pull registry.cn-hangzhou.aliyuncs.com/google_containers/coredns:$CORE_DNS_VERSIONdocker pull registry.cn-hangzhou.aliyuncs.com/google_containers/etcd:$ETCD_VERSION# retag to k8s.gcr.io prefixdocker tag kubeimage/kube-proxy:$KUBE_VERSION  k8s.gcr.io/kube-proxy:$KUBE_VERSIONdocker tag kubeimage/kube-controller-manager:$KUBE_VERSION k8s.gcr.io/kube-controller-manager:$KUBE_VERSIONdocker tag kubeimage/kube-apiserver:$KUBE_VERSION k8s.gcr.io/kube-apiserver:$KUBE_VERSIONdocker tag kubeimage/kube-scheduler:$KUBE_VERSION k8s.gcr.io/kube-scheduler:$KUBE_VERSIONdocker tag registry.cn-hangzhou.aliyuncs.com/google_containers/pause:$PAUSE_VERSION k8s.gcr.io/pause:$PAUSE_VERSIONdocker tag registry.cn-hangzhou.aliyuncs.com/google_containers/coredns:$CORE_DNS_VERSION k8s.gcr.io/coredns:$CORE_DNS_VERSIONdocker tag registry.cn-hangzhou.aliyuncs.com/google_containers/etcd:$ETCD_VERSION k8s.gcr.io/etcd:$ETCD_VERSION# untag origin tag, the images won't be delete.docker rmi kubeimage/kube-proxy:$KUBE_VERSIONdocker rmi kubeimage/kube-controller-manager:$KUBE_VERSIONdocker rmi kubeimage/kube-apiserver:$KUBE_VERSIONdocker rmi kubeimage/kube-scheduler:$KUBE_VERSIONdocker rmi registry.cn-hangzhou.aliyuncs.com/google_containers/pause:$PAUSE_VERSIONdocker rmi registry.cn-hangzhou.aliyuncs.com/google_containers/coredns:$CORE_DNS_VERSIONdocker rmi registry.cn-hangzhou.aliyuncs.com/google_containers/etcd:$ETCD_VERSION

脚本添加可执行权限,执行脚本拉取镜像:

chmod +x pull-k8s-images.sh./opt/soft/kuberetes/pull-k8s-images.sh

拉取完成,执行 docker images 查看镜像:

kubernetes初始化指定镜像 (第二种方式)

kubeadm init --image-repository=registry.aliyuncs.com/google_containers --kubernetes-version=v1.20.1 --pod-network-cidr 10.244.0.0/16

输出如下:

[root@ecs-2aae ~]# kubeadm init --image-repository=registry.aliyuncs.com/google_containers --pod-network-cidr=10.244.0.0/16 --kubernetes-version=v1.20.1[init] Using Kubernetes version: v1.20.1[preflight] Running pre-flight checks        [WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver. The recommended driver is "systemd". Please follow the guide at https://kubernetes.io/docs/setup/cri/        [WARNING FileExisting-tc]: tc not found in system path        [WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.1. Latest validated version: 19.03[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 [ecs-2aae kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.1.61][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 [ecs-2aae localhost] and IPs [192.168.1.61 127.0.0.1 ::1][certs] Generating "etcd/peer" certificate and key[certs] etcd/peer serving cert is signed for DNS names [ecs-2aae localhost] and IPs [192.168.1.61 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[apiclient] All control plane components are healthy after 7.501971 seconds[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace[kubelet] Creating a ConfigMap "kubelet-config-1.20" 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 ecs-2aae as control-plane by adding the labels "node-role.kubernetes.io/master=''" and "node-role.kubernetes.io/control-plane='' (deprecated)"[mark-control-plane] Marking the node ecs-2aae as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule][bootstrap-token] Using token: xksx1a.t09ok8h7w6ixnyva[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/.kube  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config  sudo chown $(id -u):$(id -g) $HOME/.kube/configAlternatively, if you are the root user, you can run:  export KUBECONFIG=/etc/kubernetes/admin.confYou 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.1.61:6443 --token 379rcy.4k2gsoggyjxzo4u9 \    --discovery-token-ca-cert-hash sha256:a8f563cd1c742fa64eef6db0420401ecb57556281199989449f872da9f50609f[root@ecs-2aae ~]#

可能故障

故障1:k8s node节点加入集群报错[WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver.# 解决cat < /etc/docker/daemon.json {   "exec-opts": ["native.cgroupdriver=systemd"]}EOF #重启dockersystemctl restart docker

为日常使用集群的用户添加kubectl使用权限,配置master认证

[root@ecs-2aae ~]# mkdir -p ~/.kube[root@ecs-2aae ~]# cp -i /etc/kubernetes/admin.conf ~/.kube/admin.conf[root@ecs-2aae ~]# chown $(id -u):$(id -g) ~/.kube/admin.conf[root@ecs-2aae ~]# echo 'export KUBECONFIG=/etc/kubernetes/admin.conf' >> /etc/profile[root@ecs-2aae ~]# . /etc/profile

安装网络组件,以flannel为例

[root@k8s-master ~]# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.ymlpodsecuritypolicy.policy/psp.flannel.unprivileged createdclusterrole.rbac.authorization.k8s.io/flannel createdclusterrolebinding.rbac.authorization.k8s.io/flannel createdserviceaccount/flannel createdconfigmap/kube-flannel-cfg createddaemonset.apps/kube-flannel-ds created[root@k8s-master ~]#

Node节点加入集群

这句话其实就是Master节点执行kubeadm init成功之后输出的最后一句话,我们拿到Node节点中直接执行即可

kubeadm join 192.168.1.61:6443 --token 379rcy.4k2gsoggyjxzo4u9 \    --discovery-token-ca-cert-hash sha256:a8f563cd1c742fa64eef6db0420401ecb57556281199989449f872da9f50609f

输出:

[root@k8s-node1 ~]# kubeadm join 192.168.1.61:6443 --token 379rcy.4k2gsoggyjxzo4u9     --discovery-token-ca-cert-hash sha256:a8f563cd1c742fa64eef6db0420401ecb57556281199989449f872da9f50609f [preflight] Running pre-flight checks        [WARNING FileExisting-tc]: tc not found in system path        [WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.1. Latest validated version: 19.03[preflight] Reading configuration from the cluster...[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"[kubelet-start] Starting the kubelet[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...This node has joined the cluster: ### 节点加入成功啦* Certificate signing request was sent to apiserver and a response was received.* The Kubelet was informed of the new secure connection details.Run 'kubectl get nodes' on the control-plane to see this node join the cluster.[root@k8s-node1 ~]#

查看集群节点状态

[root@k8s-master ~]# kubectl get nodesNAME         STATUS   ROLES                  AGE   VERSIONk8s-master   Ready    control-plane,master   67m   v1.20.1k8s-node1    Ready                     40m   v1.20.1k8s-node2    Ready                     32m   v1.20.1k8s-node3    Ready                     30m   v1.20.1[root@k8s-master ~]#
⚠: 如果节点是 NoReady 状态,可以稍微等一会儿,集群节点会自动拉起 flannel 镜像,由于网络可能稍慢!!

到此,关于"kubernetes环境的搭建步骤"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

节点 集群 组件 镜像 环境 步骤 端口 保证 配置 主机 命令 系统 同步 学习 服务 输出 信息 内存 密钥 时钟 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 上海挚品互联网科技有限公司 新华互联网科技 圆梦互联网科技 科技互联网政务服务 远信互联网科技 奇酷互联网科技公司 科技创新互联网企业 互联网养老 桔豆科技 中国互联网金融科技基金 江苏南京365互联网科技 浙江互联网科技研学营 明优互联网科技有限公司 互联网时代的科技公司 互联网科技实习生岗位 雨阳互联网卡科技有限公司 杭州披云加互联网科技有限公司 山东大美朱楼互联网科技有限公司 互联网时代高科技布局 河南商务圈互联网科技有限公司 恒生科技互联网指数十大成分股 互联网金融公司科技 银优互联网科技有限公司 以后互联网后是啥科技 重庆互联网医院沙龙医盟信息科技 崇明区互联网教育科技诚信经营 互联网科技年终奖 新氧科技和美国互联网有关系吗 互联网科技接地气 广州三三互联网科技有限公司 宁波允成互联网科技有限公司
0