在开始之前,部署Kubernetes集群机器需要满足以下几个条件:

  • 一台或多台机器,操作系统 CentOS7.x-86_x64
  • 硬件配置:2GB或更多RAM,2个CPU或更多CPU,硬盘30GB或更多
  • 集群中所有机器之间网络互通
  • 可以访问外网,需要拉取镜像
  • 禁止swap分区

实验准备

master(2C/4G,cpu核心数要求大于2)		    192.168.80.10		docker、kubeadm、kubelet、kubectl、flannel
node01(2C/2G)							192.168.80.20		docker、kubeadm、kubelet、kubectl、flannel
node02(2C/2G)							192.168.80.30		docker、kubeadm、kubelet、kubectl、flannel
Harbor节点(hub.kgc.com)				192.168.80.40		docker、docker-compose、harbor-offline-v1.2.2

部署步骤
1、在所有节点上安装Docker和kubeadm
2、部署Kubernetes Master
3、部署容器网络插件
4、部署 Kubernetes Node,将节点加入Kubernetes集群中
5、部署 Dashboard Web 页面,可视化查看Kubernetes资源
6、部署 Harbor 私有仓库,存放镜像资源
相关软件包:https://pan.baidu.com/share/init?surl=lb77INtbReJNVdD57uo4rg
密码:1234

一、K8S 集群架构的 kubeadm 部署

环境准备

//所有节点,关闭防火墙规则,关闭selinux,关闭swap交换
systemctl stop firewalld
systemctl disable firewalld
setenforce 0
iptables -F
swapoff -a						#交换分区必须要关闭
#加载 ip_vs 模块
for i in $(ls /usr/lib/modules/$(uname -r)/kernel/net/netfilter/ipvs|grep -o "^[^.]*");do echo $i; /sbin/modinfo -F filename $i >/dev/null 2>&1 && /sbin/modprobe $i;done
  • 通过工具—>发送键输入到所有会话 到各个终端
    在这里插入图片描述
//修改主机名
hostnamectl set-hostname master
hostnamectl set-hostname node01
hostnamectl set-hostname node02
hostnamectl set-hostname Harbor
//所有节点修改hosts文件
vim /etc/hosts
192.168.80.10 master
192.168.80.20 node01
192.168.80.30 node02
192.168.80.40 harbor

在这里插入图片描述

//调整内核参数
cat > /etc/sysctl.d/kubernetes.conf << EOF
#开启网桥模式,可将网桥的流量传递给iptables链
net.bridge.bridge-nf-call-ip6tables=1
net.bridge.bridge-nf-call-iptables=1
#关闭ipv6协议
net.ipv6.conf.all.disable_ipv6=1
net.ipv4.ip_forward=1
EOF

//生效参数
sysctl --system  

在这里插入图片描述

1.1 所有节点安装docker

  • 先配置在线yum源在安装Doker
yum install -y yum-utils device-mapper-persistent-data lvm2 
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 
yum install -y docker-ce docker-ce-cli containerd.io
  • 创建docker的配置文件
mkdir /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": ["https://6ijb8ubo.mirror.aliyuncs.com"],
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  }
}
EOF
#使用Systemd管理的Cgroup来进行资源控制与管理,因为相对Cgroupfs而言,Systemd限制CPU、内存等资源更加简单和成熟稳定。
#日志使用json-file格式类型存储,大小为100M,保存在/var/log/containers目录下,方便ELK等日志系统收集和管理日志。
  • 重启docker服务
systemctl daemon-reload
systemctl restart docker.service
systemctl enable docker.service 

docker info | grep "Cgroup Driver"
Cgroup Driver: systemd

在这里插入图片描述

1.2 所有节点安装kubeadm,kubelet和kubectl

  • 定义kubernetes源
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

yum install -y kubelet-1.15.1 kubeadm-1.15.1 kubectl-1.15.1

在这里插入图片描述

  • 开机自启kubelet
systemctl enable kubelet.service
#K8S通过kubeadm安装出来以后都是以Pod方式存在,即底层是以容器方式运行,所以kubelet必须设置开机自启

在这里插入图片描述

1.3 部署K8S集群

  • 查看初始化需要的镜像
kubeadm config images list

在这里插入图片描述

  • 在 master 节点上传 kubeadm-basic.images.tar.gz 压缩包至 /opt 目录
cd /opt
tar zxvf kubeadm-basic.images.tar.gz

for i in $(ls /opt/kubeadm-basic.images/*.tar); do docker load -i $i; done

在这里插入图片描述

  • 复制镜像和脚本到 node 节点
scp -r kubeadm-basic.images root@node01:/opt
scp -r kubeadm-basic.images root@node02:/opt

#然后到各个node节点执行
for i in $(ls /opt/kubeadm-basic.images/*.tar); do docker load -i $i; done
  • 初始化kubeadm(在master上操作)
方法一:
kubeadm config print init-defaults > /opt/kubeadm-config.yaml

cd /opt/
vim kubeadm-config.yaml
......
11 localAPIEndpoint:
12   advertiseAddress: 192.168.80.10		#指定master节点的IP地址
13   bindPort: 6443
......
34 kubernetesVersion: v1.15.1				#指定kubernetes版本号
35 networking:
36   dnsDomain: cluster.local
37   podSubnet: "10.244.0.0/16"				#指定pod网段,10.244.0.0/16用于匹配flannel默认网段
38   serviceSubnet: 10.96.0.0/16			#指定service网段
39 scheduler: {}
#末尾再添加以下内容
--- 
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
featureGates:
  SupportIPVSProxyMode: true
mode: ipvs									#把默认的service调度方式改为ipvs模式

在这里插入图片描述

  • master 开启集群,等待node节点加入
kubeadm init --config=kubeadm-config.yaml --experimental-upload-certs | tee kubeadm-init.log
#--experimental-upload-certs 参数可以在后续执行加入节点时自动分发证书文件,k8sV1.16版本开始替换为 --upload-certs
#tee kubeadm-init.log 用以输出日志

//查看 kubeadm-init 日志
less kubeadm-init.log

//kubernetes配置文件目录
ls /etc/kubernetes/

//存放ca等证书和密码的目录
ls /etc/kubernetes/pki		
//初始化kubeadm的第二种方法
方法二:
kubeadm init \
--apiserver-advertise-address=0.0.0.0 \
--image-repository registry.aliyuncs.com/google_containers \
--kubernetes-version=v1.15.1 \
--service-cidr=10.1.0.0/16 \
--pod-network-cidr=10.244.0.0/16

---
初始化集群需使用kubeadm init命令,可以指定具体参数初始化,也可以指定配置文件初始化。
可选参数:
--apiserver-advertise-address:apiserver的监听地址
--apiserver-bind-port:apiserver的监听端口,默认是6443
--cert-dir:通讯的ssl证书文件,默认/etc/kubernetes/pki
--control-plane-endpoint:控制台平面的共享终端,可以是负载均衡的ip地址或者dns域名,高可用集群时需要添加
--image-repository:拉取镜像的镜像仓库,默认是k8s.gcr.io
--kubernetes-version:指定kubernetes版本
--pod-network-cidr:pod资源的网段,需与pod网络插件的值设置一致。通常,Flannel网络插件的默认为10.244.0.0/16,Calico插件的默认值为192.168.0.0/16
--service-cidr:service资源的网段
--service-dns-domain:service全域名的后缀,默认是cluster.local

---

方法二初始化后需要修改 kube-proxy  configmap,开启 ipvs
kubectl edit cm kube-proxy -n=kube-system
修改mode: ipvs
提示:
......
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 192.168.80.10:6443 --token rc0kfs.a1sfe3gl4dvopck5 \
    --discovery-token-ca-cert-hash sha256:864fe553c812df2af262b406b707db68b0fd450dc08b34efb73dd5a4771d37a2

在这里插入图片描述

//设定kubectl
kubectl需经由API server认证及授权后方能执行相应的管理操作,kubeadm 部署的集群为其生成了一个具有管理员权限的认证配置文件 /etc/kubernetes/admin.conf,它可由 kubectl 通过默认的 “$HOME/.kube/config” 的路径进行加载。

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


// node 节点上执行 kubeadm join 命令加入群集
kubeadm join 192.168.80.10:6443 --token abcdef.0123456789abcdef \
    --discovery-token-ca-cert-hash sha256:3e45822b6147866d8d2d467e1c1eb0af9eff6405884b5483dfbc136831686252 

在这里插入图片描述

  • 在 node 节点上执行 kubeadm join 命令加入群集
    在这里插入图片描述

1.3 所有节点部署网络插件flannel

方法一:
//所有节点上传flannel镜像 flannel.tar  /opt 目录,master节点上传 kube-flannel.yml 文件
cd /opt
docker load < flannel.tar

// master 节点创建 flannel 资源
kubectl apply -f kube-flannel.yml 

方法二:
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

在这里插入图片描述

//在master节点查看节点状态(需要等几分钟)
[root@master opt]# kubectl get nodes
NAME     STATUS   ROLES    AGE   VERSION
master   Ready    master   17m   v1.15.1
node01   Ready    <none>   12m   v1.15.1
node02   Ready    <none>   12m   v1.15.1

[root@master opt]# kubectl get pods -n kube-system
NAME                             READY   STATUS    RESTARTS   AGE
coredns-5c98db65d4-hj7mn         1/1     Running   0          5m32s
coredns-5c98db65d4-sxxzr         1/1     Running   0          5m32s
etcd-master                      1/1     Running   0          4m49s
kube-apiserver-master            1/1     Running   0          4m51s
kube-controller-manager-master   1/1     Running   0          4m33s
kube-flannel-ds-amd64-7rvc4      1/1     Running   0          18s
kube-flannel-ds-amd64-dt5g4      1/1     Running   0          18s
kube-flannel-ds-amd64-msdcw      1/1     Running   0          18s
kube-proxy-2f9zl                 1/1     Running   0          4m40s
kube-proxy-hf6bx                 1/1     Running   0          4m36s
kube-proxy-mdh5c                 1/1     Running   0          5m32s
kube-scheduler-master            1/1     Running   0          4m31s
//测试 pod 资源创建
[root@master opt]# kubectl create deployment nginx --image=nginx
deployment.apps/nginx created


[root@master opt]# kubectl get pods -o wide
NAME                     READY   STATUS              RESTARTS   AGE   IP       NODE     NOMINATED NODE   READINESS GATES
nginx-554b9c67f9-h82kt   0/1     ContainerCreating   0          7s    <none>   node01   <none>           <none>


//暴露端口提供服务
[root@master opt]# kubectl expose deployment nginx --port=80 --type=NodePort
service/nginx exposed

[root@master opt]# kubectl get svc
NAME         TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1     <none>        443/TCP        10m
nginx        NodePort    10.96.59.53   <none>        80:31670/TCP   8s


//测试访问
[root@master opt]# curl http://node01:31670
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>


//扩展3个副本
[root@master opt]# kubectl scale deployment nginx --replicas=3
deployment.extensions/nginx scaled
[root@master opt]# kubectl get pods -o wide
NAME                     READY   STATUS              RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
nginx-554b9c67f9-7znrm   0/1     ContainerCreating   0          1s    <none>       node01   <none>           <none>
nginx-554b9c67f9-h82kt   1/1     Running             0          98s   10.244.1.2   node01   <none>           <none>
nginx-554b9c67f9-pnwh5   0/1     ContainerCreating   0          1s    <none>       node02   <none>           <none>

二、安装dashboard

  • 所有节点安装dashboard
方法一:
//所有节点上传dashboard镜像 dashboard.tar  /opt 目录,master节点上传kubernetes-dashboard.yaml文件
cd /opt/
docker load < dashboard.tar

kubectl apply -f kubernetes-dashboard.yaml

方法二:
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml

在这里插入图片描述

  • 查看所有容器运行状态
[root@master opt]#  kubectl get pods,svc -n kube-system -o wide
NAME                                        READY   STATUS    RESTARTS   AGE   IP              NODE     NOMINATED NODE   READINESS GATES
pod/coredns-5c98db65d4-hj7mn                1/1     Running   0          75m   10.244.2.2      node02   <none>           <none>
pod/coredns-5c98db65d4-sxxzr                1/1     Running   0          75m   10.244.2.3      node02   <none>           <none>
pod/etcd-master                             1/1     Running   0          75m   192.168.80.10   master   <none>           <none>
pod/kube-apiserver-master                   1/1     Running   0          75m   192.168.80.10   master   <none>           <none>
pod/kube-controller-manager-master          1/1     Running   0          74m   192.168.80.10   master   <none>           <none>
pod/kube-flannel-ds-amd64-7rvc4             1/1     Running   0          70m   192.168.80.30   node02   <none>           <none>
pod/kube-flannel-ds-amd64-dt5g4             1/1     Running   0          70m   192.168.80.20   node01   <none>           <none>
pod/kube-flannel-ds-amd64-msdcw             1/1     Running   0          70m   192.168.80.10   master   <none>           <none>
pod/kube-proxy-2f9zl                        1/1     Running   0          75m   192.168.80.20   node01   <none>           <none>
pod/kube-proxy-hf6bx                        1/1     Running   0          75m   192.168.80.30   node02   <none>           <none>
pod/kube-proxy-mdh5c                        1/1     Running   0          75m   192.168.80.10   master   <none>           <none>
pod/kube-scheduler-master                   1/1     Running   0          74m   192.168.80.10   master   <none>           <none>
pod/kubernetes-dashboard-859b87d4f7-56fkt   1/1     Running   0          9s    10.244.1.4      node01   <none>           <none>

NAME                           TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)                  AGE   SELECTOR
service/kube-dns               ClusterIP   10.96.0.10     <none>        53/UDP,53/TCP,9153/TCP   76m   k8s-app=kube-dns
service/kubernetes-dashboard   NodePort    10.96.210.43   <none>        443:30001/TCP            9s    k8s-app=kubernetes-dashboard
  • 使用火狐或者360浏览器访问
https://node01:30001/
https://192.168.80.20:30001/

在这里插入图片描述
在这里插入图片描述

//创建service account并绑定默认cluster-admin管理员集群角色
kubectl create serviceaccount dashboard-admin -n kube-system

kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin

//获取令牌密钥
kubectl describe secrets -n kube-system $(kubectl -n kube-system get secret | awk '/dashboard-admin/{print $1}')
Name:         dashboard-admin-token-xf4dk
Namespace:    kube-system
Labels:       <none>
Annotations:  kubernetes.io/service-account.name: dashboard-admin
              kubernetes.io/service-account.uid: 736a7c1e-0fa1-430a-9244-71cda7899293

Type:  kubernetes.io/service-account-token

Data
====
token:      eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4teGY0ZGsiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNzM2YTdjMWUtMGZhMS00MzBhLTkyNDQtNzFjZGE3ODk5MjkzIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.uNyAUOqejg7UOVCYkP0evQzG9_h-vAReaDtmYuCPdnvAf150eBsfpRPL1QmsDRsWF0xbI2Yb9m1VajMgKGneHCYFBqD-bsw0ffvbYRwM-roRnLtX-qN1kGMUyMU3iB8y_L6x-ZhiLXwjxUYZzO4WurY-e0h3yI0O2n9qQQmencEoz4snUKK4p_nBIcQrexMzO-aqhuQU_6JJQlN0q5jKHqnB11TfNQX1CNmTqN_dpZy0Wm1JzujVEd-6GQg7xawJkoSZjPYKgmN89z3o2o4cRydshUyLlb6Rmw_FSRvRWiobzL6xhWeGND4i7LgDCAr9YPRJ8LMjJYh_dPbN2Dnpxg
ca.crt:     1025 bytes
namespace:  11 bytes


//复制token令牌直接登录网站

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、安装Harbor私有仓库

//修改主机名
hostnamectl set-hostname hub.kgc.com

//所有节点加上主机名映射
echo '192.168.80.40 hub.kgc.com' >> /etc/hosts

//安装 docker
yum install -y yum-utils device-mapper-persistent-data lvm2 
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 
yum install -y docker-ce docker-ce-cli containerd.io

mkdir /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": ["https://6ijb8ubo.mirror.aliyuncs.com"],
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "insecure-registries": ["https://hub.KGC.com"]
}
EOF

systemctl start docker
systemctl enable docker
//安装 Harbor
//上传 harbor-offline-installer-v1.2.2.tgz  docker-compose 文件到 /opt 目录
cd /opt
cp docker-compose /usr/local/bin/
chmod +x /usr/local/bin/docker-compose

tar zxvf harbor-offline-installer-v1.2.2.tgz
cd harbor/
vim harbor.cfg
5  hostname = hub.kgc.com
9  ui_url_protocol = https
24 ssl_cert = /data/cert/server.crt
25 ssl_cert_key = /data/cert/server.key
59 harbor_admin_password = Harbor12345


//生成证书
mkdir -p /data/cert
cd /data/cert
#生成私钥
openssl genrsa -des3 -out server.key 2048
输入两遍密码:123456

#生成证书签名请求文件
openssl req -new -key server.key -out server.csr
输入私钥密码:123456
输入国家名:CN
输入省名:BJ
输入市名:BJ
输入组织名:KGC
输入机构名:KGC
输入域名:hub.kgc.com
输入管理员邮箱:admin@kgc.com
其它全部直接回车

#备份私钥
cp server.key server.key.org

#清除私钥密码
openssl rsa -in server.key.org -out server.key
输入私钥密码:123456

#签名证书
openssl x509 -req -days 1000 -in server.csr -signkey server.key -out server.crt

chmod +x /data/cert/*

cd /opt/harbor/
./install.sh
浏览器访问:https://hub.kgc.com
用户名:admin
密码:Harbor12345

//在一个node节点上登录harbor
docker login -u admin -p Harbor12345 https://hub.kgc.com

//上传镜像
docker tag nginx:latest hub.kgc.com/library/nginx:v1
docker push hub.kgc.com/library/nginx:v1

//在master节点上删除之前创建的nginx资源
kubectl delete deployment nginx

kubectl run nginx-deployment --image=192.168.80.13/library/nginx:v1 --port=80 --replicas=3

kubectl expose deployment nginx-deployment --port=30000 --target-port=80
kubectl get svc,pods
NAME                       TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)     AGE
service/kubernetes         ClusterIP   10.96.0.1       <none>        443/TCP     10m
service/nginx-deployment   ClusterIP   10.96.222.161   <none>        30000/TCP   3m15s

NAME                                    READY   STATUS    RESTARTS   AGE
pod/nginx-deployment-77bcbfbfdc-bv5bz   1/1     Running   0          16s
pod/nginx-deployment-77bcbfbfdc-fq8wr   1/1     Running   0          16s
pod/nginx-deployment-77bcbfbfdc-xrg45   1/1     Running   0          3m39s


yum install ipvsadm -y
ipvsadm -Ln

curl 10.96.222.161:30000


kubectl edit svc nginx-deployment
25   type: NodePort						#把调度策略改成NodePort

kubectl get svc
NAME                       TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)           AGE
service/kubernetes         ClusterIP   10.96.0.1       <none>        443/TCP           29m
service/nginx-deployment   NodePort    10.96.222.161   <none>        30000:32340/TCP   22m

浏览器访问:
192.168.80.10:32340
192.168.80.11:32340
192.168.80.12:32340

四、内核参数优化方案

cat > /etc/sysctl.d/kubernetes.conf <<EOF
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1
net.ipv4.tcp_tw_recycle=0
vm.swappiness=0									#禁止使用 swap 空间,只有当系统内存不足(OOM)时才允许使用它
vm.overcommit_memory=1							#不检查物理内存是否够用
vm.panic_on_oom=0								#开启 OOM
fs.inotify.max_user_instances=8192
fs.inotify.max_user_watches=1048576
fs.file-max=52706963							#指定最大文件句柄数
fs.nr_open=52706963								#仅4.4以上版本支持
net.ipv6.conf.all.disable_ipv6=1
net.netfilter.nf_conntrack_max=2310720
EOF
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐