Skip to content

Kubernetes

最后修改: 2019-12-31

这几天抽个空把k8s这边的部署操作整理输出一下

环境信息:

至少两台服务器,其实一台也可以,只不过就是单机的了,今天说下这个集群部署,操作也都差不了太多

推荐使用Centos7以上系列

安装docker(官方文档

// 以下命令如果提示没权限请在最前面加上sudo
// 如果安装过旧版本的docker需要先卸载旧版本(没有安装过直接跳过这一步)
yum romove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine

// 安装所需的包:yum-utils 提供yum-config-manager功能,另外两个是为了方便添加软件源,支持 devicemapper 存储类型
yum install -y yum-utils device-mapper-persistent-data lvm2


// 设置yum源
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo


// 安装docker
yum install docker-ce

// 设置国内镜像源并驱动为systemd
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.override_kernel_check=true"
  ]
}


// 启动docker并加入开机启动
systemctl enable docker
systemctl start docker

这里默认安装的是最新版本,如果想要指定版本的话,yum list docker-ce --showduplicates | sort -r 查看,然后 yum install docker-ce-版本号

前置准备(可选)

// 禁用防火墙(通常只会安装firewalld和iptables之一,一般只需要禁用firewalld)
systemctl stop firewalld.service
systemctl stop iptables.service
systemctl disable firewalld.service
systemctl disable iptables.service


// 禁用SELinux
sed -i 's@^\(SELINUX=\).*@\1disabled@' /etc/sysconfig/selinux
setenforce 0


// 禁用swap
swapoff -a
vim /etc/fstab // 如果有swap这一行就注释掉swap所在行

配置YUM仓库源

cat >/etc/yum.repos.d/kubernetes.repo <<EOF
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

开始部署

安装kubectl,kubeadm

yum makecache
yum install -y kubelet kubeadm kubectl

如果是国内地址的话,需要 kubeadm config images list 查看下当前镜像资源版本号,如图:

所以我们需要通过 打TAG 的方式来完成这一步操作

images=(
    kube-apiserver:v1.16.2
    kube-controller-manager:v1.16.2
    kube-scheduler:v1.16.2
    kube-proxy:v1.16.2
    pause:3.1
    etcd:3.3.15-0
    coredns:1.6.2
)

for imageName in ${images[@]} ; do
    docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
    docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName k8s.gcr.io/$imageName
    docker rmi registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
done
将上面的脚本保存为一个可执行文件,然后执行即可(记得改对应版本号)

执行完成之后如图所示:

初始化部署:

kubeadm init --kubernetes-version=v1.21.14 --pod-network-cidr=10.244.0.0/16 --service-cidr=10.96.0.0/12 --control-plane-endpoint=cluster-home

除了上面版本号,其他的都不要修改

输出日志如下:

root@k8s-00:~ $ kubeadm init --kubernetes-version=v1.16.2 --pod-network-cidr=10.244.0.0/16
[init] Using Kubernetes version: v1.16.2
[preflight] Running pre-flight checks
    [WARNING Service-Docker]: docker service is not enabled, please run 'systemctl enable docker.service'
    [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: 19.03.4. Latest validated version: 18.09
    [WARNING Hostname]: hostname "master.os.pve" could not be reached
    [WARNING Hostname]: hostname "master.os.pve": lookup master.os.pve on 172.24.16.1:53: read udp 172.24.18.9:39568->172.24.16.1:53: i/o timeout
    [WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
[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'
[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] Activating the kubelet service
[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 [master.os.pve kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 172.24.18.9]
[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 [master.os.pve localhost] and IPs [172.24.18.9 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [master.os.pve localhost] and IPs [172.24.18.9 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
[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 34.504499 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.16" 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 master.os.pve as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node master.os.pve as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: tpdjox.2ocehhtv7js25iy0
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[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
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your 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/config

You 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 172.24.18.9:6443 --token tpdjox.2ocehhtv7js25iy0 \
    --discovery-token-ca-cert-hash sha256:7636e9024bdcd590ef4b5d723b88dc15ccb5c84cc83f86bcfdadc527b06d6da3

将上面日志的最后一部分记录下来,用于在其他的Node上面执行,也就是这个

kubeadm join 172.24.18.9:6443 --token tpdjox.2ocehhtv7js25iy0 \
    --discovery-token-ca-cert-hash sha256:7636e9024bdcd590ef4b5d723b88dc15ccb5c84cc83f86bcfdadc527b06d6da3
其他Node上的日志输出如下所示:
//如果这一步无法执行,需要检查报错,在这之前应该确保 `modprobe br_netfilter`
root@k8s-01:~ $ kubeadm join 172.24.18.9:6443 --token tpdjox.2ocehhtv7js25iy0 \
>     --discovery-token-ca-cert-hash sha256:7636e9024bdcd590ef4b5d723b88dc15ccb5c84cc83f86bcfdadc527b06d6da3
[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: 19.03.4. Latest validated version: 18.09
    [WARNING Hostname]: hostname "slave01.os.pve" could not be reached
    [WARNING Hostname]: hostname "slave01.os.pve": lookup slave01.os.pve on 172.24.16.1:53: no such host
    [WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[kubelet-start] Downloading configuration for the kubelet from the "kubelet-config-1.16" ConfigMap in the kube-system namespace
[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] Activating the kubelet service
[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.

初始化成功后依次键入以下命令:

// 初始化kubectl
mkdir ~/.kube
cp /etc/kubernetes/admin.conf ~/.kube/config

现在可以看到部分节点为NotReady,如下图:

root@k8s-00:~ $ kubectl get nodes
NAME             STATUS     ROLES    AGE     VERSION
master.os.pve    NotReady   master   4m30s   v1.16.2
slave01.os.pve   NotReady   <none>   111s    v1.16.2
slave02.os.pve   NotReady   <none>   91s     v1.16.2

root@k8s-00:~ $ kubectl get pods -n kube-system
NAME                                    READY   STATUS    RESTARTS   AGE
coredns-5644d7b6d9-cxnpx                0/1     Pending   0          5m18s
coredns-5644d7b6d9-krr8b                0/1     Pending   0          5m18s
etcd-master.os.pve                      1/1     Running   0          5m33s
kube-apiserver-master.os.pve            1/1     Running   0          5m33s
kube-controller-manager-master.os.pve   1/1     Running   0          5m33s
kube-proxy-fnc2l                        1/1     Running   0          2m58s
kube-proxy-tzfps                        1/1     Running   0          5m17s
kube-proxy-ww554                        1/1     Running   0          2m38s
kube-scheduler-master.os.pve            1/1     Running   0          4m31s
这是因为没有部署网络插件导致的,可以按照下面的方法:
//这一步受限于GFW,有可能出现慢甚至无法加载的情况
root@k8s-00:~ $ kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
podsecuritypolicy.policy/psp.flannel.unprivileged 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-amd64 created
daemonset.apps/kube-flannel-ds-arm64 created
daemonset.apps/kube-flannel-ds-arm created
daemonset.apps/kube-flannel-ds-ppc64le created
daemonset.apps/kube-flannel-ds-s390x created

到这一步差不多就结束了,然后我们验证一下在master节点上面执行命令观察状态:

root@k8s-00:~ $ kubectl get no
NAME             STATUS   ROLES    AGE    VERSION
master.os.pve    Ready    master   12m    v1.16.2
slave01.os.pve   Ready    <none>   117s   v1.16.2
slave02.os.pve   Ready    <none>   43s    v1.16.2

source <(kubectl completion bash)