引子

使用Docker容器化封装应用的意义(好处)

Docker引擎统一了基础设施环境-docker环境

  • 硬件的配置
  • 操作系统的版本
  • 运行时环境的异构

Docker引擎统一了程序打包方式-docker进行

  • java程序
  • python程序
  • nodejs程序
  • ….

Docker引擎统一了程序部署(运行)

  • java -jar …..-> docker run ….
  • python manage.py runserver ….-> docker run …
  • npm run dev … -> docker run …

Docker容器化封装应用程序的缺点(坏处)

  • 单机使用,无法有效集群
  • 随着容器数量的上升,管理成本攀升
  • 没有有效的容灾/自愈机制
  • 没有预设编排模板,无法实现快速、大规模容器调度
  • 没有统一的配置管理中心工具
  • 没有容器生命周期的管理工具
  • 没有图形化运维管理工具
  • …..
    因此我们需要一套容器编排的工具。

Docker容器引擎的开源容器编排工具目前市场上主要有

  • docker compose、docker swarm
  • Mesosphere + Marathon
  • Kubernetes

第一章:kubernetes概述

官网:https://kubernetes.io
GitHub:https://github.com/kubernetes/kubernetes
由来:谷歌的Borg系统,后经Go语言重写并捐给CNCF基金会开源
含义:词根源于希腊语:舵手/飞行员。K8S -> K12345678S
重要作用:开源的容器编排框架工具(生态极其丰富)
学习的意义:解决跑裸docker的若干痛点

kubernetes优势:

  • 自动装箱,水平扩展,自我修复
  • 服务发现和负载均衡
  • 自动发布(默认滚动发布模式)和回滚
  • 集中化配置管理和秘钥管理
  • 存储编排
  • 任务批量处理运行
  • ……

第二章:kubernetes快速入门

1.四组基本概念

1.Pod/Pod控制器

Pod

Pod是K8S里能够被运行的最小的逻辑单元(原子单元)
1个Pod里面可以运行多个容器,他们共享UTS+NET+IPC名称空间
可以把Pod理解成豌豆荚,而同一个Pod内的每个容器是一颗颗豌豆
一个Pod里运行多个容器,又叫:边车(SideCar)模式

Pod控制器

Pod控制器是Pod启动的一种模板,用来保证在K8S里启动的Pod应该始终按照人们的预期运行(f副本数、生命周期、健康状态检查...)
K8S内提供了众多的Pod控制器,常用的有以下几种:
    Deployment
    DaemonSet
    ReplicaSet
    StatefuSet
    Job
    Cronjob

2.Name/Namespace

Name

由于K8S每部,使用”资源”来定义每一种逻辑概念(功能)故每种”资源”,都应该有自己的”名称”
“名称”通常定义在”资源”的”元数据”信息里

Namespace

随着项目增多、人员增加,集群规模的扩大,需要一种能够隔离K8S内各种”资源”的方法,这就是名称空间
名称空间可以理解为K8S内部的虚拟集群组
不同名称空间内的”资源”,名称可以相同,相同名称空间内的同种”资源”,”名称”不能相同
合理的使用K8S的名称空间,使得集群管理员能够更好的对交付到K8S里的服务进行分类管理和浏览
K8S里默认存在的名称空间有:default、kube-system 、kube-public
查询K8S里特定的”资源”要带上相应的名称空间

3.Label/Label选择器

Label

标签是K8S特色的管理方式,便于分类管理资源对象
一个标签可以对应多个资源,一个资源也可以有多个标签,它们是多对多的关系
一个资源拥有多个标签,可以实现不同维度的管理
标签的组成: key=value
与标签类似的,还有一种”注解”(annotations)

Label选择器

给资源打上标签后,可以使用标签选择器过滤指定的标签
标签选择器目前有两个:基于等值关系(等于、不等于)和基于集合关系(属于、不属于、存在)
许多资源支持内嵌标签选择器字段
    matchLabels
    matchExpressions

4.Service/Ingress

Service

在K8S的世界里,虽然每个Pod都会被分配一个单独的IP地址,但这个IP地址会随着Pod的销毁而消失。
Service(服务)就是用来解决这个问题的核心概念
一个Service可以看作一组提供相同服务的Pod的对外访问接口
Service作用于哪些Pod是通过标签选择器来定义的

Ingress

Ingress是K8S集群里工作在OIS网络参考模型下,第7层的应用,对外暴露的接口
Service只能进行L4流量调度,表现形式是ip+port
Ingress则可以调度不同业务域,不同URL访问路径的业务流量

2.K8S的组成

核心组件:
    配置存储中心 -> etcd服务
    主控(Master)节点
        kube-apiserver服务
        kube-controller-manager服务
        kube-scheduler服务
    运算(node)节点
        kube-kubelet服务
        kube-proxy服务

CLI客户端
    kubectl

其他核心组件
    CNI网络插件 -> flannel/calico
    服务发现插件 -> coredns
    服务暴露插件 -> traefik
    GUI管理插件 -> Dashboard

apiserver:

提供了集群管理的REST API接口(包括鉴权、数据校验及集群状态变更)
负责其他模块之间的数据交互,承担通信纽约功能
是资源配额控制的入口
提供完备的集群安全机制

controller-manager:

由一系列控制器组成,通过apiserver监控整个集群的状态,并确保集群处于预期的工作状态
Node Controller                节点控制
Deployment Controller        pod控制器
Service Controller            服务控制器
Volume Controller            存储卷控制器
Endpoint Controller            接入点控制器
Garbage Controller            垃圾控制器
Namespace Controller        名称空间控制器
Job Controller                任务控制器
Resource quta Controller    资源配额控制器

scheduler:

主要功能是接受调度pod到适合的运算节点上
预算策略(predict)
优选策略(priorities)

kubelet:
```shell
简单地说,kubelet的主要功能就是定时从某个地方获取节点上pod的期望状态(运行什么容器、运行副本数量、网络或者存储如何配置等等),并调用对应的容器平台接口达到这个状态。
定时汇报当前节点的状态给apiserver,以供调度的时候使用
镜像和容器的清理工作,保证节点上的镜像不会占满磁盘空间,退出的容器不会占用太多资源

kube-proxy:

是K8S在每个节点上运行网络代理,service资源的载体
建立了pod网络和集群网络的关系(clusterip -> podip)
常用的三种流量调度模式:
    Userspace(废弃)
    Iptables(濒临泛滥)
    Ipvs(推荐)
负责建立和删除包括更新调度规则,通知apiserver自己的更新,或者从apiserver的调度规则来更新自己的。

3.K8S三条网络详解

  • 节点网络
  • Pod网络
  • Service网络

4.K8S逻辑架构图

第三章:实验部署集群架构详解

常见的K8S安装部署方式:

1. Minikube单节点微型K8S(仅供学习、预览使用)
2. 二进制安装部署(生产首选,新手推荐)
3. 实验kubeadmin进行部署,K8S的部署工具,跑在K8S里(相对简单,熟手推荐)

第四章:部署K8S集群前准备工作

安装部署准备工作:

  • 准备5台2c/2g/50g虚机,使用10.4.7.0/24网络
  • 预装centos7.6操作系统,做好基础优化
  • 安装部署bind9,部署自建DNS系统
  • 准备自签证书环境
  • 安装部署Docker环境,部署Harbor私有仓库

1.基础架构

主机名 角色 ip
hdss7-11.host.com k8s代理节点1 10.4.7.11
hdss7-12.host.com k8s代理节点2 10.4.7.12
hdss7-21.host.com k8s运算节点1 10.4.7.21
hdss7-22.host.com k8s运算节点2 10.4.7.22
hdss7-200.host.com k8s运维节点(docker仓库) 10.4.7.200

2.基础环境

所有机器上:

1.设置主机名

hostnamectl set-hostname hdss7-11.host.com
hostnamectl set-hostname hdss7-12.host.com
hostnamectl set-hostname hdss7-21.host.com
hostnamectl set-hostname hdss7-22.host.com
hostnamectl set-hostname hdss7-200.host.com

2.关闭selinux和关闭防火墙

~]# sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
~]# setenforce 0

3.安装epel-release

yum install -y epel-release

4.安装软件包

yum install wget net-tools telnet tree nmap sysstat lrzsz dos2unix bind-utils -y

3.部署DNS服务

hdss7-11.host.com上:

1.安装bind9软件

[root@hdss7-11 ~]# yum install bind -y

2.配置bind9

主配置文件

[root@hdss7-11 ~]# vim /etc/named.conf 
listen-on port 53 { 10.4.7.11; };
allow-query     { any; };
forwarders      { 10.4.7.254; };      #向上查询(增加一条),网关
dnssec-enable no;
dnssec-validation no;

[root@hdss7-11 ~]# named-checkconf     #检查配置文件的语法是否正确
[root@hdss7-11 ~]# 
区域配置文件,添加一下内容
#创建主机域host.com
#创建业务域od.com
[root@hdss7-11 ~]# vim /etc/named.rfc1912.zones
zone "host.com" IN {
        type  master;
        file  "host.com.zone";
        allow-update { 10.4.7.11; };
};

zone "od.com" IN {
        type  master;
        file  "od.com.zone";
        allow-update { 10.4.7.11; };
};

配置区域数据文件

[root@hdss7-11 ~]# cat /var/named/host.com.zone 
$ORIGIN host.com.
$TTL 600    ; 10 minutes
@       IN SOA    dns.host.com. dnsadmin.host.com. (
                2021031901 ; serial
                10800      ; refresh (3 hours)
                900        ; retry (15 minutes)
                604800     ; expire (1 week)
                86400      ; minimum (1 day)
                )
            NS   dns.host.com.
$TTL 60    ; 1 minute
dns                A    10.4.7.11
HDSS7-11           A    10.4.7.11
HDSS7-12           A    10.4.7.12
HDSS7-21           A    10.4.7.21
HDSS7-22           A    10.4.7.22
HDSS7-200          A    10.4.7.200

[root@hdss7-11 ~]# cat /var/named/od.com.zone 
$ORIGIN od.com.
$TTL 600    ; 10 minutes
@           IN SOA    dns.od.com. dnsadmin.od.com. (
                2021031901 ; serial
                10800      ; refresh (3 hours)
                900        ; retry (15 minutes)
                604800     ; expire (1 week)
                86400      ; minimum (1 day)
                )
                NS   dns.od.com.
$TTL 60    ; 1 minute
dns                A    10.4.7.11
[root@hdss7-11 ~]# 

3.启动bind9

[root@hdss7-11 ~]# named-checkconf
[root@hdss7-11 ~]# systemctl start named
[root@hdss7-11 ~]# systemctl enable named

4.检查

[root@hdss7-11 ~]# dig -t A hdss7-11.host.com @10.4.7.11 +short
10.4.7.11
[root@hdss7-11 ~]# dig -t A hdss7-12.host.com @10.4.7.11 +short
10.4.7.12
[root@hdss7-11 ~]# dig -t A hdss7-21.host.com @10.4.7.11 +short
10.4.7.21
[root@hdss7-11 ~]# dig -t A hdss7-22.host.com @10.4.7.11 +short
10.4.7.22
[root@hdss7-11 ~]# dig -t A hdss7-200.host.com @10.4.7.11 +short
10.4.7.200

5.配置dns客户端

Linux主机上:(临时生效)
echo "search host.com" >/etc/resolv.conf
echo "nameserver 10.4.7.11" >>/etc/resolv.conf

永久生效:修改网卡的配置信息

windows主机上:
网络和共享中心 -> 网卡设置 -> 设置DNS服务器
如有必要,还应设置虚拟网卡的接口地跃点数为:10
C:\Users\xtyang>ping dns.od.com

正在 Ping dns.od.com [10.4.7.11] 具有 32 字节的数据:
来自 10.4.7.11 的回复: 字节=32 时间<1ms TTL=64
来自 10.4.7.11 的回复: 字节=32 时间=1ms TTL=64

4.准备自签证书

运维主机HDSS7-200.host.com上:

1.安装CFSSL

cfssl下载地址
cfssljson下载地址
cfssl-certinfo下载地址

[root@hdss7-200 ~]# wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 -O /usr/bin/cfssl
[root@hdss7-200 ~]# wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64 -O /usr/bin/cfssl-json
[root@hdss7-200 ~]# wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64 -O /usr/bin/cfssl-certinfo
[root@hdss7-200 ~]# chmod +x /usr/bin/cfssl*

2.创建生成CA证书签名请求(csr)的JSON配置文件

[root@hdss7-200 ~]# mkdir /opt/certs
[root@hdss7-200 ~]# cd /opt/certs/
[root@hdss7-200 certs]# more /opt/certs/ca-csr.json 
{
    "CN": "OldboyEdu",
    "hosts": [
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ],
    "ca": {
        "expiry": "175200h"
    }
}

CN:Common Name,浏览器使用该字段验证网站是否合法,一般写的是域名。非常重要。
C:Country。国家
ST:State,州,省
L:Locality,城区,城市
O:Organization Name,组织名称,公司名称
OU:Organization Unit Name。组织单位名称,公司部门

3.生成CA证书和私钥

/opt/certs

[root@hdss7-200 certs]# cfssl gencert -initca ca-csr.json | cfssl-json -bare ca
2021/03/19 21:19:38 [INFO] generating a new CA key and certificate from CSR
2021/03/19 21:19:38 [INFO] generate received request
2021/03/19 21:19:38 [INFO] received CSR
2021/03/19 21:19:38 [INFO] generating key: rsa-2048
2021/03/19 21:19:38 [INFO] encoded CSR
2021/03/19 21:19:38 [INFO] signed certificate with serial number 496748778875537006760101778838514488750911478087
[root@hdss7-200 certs]# ls
ca.csr  ca-csr.json  ca-key.pem  ca.pem
[root@hdss7-200 certs]# 

5.部署docker环境

HDSS7-21.host.com,HDSS7-22.host.com,HDSS7-200.host.com,上:

1.安装

[root@hdss7-21 ~]# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
[root@hdss7-22 ~]# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
[root@hdss7-200 ~]# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

2.配置

[root@hdss7-21 ~]# mkdir /etc/docker
[root@hdss7-21 ~]# mkdir  -p /data/docker
[root@hdss7-21 ~]# more /etc/docker/daemon.json 
{
  "graph": "/data/docker",
  "storage-driver": "overlay2",
  "insecure-registries": ["registry.access.redhat.com","quay.io","harbor.od.com"],
  "registry-mirrors": ["https://q2gr04ke.mirror.aliyuncs.com"],
  "bip": "172.7.21.1/24",
  "exec-opts": ["native.cgroupdriver=systemd"],
  "live-restore": true
}
[root@hdss7-21 ~]# 

[root@hdss7-22 ~]# mkdir /etc/docker
[root@hdss7-22 ~]# mkdir  -p /data/docker
[root@hdss7-22 ~]# more /etc/docker/daemon.json 
{
  "graph": "/data/docker",
  "storage-driver": "overlay2",
  "insecure-registries": ["registry.access.redhat.com","quay.io","harbor.od.com"],
  "registry-mirrors": ["https://q2gr04ke.mirror.aliyuncs.com"],
  "bip": "172.7.22.1/24",
  "exec-opts": ["native.cgroupdriver=systemd"],
  "live-restore": true
}
[root@hdss7-22 ~]#

[root@hdss7-200 ~]# mkdir /etc/docker
[root@hdss7-200 ~]# mkdir  -p /data/docker
[root@hdss7-200 ~]# more /etc/docker/daemon.json 
{
  "graph": "/data/docker",
  "storage-driver": "overlay2",
  "insecure-registries": ["registry.access.redhat.com","quay.io","harbor.od.com"],
  "registry-mirrors": ["https://q2gr04ke.mirror.aliyuncs.com"],
  "bip": "172.7.200.1/24",
  "exec-opts": ["native.cgroupdriver=systemd"],
  "live-restore": true
}
[root@hdss7-200 ~]# 

3.启动

HDSS7-21.host.com,HDSS7-22.host.com,HDSS7-200.host.com,上:

systemctl start docker
systemctl enable docker

6.部署docker镜像私有仓库harbor

HDSS7-200.host.com上:

1.下载二进制软件包

[root@hdss7-200 ~]#  mkdir -p /opt/src/
[root@hdss7-200 ~]# cd /opt/src
[root@hdss7-200 src]# wget https://storage.googleapis.com/harbor-releases/release-1.8.0/harbor-offline-installer-v1.8.3.tgz
[root@hdss7-200 src]# tar xf harbor-offline-installer-v1.8.3.tgz -C /opt
[root@hdss7-200 src]# mv /opt/harbor/ /opt/harbor-v1.8.3
[root@hdss7-200 src]# ln -s /opt/harbor-v1.8.3/ /opt/harbor
[root@hdss7-200 src]# 

2.配置

/opt/harbor/harbor.yml 

hostname: harbor.od.com
http:
  port: 180
harbor_admin_password: Harbor12345
data_volume: /data/harbor
log:
  level: info
  rotate_count: 50
  rotate_size: 200M
  location: /data/harbor/logs
# 主要的配置内容
[root@hdss7-200 ~]# mkdir -p /data/harbor/logs

3.安装docker-compose

[root@hdss7-200 ~]# yum install docker-compose -y
[root@hdss7-200 ~]# rpm -qa docker-compose
docker-compose-1.18.0-4.el7.noarch
[root@hdss7-200 ~]# 

4.安装harbor

[root@hdss7-200 ~]# cd /opt/harbor
[root@hdss7-200 harbor]# ls
harbor.v1.8.3.tar.gz  harbor.yml  install.sh  LICENSE  prepare
[root@hdss7-200 harbor]# sh install.sh

5.检查harbor启动情况

[root@hdss7-200 harbor]# docker-compose  ps
      Name                     Command               State             Ports          
--------------------------------------------------------------------------------------
harbor-core         /harbor/start.sh                 Up                               
harbor-db           /entrypoint.sh postgres          Up      5432/tcp                 
harbor-jobservice   /harbor/start.sh                 Up                               
harbor-log          /bin/sh -c /usr/local/bin/ ...   Up      127.0.0.1:1514->10514/tcp
harbor-portal       nginx -g daemon off;             Up      80/tcp                   
nginx               nginx -g daemon off;             Up      0.0.0.0:180->80/tcp      
redis               docker-entrypoint.sh redis ...   Up      6379/tcp                 
registry            /entrypoint.sh /etc/regist ...   Up      5000/tcp                 
registryctl         /harbor/start.sh                 Up                               
[root@hdss7-200 harbor]# 

6.配置harbor的dns内网解析

在HDSS7-11 DNS服务器上:
root@hdss7-11 ~]# vim /var/named/od.com.zone
2021031902 ; serial # 这个每次修改配置,都需要修改一下
harbor             A    10.4.7.200
# 注意serial前滚一个序号

# 重启named
[root@hdss7-11 ~]# named-checkconf 
[root@hdss7-11 ~]# systemctl restart named

# 测试
[root@hdss7-11 ~]# dig -t A harbor.od.com +short
10.4.7.200
[root@hdss7-11 ~]# 

7.安装nginx并配置

HDSS7-200主机上:
用nginx代理180端口:
[root@hdss7-200 ~]# yum install nginx -y 
[root@hdss7-200 ~]# vim /etc/nginx/conf.d/harbor.od.com.conf
server {
    listen       80;
    server_name  harbor.od.com;

    client_max_body_size 1000m;

    location / {
        proxy_pass http://127.0.0.1:180;
    }
}

[root@hdss7-200 ~]# nginx -t
[root@hdss7-200 ~]# systemctl enable nginx
[root@hdss7-200 ~]# systemctl start nginx

8.浏览器打开http://harbor.od.com

账号为admin 密码是Harbor12345

9.检查

1.登录harbor,创建public仓库

2.从docker.io下载镜像nginx:1.7.9

[root@hdss7-200 ~]# docker pull nginx:1.7.9

3.打tag

[root@hdss7-200 ~]# docker images|grep 1.7.9
nginx                           1.7.9                      84581e99d807   6 years ago     91.7MB
[root@hdss7-200 ~]# docker tag 84581e99d807 harbor.od.com/public/nginx:v1.7.9

4.登录私有仓库,并推送镜像nginx

[root@hdss7-200 ~]# docker login harbor.od.com
Username: admin
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
[root@hdss7-200 ~]# docker push harbor.od.com/public/nginx:v1.7.9

5.查看仓库

第五章:部署主控节点服务

1.部署etcd集群

1.集群规划

主机名 角色 ip
HDSS7-12.host.com etcd lead 10.4.7.12
HDSS7-21.host.com etcd follow 10.4.7.21
HDSS7-22.host.com etcd follow 10.4.7.22

注意:这里部署文档以HDSS7-12.host.com主机为例,另外两台主机安装部署方法类似

2.创建基于根证书的config配置文件

运维主机HDSS7-200.host.com

root@hdss7-200 ~]# cd /opt/certs/
[root@hdss7-200 certs]# vim ca-config.json
{
    "signing": {
        "default": {
            "expiry": "175200h"
        },
        "profiles": {
            "server": {
                "expiry": "175200h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth"
                ]
            },
            "client": {
                "expiry": "175200h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "client auth"
                ]
            },
            "peer": {
                "expiry": "175200h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth",
                    "client auth"
                ]
            }
        }
    }
}
证书类型
client certificate:客户端使用,用于服务端认证客户端,例如etcdctl、etcd proxy、fleetctl、docker客户端
server certificate:服务器端使用,客户端已验证服务端身份,例如docker服务端、kube-apiserver
peer certificate:双向证书,用于etcd集群成员间通信

3.创建生成证书签名请求(csr)的JSON配置文件

运维主机HDSS7-200.host.com上:

root@hdss7-200 ~]# cd /opt/certs/
[root@hdss7-200 certs]# vim etcd-peer-csr.json 
{
    "CN": "etcd-peer",
    "hosts": [
        "10.4.7.11",
        "10.4.7.12",
        "10.4.7.21",
        "10.4.7.22"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ]
}

4.生成etcd证书和私钥

[root@hdss7-200 certs]# pwd
/opt/certs
[root@hdss7-200 certs]# ls
ca-config.json  ca.csr  ca-csr.json  ca-key.pem  ca.pem  etcd-peer-csr.json
[root@hdss7-200 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=peer etcd-peer-csr.json|cfssl-json -bare etcd-peer
2021/03/22 16:00:36 [INFO] generate received request
2021/03/22 16:00:36 [INFO] received CSR
2021/03/22 16:00:36 [INFO] generating key: rsa-2048
2021/03/22 16:00:37 [INFO] encoded CSR
2021/03/22 16:00:37 [INFO] signed certificate with serial number 201550033673956140770976702993206605492139599119
2021/03/22 16:00:37 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").
[root@hdss7-200 certs]# ls etcd-peer*
etcd-peer.csr  etcd-peer-csr.json  etcd-peer-key.pem  etcd-peer.pem
[root@hdss7-200 certs]# 

5.创建etcd用户

[root@hdss7-12 ~]# useradd -s /sbin/nologin  -M etcd
[root@hdss7-21 ~]# useradd -s /sbin/nologin  -M etcd
[root@hdss7-22 ~]# useradd -s /sbin/nologin  -M etcd

6.下载软件,解压,做软连接

etcd下载地址

这里使用的是etcd-v3.1.20
三台机器上都要安装:

[root@hdss7-12 ~]# mkdir /opt/src
[root@hdss7-12 ~]# cd /opt/src/
[root@hdss7-12 ~]# wget https://github.com/etcd-io/etcd/releases/download/v3.1.20/etcd-v3.1.20-linux-amd64.tar.gz
[root@hdss7-12 src]# tar xf etcd-v3.1.20-linux-amd64.tar.gz  -C /opt/
[root@hdss7-12 src]# cd /opt/
[root@hdss7-12 opt]# ls
etcd-v3.1.20-linux-amd64  src
[root@hdss7-12 opt]# mv etcd-v3.1.20-linux-amd64/ etcd-v3.1.20
[root@hdss7-12 opt]# ln -s /opt/etcd-v3.1.20/ /opt/etcd
[root@hdss7-12 opt]# 

7.创建目录,拷贝证书,私钥

  • 创建目录
[root@hdss7-12 ~]# mkdir -p /opt/etcd/certs /data/etcd /data/logs/etcd-server
  • 拷贝证书
[root@hdss7-12 ~]# cd /opt/etcd/certs/
[root@hdss7-12 certs]# scp hdss7-200:/opt/certs/ca.pem .
[root@hdss7-12 certs]# scp hdss7-200:/opt/certs/etcd-peer.pem .
[root@hdss7-12 certs]# scp hdss7-200:/opt/certs/etcd-peer-key.pem .
[root@hdss7-12 certs]# ls
ca.pem  etcd-peer-key.pem  etcd-peer.pem
[root@hdss7-12 certs]#

将运维主机上生成的ca.pem,etcd-peer-key.pem,etcd-peer.pem拷贝到/ope/etcd/certs目录中,注意私钥权限600。

  • 修改权限
    [root@hdss7-12 certs]# chown -R etcd.etcd /opt/etcd/certs /data/etcd /data/logs/etcd-server
    [root@hdss7-12 certs]# chown  -R etcd.etcd /opt/etcd-v3.1.20/

    8.创建etcd服务启动脚本

/opt/etcd/etcd-server-startup.sh

#!/bin/sh
./etcd --name etcd-server-7-12 \
       --data-dir /data/etcd/etcd-server \
       --listen-peer-urls https://10.4.7.12:2380 \
       --listen-client-urls https://10.4.7.12:2379,http://127.0.0.1:2379 \
       --quota-backend-bytes 8000000000 \
       --initial-advertise-peer-urls https://10.4.7.12:2380 \
       --advertise-client-urls https://10.4.7.12:2379,http://127.0.0.1:2379 \
       --initial-cluster  etcd-server-7-12=https://10.4.7.12:2380,etcd-server-7-21=https://10.4.7.21:2380,etcd-server-7-22=https://10.4.7.22:2380 \
       --ca-file ./certs/ca.pem \
       --cert-file ./certs/etcd-peer.pem \
       --key-file ./certs/etcd-peer-key.pem \
       --client-cert-auth  \
       --trusted-ca-file ./certs/ca.pem \
       --peer-ca-file ./certs/ca.pem \
       --peer-cert-file ./certs/etcd-peer.pem \
       --peer-key-file ./certs/etcd-peer-key.pem \
       --peer-client-cert-auth \
       --peer-trusted-ca-file ./certs/ca.pem \
       --log-output stdout

添加执行权限:

[root@hdss7-12 ~]# chmod  +x /opt/etcd/etcd-server-startup.sh 

注意:etcd集群各主机的启动脚本略有不同,部署其他节点时注意修改。

9.安装supervisor软件

[root@hdss7-12 ~]# yum install supervisor -y
[root@hdss7-12 ~]# systemctl start supervisord
[root@hdss7-12 ~]# systemctl enable supervisord

10.创建etcd-server的启动配置

HDSS7-12.host.com上:

/etc/supervisord.d/etcd-server.ini

[program:etcd-server-7-12]
command=/opt/etcd/etcd-server-startup.sh                        ; the program (relative uses PATH, can take args)
numprocs=1                                                      ; number of processes copies to start (def 1)
directory=/opt/etcd                                             ; directory to cwd to before exec (def no cwd)
autostart=true                                                  ; start at supervisord start (default: true)
autorestart=true                                                ; retstart at unexpected quit (default: true)
startsecs=22                                                    ; number of secs prog must stay running (def. 1)
startretries=3                                                  ; max # of serial start failures (default 3)
exitcodes=0,2                                                   ; 'expected' exit codes for process (default 0,2)
stopsignal=QUIT                                                 ; signal used to kill process (default TERM)
stopwaitsecs=10                                                 ; max num secs to wait b4 SIGKILL (default 10)
user=etcd                                                       ; setuid to this UNIX account to run the program
redirect_stderr=false                                           ; redirect proc stderr to stdout (default false)
stdout_logfile=/data/logs/etcd-server/etcd.stdout.log           ; stdout log path, NONE for none; default AUTO
stdout_logfile_maxbytes=64MB                                    ; max # logfile bytes b4 rotation (default 50MB)
stdout_logfile_backups=4                                        ; # of stdout logfile backups (default 10)
stdout_capture_maxbytes=1MB                                     ; number of bytes in 'capturemode' (default 0)
stdout_events_enabled=false                                     ; emit events on stdout writes (default false)
stderr_logfile=/data/logs/etcd-server/etcd.stderr.log           ; stderr log path, NONE for none; default AUTO
stderr_logfile_maxbytes=64MB                                    ; max # logfile bytes b4 rotation (default 50MB)
stderr_logfile_backups=4                                        ; # of stderr logfile backups (default 10)
stderr_capture_maxbytes=1MB                                     ; number of bytes in 'capturemode' (default 0)
stderr_events_enabled=false                                     ; emit events on stderr writes (default false)

注意:etcd集群各主机启动配置略有不同,配置其他节点时注意修改。

11.启动etcd服务并检查

[root@hdss7-12 ~]# supervisorctl update
etcd-server-7-12: added process group
[root@hdss7-12 ~]# supervisorctl status
etcd-server-7-12                 RUNNING   pid 8145, uptime 0:00:26
[root@hdss7-12 ~]# netstat  -lntup|grep etcd
tcp        0      0 10.4.7.12:2379          0.0.0.0:*               LISTEN      8146/./etcd         
tcp        0      0 127.0.0.1:2379          0.0.0.0:*               LISTEN      8146/./etcd         
tcp        0      0 10.4.7.12:2380          0.0.0.0:*               LISTEN      8146/./etcd         

12.安装部署启动检查所有集群规划的etcd服务

从第五步开始操作,配置节点时注意修改。

13.检查etcd集群状态

[root@hdss7-22 ~]# cd /opt/etcd
[root@hdss7-22 etcd]# ./etcdctl  cluster-health
member 988139385f78284 is healthy: got healthy result from http://127.0.0.1:2379
member 5a0ef2a004fc4349 is healthy: got healthy result from http://127.0.0.1:2379
member f4a0cb0a765574a8 is healthy: got healthy result from http://127.0.0.1:2379
cluster is healthy
[root@hdss7-22 etcd]# ./etcdctl member list
988139385f78284: name=etcd-server-7-22 peerURLs=https://10.4.7.22:2380 clientURLs=http://127.0.0.1:2379,https://10.4.7.22:2379 isLeader=false
5a0ef2a004fc4349: name=etcd-server-7-21 peerURLs=https://10.4.7.21:2380 clientURLs=http://127.0.0.1:2379,https://10.4.7.21:2379 isLeader=false
f4a0cb0a765574a8: name=etcd-server-7-12 peerURLs=https://10.4.7.12:2380 clientURLs=http://127.0.0.1:2379,https://10.4.7.12:2379 isLeader=true
[root@hdss7-22 etcd]# 

2.部署kube-apiserver集群

1.集群规划

主机名 角色 ip 版本
HDSS7-21.host.com kube-apiserver 10.4.7.21 v1.15.2
HDSS7-22.host.com kube-apiserver 10.4.7.22 v1.15.2
HDSS7-11.host.com 4层负载均衡 10.4.7.11
HDSS7-12.host.com 4层负载均衡 10.4.7.12
注意:这里10.4.7.1110.4.7.12使用nginx做4层负载均衡器,用keepalived跑一个vip:10.4.7.10,代理两个kube-apiserver,实现高可用
这里部署文档以HDSS7-21.host.com主机为例,另外一台运算节点安装部署方法类似

2.下载软件,解压,做软连接

kubernetes官方Github地址
kubernetes下地址

[root@hdss7-21 etcd]# cd /opt/src/
[root@hdss7-21 src]# wget https://dl.k8s.io/v1.15.2/kubernetes-server-linux-amd64.tar.gz
[root@hdss7-21 src]# tar xf kubernetes-server-linux-amd64-v1.15.2.tar.gz  -C /opt/
[root@hdss7-21 src]# cd /opt/
[root@hdss7-21 opt]# mv kubernetes/ kubernetes-v1.15.2
[root@hdss7-21 opt]# ln -s /opt/kubernetes-v1.15.2/ /opt/kubernetes
# 删除源码
[root@hdss7-21 opt]# cd kubernetes
[root@hdss7-21 kubernetes]# rm -f kubernetes-src.tar.gz 
# 删除docker镜像
[root@hdss7-21 kubernetes]# cd server/bin/
[root@hdss7-21 bin]# rm -f *.tar
[root@hdss7-21 bin]# rm -f *_tag

3.签发client证书

运维主机HDSS7-200.host.com上:

1.创建生成证书请求(csr)的JSON配置文件

[root@hdss7-200 certs]# vim /opt/certs/client-csr.json
{
    "CN": "k8s-node",
    "hosts": [
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ]
}

2.生成client证书和私钥

[root@hdss7-200 certs]# pwd
/opt/certs
[root@hdss7-200 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=client client-csr.json |cfssl-json -bare client
2021/03/22 18:35:34 [INFO] generate received request
2021/03/22 18:35:34 [INFO] received CSR
2021/03/22 18:35:34 [INFO] generating key: rsa-2048
2021/03/22 18:35:34 [INFO] encoded CSR
2021/03/22 18:35:34 [INFO] signed certificate with serial number 618522899307354876284159939419899716688778468335
2021/03/22 18:35:34 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

3.检查生成的证书和私钥

[root@hdss7-200 certs]# ll client*
-rw-r--r-- 1 root root  993 Mar 22 18:35 client.csr
-rw-r--r-- 1 root root  280 Mar 22 18:34 client-csr.json
-rw------- 1 root root 1679 Mar 22 18:35 client-key.pem
-rw-r--r-- 1 root root 1363 Mar 22 18:35 client.pem

4.签发kube-apiserver证书

运维主机HDSS7-200.host.com上:

1.创建生成证书签名请求(csr)的josn配置文件

[root@hdss7-200 ~]# cat /opt/certs/apiserver-csr.json 
{
    "CN": "apiserver",
    "hosts": [
        "127.0.0.1",
        "192.168.0.1",
        "kubernetes.default",
        "kubernetes.default.svc",
        "kubernetes.default.svc.cluster",
        "kubernetes.default.svc.cluster.local",
        "10.4.7.10",
        "10.4.7.21",
        "10.4.7.22",
        "10.4.7.23",
        "10.4.7.24"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ]
}
[root@hdss7-200 ~]#

2.生成kube-apiserver证书和私钥

[root@hdss7-200 ~]# cd /opt/certs/
[root@hdss7-200 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=server apiserver-csr.json |cfssl-json -bare apiserver
2021/03/22 18:44:52 [INFO] generate received request
2021/03/22 18:44:52 [INFO] received CSR
2021/03/22 18:44:52 [INFO] generating key: rsa-2048
2021/03/22 18:44:52 [INFO] encoded CSR
2021/03/22 18:44:52 [INFO] signed certificate with serial number 27716320331827529174259696028778658707078846977
2021/03/22 18:44:52 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").
[root@hdss7-200 certs]# 

3.检查生成的证书和私钥

[root@hdss7-200 certs]# ll apiserver*
-rw-r--r-- 1 root root 1253 Mar 22 18:44 apiserver.csr
-rw-r--r-- 1 root root  583 Mar 22 18:41 apiserver-csr.json
-rw------- 1 root root 1679 Mar 22 18:44 apiserver-key.pem
-rw-r--r-- 1 root root 1602 Mar 22 18:44 apiserver.pem
[root@hdss7-200 certs]# 

5.拷贝证书至各个运算节点,并创建配置

HDSS7-21.host.com上,HDSS7-22.host.com上:

  • 拷贝证书

    # 1 先创建目录
    [root@hdss7-21 ~]# cd /opt/kubernetes/server/bin/
    [root@hdss7-21 bin]# mkdir cert
    # 2 各个运算节点上远程拷贝证书到本地服务器
    [root@hdss7-21 cert]# pwd
    /opt/kubernetes/server/bin/cert
    [root@hdss7-21 cert]# scp hdss7-200:/opt/certs/apiserver-key.pem .
    [root@hdss7-21 cert]# scp hdss7-200:/opt/certs/apiserver.pem .
    [root@hdss7-21 cert]# scp hdss7-200:/opt/certs/ca-key.pem .
    [root@hdss7-21 cert]# scp hdss7-200:/opt/certs/ca.pem .
    [root@hdss7-21 cert]# scp hdss7-200:/opt/certs/client-key.pem .
    [root@hdss7-21 cert]# scp hdss7-200:/opt/certs/client.pem .
    [root@hdss7-21 cert]# ll
    total 24
    -rw------- 1 root root 1675 Feb  3 20:15 apiserver-key.pem
    -rw-r--r-- 1 root root 1594 Feb  3 20:15 apiserver.pem
    -rw------- 1 root root 1675 Feb  3 20:15 ca-key.pem
    -rw-r--r-- 1 root root 1346 Feb  3 20:15 ca.pem
    -rw------- 1 root root 1675 Feb  3 20:16 client-key.pem
    -rw-r--r-- 1 root root 1363 Feb  3 20:16 client.pem
  • 创建配置文件

    [root@hdss7-22 bin]# pwd
    /opt/kubernetes/server/bin
    [root@hdss7-21 bin]# mkdir  conf
    [root@hdss7-21 bin]# vim /opt/kubernetes/server/bin/conf/audit.yaml
    apiVersion: audit.k8s.io/v1beta1 # This is required.
    kind: Policy
    # Don't generate audit events for all requests in RequestReceived stage.
    omitStages:
    - "RequestReceived"
    rules:
    # Log pod changes at RequestResponse level
    - level: RequestResponse
      resources:
      - group: ""
        # Resource "pods" doesn't match requests to any subresource of pods,
        # which is consistent with the RBAC policy.
        resources: ["pods"]
    # Log "pods/log", "pods/status" at Metadata level
    - level: Metadata
      resources:
      - group: ""
        resources: ["pods/log", "pods/status"]
    
    # Don't log requests to a configmap called "controller-leader"
    - level: None
      resources:
      - group: ""
        resources: ["configmaps"]
        resourceNames: ["controller-leader"]
    
    # Don't log watch requests by the "system:kube-proxy" on endpoints or services
    - level: None
      users: ["system:kube-proxy"]
      verbs: ["watch"]
      resources:
      - group: "" # core API group
        resources: ["endpoints", "services"]
    
    # Don't log authenticated requests to certain non-resource URL paths.
    - level: None
      userGroups: ["system:authenticated"]
      nonResourceURLs:
      - "/api*" # Wildcard matching.
      - "/version"
    
    # Log the request body of configmap changes in kube-system.
    - level: Request
      resources:
      - group: "" # core API group
        resources: ["configmaps"]
      # This rule only applies to resources in the "kube-system" namespace.
      # The empty string "" can be used to select non-namespaced resources.
      namespaces: ["kube-system"]
    
    # Log configmap and secret changes in all other namespaces at the Metadata level.
    - level: Metadata
      resources:
      - group: "" # core API group
        resources: ["secrets", "configmaps"]
    
    # Log all other resources in core and extensions at the Request level.
    - level: Request
      resources:
      - group: "" # core API group
      - group: "extensions" # Version of group should NOT be included.
    
    # A catch-all rule to log all other requests at the Metadata level.
    - level: Metadata
      # Long-running requests like watches that fall under this rule will not
      # generate an audit event in RequestReceived.
      omitStages:
        - "RequestReceived"

    6.创建启动脚本

    [root@hdss7-21 bin]# vim /opt/kubernetes/server/bin/kube-apiserver.sh
    #!/bin/bash
    ./kube-apiserver \
    --apiserver-count 2 \
    --audit-log-path /data/logs/kubernetes/kube-apiserver/audit-log \
    --audit-policy-file ./conf/audit.yaml \
    --authorization-mode RBAC \
    --client-ca-file ./cert/ca.pem \
    --requestheader-client-ca-file ./cert/ca.pem \
    --enable-admission-plugins NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota \
    --etcd-cafile ./cert/ca.pem \
    --etcd-certfile ./cert/client.pem \
    --etcd-keyfile ./cert/client-key.pem \
    --etcd-servers https://10.4.7.12:2379,https://10.4.7.21:2379,https://10.4.7.22:2379 \
    --service-account-key-file ./cert/ca-key.pem \
    --service-cluster-ip-range 192.168.0.0/16 \
    --service-node-port-range 3000-29999 \
    --target-ram-mb=1024 \
    --kubelet-client-certificate ./cert/client.pem \
    --kubelet-client-key ./cert/client-key.pem \
    --log-dir  /data/logs/kubernetes/kube-apiserver \
    --tls-cert-file ./cert/apiserver.pem \
    --tls-private-key-file ./cert/apiserver-key.pem \
    --v 2

    7.调整权限和目录

    [root@hdss7-21 bin]# chmod  +x /opt/kubernetes/server/bin/kube-apiserver.sh 
    [root@hdss7-21 bin]# mkdir -p /data/logs/kubernetes/kube-apiserver

    8.创建supervisor配置

    [root@hdss7-21 bin]# vim /etc/supervisord.d/kube-apiserver.ini
    [program:kube-apiserver-7-21]
    command=/opt/kubernetes/server/bin/kube-apiserver.sh            ; the program (relative uses PATH, can take args)
    numprocs=1                                                      ; number of processes copies to start (def 1)
    directory=/opt/kubernetes/server/bin                            ; directory to cwd to before exec (def no cwd)
    autostart=true                                                  ; start at supervisord start (default: true)
    autorestart=true                                                ; retstart at unexpected quit (default: true)
    startsecs=22                                                    ; number of secs prog must stay running (def. 1)
    startretries=3                                                  ; max # of serial start failures (default 3)
    exitcodes=0,2                                                   ; 'expected' exit codes for process (default 0,2)
    stopsignal=QUIT                                                 ; signal used to kill process (default TERM)
    stopwaitsecs=10                                                 ; max num secs to wait b4 SIGKILL (default 10)
    user=root                                                       ; setuid to this UNIX account to run the program
    redirect_stderr=false                                           ; redirect proc stderr to stdout (default false)
    stdout_logfile=/data/logs/kubernetes/kube-apiserver/apiserver.stdout.log        ; stdout log path, NONE for none; default AUTO
    stdout_logfile_maxbytes=64MB                                    ; max # logfile bytes b4 rotation (default 50MB)
    stdout_logfile_backups=4                                        ; # of stdout logfile backups (default 10)
    stdout_capture_maxbytes=1MB                                     ; number of bytes in 'capturemode' (default 0)
    stdout_events_enabled=false                                     ; emit events on stdout writes (default false)
    stderr_logfile=/data/logs/kubernetes/kube-apiserver/apiserver.stderr.log        ; stderr log path, NONE for none; default AUTO
    stderr_logfile_maxbytes=64MB                                    ; max # logfile bytes b4 rotation (default 50MB)
    stderr_logfile_backups=4                                        ; # of stderr logfile backups (default 10)
    stderr_capture_maxbytes=1MB                                     ; number of bytes in 'capturemode' (default 0)
    stderr_events_enabled=false                                     ; emit events on stderr writes (default false)
    ;子进程还有子进程,需要添加这个参数,避免产生孤儿进程
    killagroup=true
    stopasgroup=true

    9.启动服务并检查

    [root@hdss7-21 bin]# supervisorctl update
    kube-apiserver-7-21: added process group
    [root@hdss7-21 bin]# supervisorctl status
    etcd-server-7-21                 RUNNING   pid 29079, uptime 3:48:52
    kube-apiserver-7-21              RUNNING   pid 29587, uptime 0:00:35
    [root@hdss7-21 bin]# 

    10.安装部署启动检查所有集群规划主机上的kube-apiserver

HDSS7-22.host.com从第2步下载软件,不需要再生成证书了,第5步拷贝证书。

注意: [program:kube-apiserver-7-22]

[root@hdss7-22 ~]# supervisorctl status
etcd-server-7-22                 RUNNING   pid 19138, uptime 5:24:13
kube-apiserver-7-22              RUNNING   pid 19766, uptime 0:02:12
[root@hdss7-22 ~]# 

11.kube-apiserver服务监听端口

[root@hdss7-22 ~]# netstat  -lngtup|grep kube-apiser
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      19767/./kube-apiser 
tcp6       0      0 :::6443                 :::*                    LISTEN      19767/./kube-apiser 
[root@hdss7-22 ~]# 

12.配4层反向代理,代理kube-apiserver

HDSS7-11.host.com,HDSS7-12.host.com

[root@hdss7-11 ~]# yum install nginx -y

/etc/nginx/nginx.conf,结尾处添加如下内容

stream {
    upstream kube-apiserver {
        server 10.4.7.21:6443     max_fails=3 fail_timeout=30s;
        server 10.4.7.22:6443     max_fails=3 fail_timeout=30s;
    }
    server {
        listen 7443;
        proxy_connect_timeout 2s;
        proxy_timeout 900s;
        proxy_pass kube-apiserver;
    }
}

[root@hdss7-11 ~]# 
[root@hdss7-11 ~]# nginx  -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@hdss7-11 ~]# systemctl enable nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@hdss7-11 ~]# systemctl start nginx
[root@hdss7-11 ~]# ss -lnt |grep 7443
LISTEN     0      511          *:7443                     *:*                  
[root@hdss7-11 ~]# 

keepalived配置

[root@hdss7-11 ~]# yum install keepalived -y

#check_port.sh
/etc/keepalived/check_port.sh
#!/bin/bash
#keepalived 监控端口脚本
#使用方法:
#在keepalived的配置文件中
#vrrp_script check_port {#创建一个vrrp_script脚本,检查配置
#    script "/etc/keepalived/check_port.sh 6379" #配置监听的端口
#    interval 2 #检查脚本的频率,单位(秒)
#}
CHK_PORT=$1
if [ -n "$CHK_PORT" ];then
        PORT_PROCESS=`ss -lnt|grep $CHK_PORT|wc -l`
        if [ $PORT_PROCESS -eq 0 ];then
                echo "Port $CHK_PORT Is Not Used,End."
                exit 1
        fi
else
        echo "Check Port Cant Be Empty!"
fi
# 执行权限
[root@hdss7-11 ~]# chmod  +x /etc/keepalived/check_port.sh

keepalived主配置文件

[root@hdss7-11 ~]# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id 10.4.7.11

}

vrrp_script chk_nginx {
    script "/etc/keepalived/check_port.sh 7443"
    interval 2
    weight -20
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 251
    priority 100
    advert_int 1
    mcast_src_ip 10.4.7.11
    nopreempt

    authentication {
        auth_type PASS
        auth_pass 11111111
    }
    track_script {
         chk_nginx
    }
    virtual_ipaddress {
        10.4.7.10
    }
}
[root@hdss7-11 ~]# 
keepalived备

HDSS7-12.host.com

/etc/keepalived/keepalived.conf

! Configuration File for keepalived
global_defs {
    router_id 10.4.7.12
}
vrrp_script chk_nginx {
    script "/etc/keepalived/check_port.sh 7443"
    interval 2
    weight -20
}
vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 251
    mcast_src_ip 10.4.7.12
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 11111111
    }
    track_script {
        chk_nginx
    }
    virtual_ipaddress {
        10.4.7.10
    }
}

13.启动代理并检查

  • 启动
[root@hdss7-11 ~]# systemctl start keepalived
[root@hdss7-11 ~]# systemctl enable keepalived
[root@hdss7-11 ~]# nginx -s reload

[root@hdss7-12 ~]# systemctl start keepalived
[root@hdss7-12 ~]# systemctl enable keepalived
[root@hdss7-12 ~]# nginx -s reload
  • 检查
[root@hdss7-11 ~]# netstat -luntp|grep 7443
tcp        0      0 0.0.0.0:7443            0.0.0.0:*               LISTEN      28657/nginx: master 
[root@hdss7-12 ~]# netstat -luntp|grep 7443
tcp        0      0 0.0.0.0:7443            0.0.0.0:*               LISTEN      29366/nginx: master 
[root@hdss7-11 ~]# ip addr|grep 10.4.7.10
    inet 10.4.7.10/32 scope global eth0
[root@hdss7-11 ~]# 
[root@hdss7-12 ~]# ip add|grep 10.4.7.10
[root@hdss7-12 ~]# 

3.部署controller-manager

1.集群规划

主机名 角色 ip
HDSS7-21.host.com controller-manager 10.4.7.21
HDSS7-22.host.com controller-manager 10.4.7.22

注意:这里部署文档以HDSS7-21.host.com主机为例,另外一台运算节点安装部署方法类似

2.创建启动脚本

#apiserve、controller-manager、kube-scheduler三个服务所需的软件在同一套压缩包里面,因此后两个服务不需要再单独解包
#而且这三个服务是在同一个主机上,互相之间通过http://127.0.0.1访问,也不需要证书

/opt/kubernetes/server/bin/kube-controller-manager.sh

#!/bin/sh
./kube-controller-manager \
  --cluster-cidr 172.7.0.0/16 \
  --leader-elect true \
  --log-dir /data/logs/kubernetes/kube-controller-manager \
  --master http://127.0.0.1:8080 \
  --service-account-private-key-file ./cert/ca-key.pem \
  --service-cluster-ip-range 192.168.0.0/16 \
  --root-ca-file ./cert/ca.pem \
  --v 2

3.调整文件权限,创建目录

[root@hdss7-21 bin]# chmod +x /opt/kubernetes/server/bin/kube-controller-manager.sh
[root@hdss7-21 bin]# mkdir -p /data/logs/kubernetes/kube-controller-manager

4.创建supervisor配置

/etc/supervisord.d/kube-conntroller-manager.ini

[program:kube-controller-manager-7-21]
command=/opt/kubernetes/server/bin/kube-controller-manager.sh                     ; the program (relative uses PATH, can take args)
numprocs=1                                                                        ; number of processes copies to start (def 1)
directory=/opt/kubernetes/server/bin                                              ; directory to cwd to before exec (def no cwd)
autostart=true                                                                    ; start at supervisord start (default: true)
autorestart=true                                                                  ; retstart at unexpected quit (default: true)
startsecs=30                                                                      ; number of secs prog must stay running (def. 1)
startretries=3                                                                    ; max # of serial start failures (default 3)
exitcodes=0,2                                                                     ; 'expected' exit codes for process (default 0,2)
stopsignal=QUIT                                                                   ; signal used to kill process (default TERM)
stopwaitsecs=10                                                                   ; max num secs to wait b4 SIGKILL (default 10)
user=root                                                                         ; setuid to this UNIX account to run the program
redirect_stderr=true                                                              ; redirect proc stderr to stdout (default false)
killasgroup=true                                                                  ; kill all process in a group
stopasgroup=true                                                                  ; stop all process in a group
stdout_logfile=/data/logs/kubernetes/kube-controller-manager/controller.stdout.log  ; stderr log path, NONE for none; default AUTO
stdout_logfile_maxbytes=64MB                                                      ; max # logfile bytes b4 rotation (default 50MB)
stdout_logfile_backups=4                                                          ; # of stdout logfile backups (default 10)
stdout_capture_maxbytes=1MB                                                       ; number of bytes in 'capturemode' (default 0)
stdout_events_enabled=false                                                       ; emit events on stdout writes (default false)
;子进程还有子进程,需要添加这个参数,避免产生孤儿进程
killagroup=true
stopasgroup=true

5.启动服务并检查

[root@hdss7-21 bin]# supervisorctl update
kube-controller-manager-7-21: added process group
[root@hdss7-21 bin]# supervisorctl status
etcd-server-7-21                 RUNNING   pid 29079, uptime 21:39:50
kube-apiserver-7-21              RUNNING   pid 29587, uptime 17:51:33
kube-controller-manager-7-21     RUNNING   pid 30315, uptime 0:01:39

[root@hdss7-22 ~]# supervisorctl update
kube-controller-manager-7-22: added process group
[root@hdss7-22 ~]# supervisorctl status
etcd-server-7-22                 RUNNING   pid 19138, uptime 17:25:44
kube-apiserver-7-22              RUNNING   pid 19766, uptime 12:03:43
kube-controller-manager-7-22     RUNNING   pid 20145, uptime 0:01:24
[root@hdss7-22 ~]# 

4.部署kube-scheduler

1.集群规划

主机名 角色 ip
HDSS7-21.host.com controller-manager 10.4.7.21
HDSS7-22.host.com controller-manager 10.4.7.22

注意:这里部署文档以HDSS7-21.host.com主机为例,另外一台运算节点安装部署方法类似

2.创建启动脚本

/opt/kubernetes/server/bin/kube-scheduler.sh

#!/bin/sh
./kube-scheduler \
  --leader-elect  \
  --log-dir /data/logs/kubernetes/kube-scheduler \
  --master http://127.0.0.1:8080 \
  --v 2

3.调整文件权限,创建目录

[root@hdss7-21 bin]# chmod +x /opt/kubernetes/server/bin/kube-scheduler.sh
[root@hdss7-21 bin]# mkdir -p /data/logs/kubernetes/kube-scheduler

4.创建supervisor配置

/etc/supervisord.d/kube-scheduler.ini

[program:kube-scheduler-7-21]
command=/opt/kubernetes/server/bin/kube-scheduler.sh                     ; the program (relative uses PATH, can take args)
numprocs=1                                                               ; number of processes copies to start (def 1)
directory=/opt/kubernetes/server/bin                                     ; directory to cwd to before exec (def no cwd)
autostart=true                                                           ; start at supervisord start (default: true)
autorestart=true                                                         ; retstart at unexpected quit (default: true)
startsecs=22                                                             ; number of secs prog must stay running (def. 1)
startretries=3                                                           ; max # of serial start failures (default 3)
exitcodes=0,2                                                            ; 'expected' exit codes for process (default 0,2)
stopsignal=QUIT                                                          ; signal used to kill process (default TERM)
stopwaitsecs=10                                                          ; max num secs to wait b4 SIGKILL (default 10)
user=root                                                                ; setuid to this UNIX account to run the program
redirect_stderr=false                                                    ; redirect proc stderr to stdout (default false)
stdout_logfile=/data/logs/kubernetes/kube-scheduler/scheduler.stdout.log ; stdout log path, NONE for none; default AUTO
stdout_logfile_maxbytes=64MB                                             ; max # logfile bytes b4 rotation (default 50MB)
stdout_logfile_backups=4                                                 ; # of stdout logfile backups (default 10)
stdout_capture_maxbytes=1MB                                              ; number of bytes in 'capturemode' (default 0)
stdout_events_enabled=false                                              ; emit events on stdout writes (default false)
stderr_logfile=/data/logs/kubernetes/kube-scheduler/scheduler.stderr.log ; stderr log path, NONE for none; default AUTO
stderr_logfile_maxbytes=64MB                                             ; max # logfile bytes b4 rotation (default 50MB)
stderr_logfile_backups=4                                                 ; # of stderr logfile backups (default 10)
stderr_capture_maxbytes=1MB                                              ; number of bytes in 'capturemode' (default 0)
stderr_events_enabled=false                                              ; emit events on stderr writes (default false)
killagroup=true
stopasgroup=true

5.启动服务并检查

[root@hdss7-21 ~]# supervisorctl update
kube-scheduler-7-21: added process group
[root@hdss7-21 ~]# supervisorctl status
etcd-server-7-21                 RUNNING   pid 21621, uptime 18:44:35
kube-apiserver-7-21              RUNNING   pid 22849, uptime 0:18:38
kube-controller-manager-7-21     RUNNING   pid 22878, uptime 0:17:15
kube-scheduler-7-21              RUNNING   pid 22911, uptime 0:03:29

6.安装部署启动检查所有集群规划主机上的kube-scheduler服务

[root@hdss7-22 ~]# supervisorctl update
kube-scheduler-7-22: added process group
[root@hdss7-22 ~]# supervisorctl status
etcd-server-7-22                 RUNNING   pid 19138, uptime 17:55:08
kube-apiserver-7-22              RUNNING   pid 19766, uptime 12:33:07
kube-controller-manager-7-22     RUNNING   pid 20145, uptime 0:30:48
kube-scheduler-7-22              RUNNING   pid 20187, uptime 0:13:56
[root@hdss7-22 ~]# 

6.检查主控节点

[root@hdss7-21 ~]# ln -s /opt/kubernetes/server/bin/kubectl  /usr/bin/kubectl
[root@hdss7-21 ~]# kubectl get cs
NAME                 STATUS    MESSAGE              ERROR
scheduler            Healthy   ok                   
controller-manager   Healthy   ok                   
etcd-1               Healthy   {"health": "true"}   
etcd-0               Healthy   {"health": "true"}   
etcd-2               Healthy   {"health": "true"}   
[root@hdss7-21 ~]# 

[root@hdss7-22 ~]# ln -s /opt/kubernetes/server/bin/kubectl  /usr/bin/kubectl
[root@hdss7-22 ~]# kubectl get cs
NAME                 STATUS    MESSAGE              ERROR
controller-manager   Healthy   ok                   
scheduler            Healthy   ok                   
etcd-1               Healthy   {"health": "true"}   
etcd-2               Healthy   {"health": "true"}   
etcd-0               Healthy   {"health": "true"}   
[root@hdss7-22 ~]# 

第六章:部署运算节点服务

1.部署kubelet

1.集群规划

主机名 角色 ip
HDSS7-21.host.com kubelet 10.4.7.21
HDSS7-22.host.com kubelet 10.4.7.22

注意:这里部署文档以HDSS7-21.host.com主机为例,另外一台运算节点安装部署方法类似

2.签发kubelet证书

运维主机HDSS7-200.host.com上:

1.创建生成证书签名请求(csr)的JSON配置文件

/opt/certs/kubelet-csr.json

{
    "CN": "kubelet-node",
    "hosts": [
    "127.0.0.1",
    "10.4.7.10",
    "10.4.7.21",
    "10.4.7.22",
    "10.4.7.23",
    "10.4.7.24",
    "10.4.7.25",
    "10.4.7.26",
    "10.4.7.27",
    "10.4.7.28"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ]
}

2.生成kubelet证书和私钥

[root@hdss7-200 ~]# cd /opt/certs/
[root@hdss7-200 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=server kubelet-csr.json | cfssl-json -bare kubelet
2021/03/23 14:11:33 [INFO] generate received request
2021/03/23 14:11:33 [INFO] received CSR
2021/03/23 14:11:33 [INFO] generating key: rsa-2048
2021/03/23 14:11:34 [INFO] encoded CSR
2021/03/23 14:11:34 [INFO] signed certificate with serial number 559966770811055645402645807507417612409107759291
2021/03/23 14:11:34 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

3.检查生成证书的证书、私钥

[root@hdss7-200 certs]# ll kubelet*
-rw-r--r-- 1 root root 1119 Mar 23 14:11 kubelet.csr
-rw-r--r-- 1 root root  453 Mar 23 14:11 kubelet-csr.json
-rw------- 1 root root 1675 Mar 23 14:11 kubelet-key.pem
-rw-r--r-- 1 root root 1468 Mar 23 14:11 kubelet.pem
[root@hdss7-200 certs]# 

3.拷贝证书至各运算节点

# 1 将证书拷贝到运算节点
[root@hdss7-21 ~]# cd /opt/kubernetes/server/bin/cert/
[root@hdss7-21 cert]# scp hdss7-200:/opt/certs/kubelet-key.pem .
[root@hdss7-21 cert]# scp hdss7-200:/opt/certs/kubelet.pem .
# 2 将证书拷贝到其他运算节点上
[root@hdss7-22 ~]#  cd /opt/kubernetes/server/bin/cert/
[root@hdss7-22 cert]# scp hdss7-200:/opt/certs/kubelet-key.pem .
[root@hdss7-22 cert]# scp hdss7-200:/opt/certs/kubelet.pem .
[root@hdss7-21 cert]# ll
total 32
-rw------- 1 root root 1675 Feb  3 20:15 apiserver-key.pem
-rw-r--r-- 1 root root 1594 Feb  3 20:15 apiserver.pem
-rw------- 1 root root 1675 Feb  3 20:15 ca-key.pem
-rw-r--r-- 1 root root 1346 Feb  3 20:15 ca.pem
-rw------- 1 root root 1675 Feb  3 20:16 client-key.pem
-rw-r--r-- 1 root root 1363 Feb  3 20:16 client.pem
-rw------- 1 root root 1675 Feb  4 17:41 kubelet-key.pem
-rw-r--r-- 1 root root 1468 Feb  4 17:41 kubelet.pem
[root@hdss7-21 cert]# 

4.创建配置

给kubectl创建软连接

[root@hdss7-21~]# ln -s /opt/kubernetes/server/bin/kubectl  /usr/bin/kubectl

1.set-cluster

注意:在conf目录下
/opt/kubernetes/server/bin/conf

[root@hdss7-21 conf]# pwd
/opt/kubernetes/server/bin/conf

[root@hdss7-21 conf]# kubectl config set-cluster myk8s \
  --certificate-authority=/opt/kubernetes/server/bin/cert/ca.pem \
  --embed-certs=true \
  --server=https://10.4.7.10:7443 \
  --kubeconfig=kubelet.kubeconfig

Cluster "myk8s" set.

2.set-credentials

注意:在conf目录下

/opt/kubernetes/server/bin/conf

[root@hdss7-21 conf]# kubectl config set-credentials k8s-node --client-certificate=/opt/kubernetes/server/bin/cert/client.pem --client-key=/opt/kubernetes/server/bin/cert/client-key.pem --embed-certs=true --kubeconfig=kubelet.kubeconfig 
User "k8s-node" set.
[root@hdss7-21 conf]# 

3.set-context

注意:在conf目录下

/opt/kubernetes/server/bin/conf

[root@hdss7-21 conf]# kubectl config set-context myk8s-context \
  --cluster=myk8s \
  --user=k8s-node \
  --kubeconfig=kubelet.kubeconfig

Context "myk8s-context" created.

4.use-context

注意:在conf目录下

/opt/kubernetes/server/bin/conf

[root@hdss7-21 conf]# kubectl config use-context myk8s-context --kubeconfig=kubelet.kubeconfig
Switched to context "myk8s-context".
[root@hdss7-21 conf]# 

5.配置k8s-node.yaml

  • 创建资源配置文件
vim /opt/kubernetes/server/bin/conf/k8s-node.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: k8s-node
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:node
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: k8s-node
  • 应用资源配置文件,使集群角色用户生效
[root@hdss7-21 conf]# kubectl create -f k8s-node.yaml 
clusterrolebinding.rbac.authorization.k8s.io/k8s-node created
[root@hdss7-21 conf# 
  • 查看集群角色
[root@hdss7-21 conf]# kubectl  get clusterrolebinding k8s-node
NAME       AGE
k8s-node   13s
[root@hdss7-21 conf]# kubectl get clusterrolebinding k8s-node -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRoleBinding","metadata":{"annotations":{},"name":"k8s-node"},"roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"ClusterRole","name":"system:node"},"subjects":[{"apiGroup":"rbac.authorization.k8s.io","kind":"User","name":"k8s-node"}]}
  creationTimestamp: "2021-03-23T07:00:55Z"
  name: k8s-node
  resourceVersion: "18852"
  selfLink: /apis/rbac.authorization.k8s.io/v1/clusterrolebindings/k8s-node
  uid: 6fedafff-f40f-43d1-93b6-241a15bff507
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:node
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: k8s-node
[root@hdss7-21 conf]# 
  • 在HDSS7-22上等其他运算节点执行以下步骤,不需要上面的步骤
[root@hdss7-22 conf]# pwd
/opt/kubernetes/server/bin/conf
[root@hdss7-22 conf]# 
[root@hdss7-22 conf]# scp hdss7-21:/opt/kubernetes/server/bin/conf/kubelet.kubeconfig  .
[root@hdss7-22 conf]# ls
audit.yaml  kubelet.kubeconfig
[root@hdss7-22 conf]# 

5.准备pause基础镜像

运维主机HDSS7-200.host.com上:

  • 下载镜像
[root@hdss7-200 ~]# docker pull kubernetes/pause
  • 打标签
    [root@hdss7-200 ~]# docker images|grep pause
    kubernetes/pause                latest                     f9d5de079539   6 years ago     240kB
    [root@hdss7-200 ~]# docker tag f9d5de079539 harbor.od.com/public/pause:latest
    [root@hdss7-200 ~]# 
  • 推送镜像到私有仓库中
    [root@hdss7-200 ~]# docker push harbor.od.com/public/pause:latest

    6.创建kubelet启动脚本

    HDSS7-21.host.com上,HDSS7-22.host.com上:

注意:kubelet集群各主机的启动脚本略有不同,部署其他节点时注意修改。

/opt/kubernetes/server/bin/kubelet.sh

#!/bin/sh
./kubelet \
  --anonymous-auth=false \
  --cgroup-driver systemd \
  --cluster-dns 192.168.0.2 \
  --cluster-domain cluster.local \
  --runtime-cgroups=/systemd/system.slice --kubelet-cgroups=/systemd/system.slice \
  --fail-swap-on="false" \
  --client-ca-file ./cert/ca.pem \
  --tls-cert-file ./cert/kubelet.pem \
  --tls-private-key-file ./cert/kubelet-key.pem \
  --hostname-override hdss7-21.host.com \
  --image-gc-high-threshold 20 \
  --image-gc-low-threshold 10 \
  --kubeconfig ./conf/kubelet.kubeconfig \
  --log-dir /data/logs/kubernetes/kube-kubelet \
  --pod-infra-container-image harbor.od.com/public/pause:latest \
  --root-dir /data/kubelet

hostname-override 不同

7.检查配置,权限,创建日志目录

[root@hdss7-21 conf]# pwd
/opt/kubernetes/server/bin/conf
[root@hdss7-21 conf]# ls -l|grep kubelet.kubeconfig 
-rw------- 1 root root 6195 Feb  4 17:55 kubelet.kubeconfig
[root@hdss7-21 conf]# chmod +x /opt/kubernetes/server/bin/kubelet.sh 
[root@hdss7-21 conf]# mkdir -p /data/logs/kubernetes/kube-kubelet /data/kubelet
[root@hdss7-21 conf]# 

8.创建supervisor配置

vi /etc/supervisord.d/kube-kubelet.ini
[root@hdss7-21 ~]# more /etc/supervisord.d/kube-kubelet.ini 
[program:kube-kubelet-7-21]
command=/opt/kubernetes/server/bin/kubelet.sh                 ; the program (relative uses PATH, can take args)
numprocs=1                                                        ; number of processes copies to start (def 1)
directory=/opt/kubernetes/server/bin                              ; directory to cwd to before exec (def no cwd)
autostart=true                                                    ; start at supervisord start (default: true)
autorestart=true                                                    ; retstart at unexpected quit (default: true)
startsecs=22                                                        ; number of secs prog must stay running (def. 1)
startretries=3                                                      ; max # of serial start failures (default 3)
exitcodes=0,2                                                       ; 'expected' exit codes for process (default 0,2)
stopsignal=QUIT                                                     ; signal used to kill process (default TERM)
stopwaitsecs=10                                                     ; max num secs to wait b4 SIGKILL (default 10)
user=root                                                         ; setuid to this UNIX account to run the program
redirect_stderr=false                                             ; redirect proc stderr to stdout (default false)
stdout_logfile=/data/logs/kubernetes/kube-kubelet/kubelet.stdout.log   ; stdout log path, NONE for none; default AUTO
stdout_logfile_maxbytes=64MB                                      ; max # logfile bytes b4 rotation (default 50MB)
stdout_logfile_backups=4                                          ; # of stdout logfile backups (default 10)
stdout_capture_maxbytes=1MB                                       ; number of bytes in 'capturemode' (default 0)
stdout_events_enabled=false                                       ; emit events on stdout writes (default false)
stderr_logfile=/data/logs/kubernetes/kube-kubelet/kubelet.stderr.log   ; stderr log path, NONE for none; default AUTO
stderr_logfile_maxbytes=64MB                                      ; max # logfile bytes b4 rotation (default 50MB)
stderr_logfile_backups=4                                          ; # of stderr logfile backups (default 10)
stderr_capture_maxbytes=1MB                                         ; number of bytes in 'capturemode' (default 0)
stderr_events_enabled=false                                         ; emit events on stderr writes (default false)
[root@hdss7-21 ~]# 

9.启动服务并检查

[root@hdss7-21 conf]# supervisorctl update
kube-kubelet-7-21: added process group
[root@hdss7-21 conf]# supervisorctl status
etcd-server-7-21                 RUNNING   pid 21621, uptime 1 day, 0:44:15
kube-apiserver-7-21              RUNNING   pid 22849, uptime 6:18:18
kube-controller-manager-7-21     RUNNING   pid 22878, uptime 6:16:55
kube-kubelet-7-21                RUNNING   pid 23651, uptime 0:01:51
kube-scheduler-7-21              RUNNING   pid 22911, uptime 6:03:09
[root@hdss7-21 conf]# 

10.检查运算节点

[root@hdss7-21 ~]# kubectl get nodes
NAME                STATUS   ROLES    AGE     VERSION
hdss7-21.host.com   Ready    <none>   2m20s   v1.15.12
[root@hdss7-21 ~]# 

11.同理在另外一台服务器进行配置,此步骤省略

[root@hdss7-22 ~]# supervisorctl status
etcd-server-7-22                 RUNNING   pid 21749, uptime 0:02:42
kube-apiserver-7-22              RUNNING   pid 20968, uptime 0:13:51
kube-controller-manager-7-22     RUNNING   pid 20965, uptime 0:13:51
kube-kubelet-7-22                RUNNING   pid 21098, uptime 0:04:51
kube-scheduler-7-22              RUNNING   pid 20966, uptime 0:13:51
[root@hdss7-22 ~]# 

12.检查所有的运算节点

[root@hdss7-22 ~]# kubectl get nodes
NAME                STATUS   ROLES    AGE     VERSION
hdss7-21.host.com   Ready    <none>   38m     v1.15.12
hdss7-22.host.com   Ready    <none>   5m21s   v1.15.12
[root@hdss7-22 ~]# 

13.给nod节点打标签

[root@hdss7-22 ~]# kubectl label node hdss7-21.host.com node-role.kubernetes.io/master=
node/hdss7-21.host.com labeled
[root@hdss7-22 ~]# kubectl label node hdss7-21.host.com node-role.kubernetes.io/node=
node/hdss7-21.host.com labeled
[root@hdss7-22 ~]# kubectl label node hdss7-22.host.com node-role.kubernetes.io/master=
node/hdss7-22.host.com labeled
[root@hdss7-22 ~]# kubectl label node hdss7-22.host.com node-role.kubernetes.io/node=
node/hdss7-22.host.com labeled
[root@hdss7-22 ~]# 

14.再次查看所有的运算节点

[root@hdss7-21 cert]# kubectl get nodes
NAME                STATUS   ROLES         AGE   VERSION
hdss7-21.host.com   Ready    master,node   43m   v1.15.12
hdss7-22.host.com   Ready    master,node   10m   v1.15.12
[root@hdss7-21 cert]# 
[root@hdss7-21 cert]# kubectl get nodes -o wide
NAME                STATUS   ROLES         AGE   VERSION    INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION               CONTAINER-RUNTIME
hdss7-21.host.com   Ready    master,node   43m   v1.15.12   10.4.7.21     <none>        CentOS Linux 7 (Core)   3.10.0-957.12.1.el7.x86_64   docker://20.10.5
hdss7-22.host.com   Ready    master,node   10m   v1.15.12   10.4.7.22     <none>        CentOS Linux 7 (Core)   3.10.0-957.12.1.el7.x86_64   docker://20.10.5
[root@hdss7-21 cert]# 

2.部署kube-proxy

1.集群规划

主机名 角色 ip
HDSS7-21.host.com kube-proxy 10.4.7.21
HDSS7-22.host.com kube-proxy 10.4.7.22

注意:这里部署文档以HDSS7-21.host.com主机为例,另外一台运算节点安装部署方法类似

2.签发kube-proxy证书

运维主机HDSS7-200.host.com上:

1.创建生成证书签名请求(csr)的JSON配置文件

/opt/certs/kube-proxy-csr.json
{
    "CN": "system:kube-proxy",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ]
}

2.生成kube-proxy证书和私钥

[root@hdss7-200 ~]# cd /opt/certs/
[root@hdss7-200 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=client kube-proxy-csr.json | cfssl-json -bare kube-proxy-client
2021/03/23 18:43:48 [INFO] generate received request
2021/03/23 18:43:48 [INFO] received CSR
2021/03/23 18:43:48 [INFO] generating key: rsa-2048
2021/03/23 18:43:49 [INFO] encoded CSR
2021/03/23 18:43:49 [INFO] signed certificate with serial number 254542935330912055520303684419526203587788111468
2021/03/23 18:43:49 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

3.检查生成的证书、私钥

[root@hdss7-200 certs]# ll -lh kube-proxy-*
-rw-r--r-- 1 root root 1005 Feb  5 11:56 kube-proxy-client.csr
-rw------- 1 root root 1.7K Feb  5 11:56 kube-proxy-client-key.pem
-rw-r--r-- 1 root root 1.4K Feb  5 11:56 kube-proxy-client.pem
-rw-r--r-- 1 root root  267 Feb  5 11:55 kube-proxy-csr.json

4.拷贝证书到运算节点

[root@hdss7-21 ~]# cd /opt/kubernetes/server/bin/cert/
[root@hdss7-21 cert]# scp hdss7-200:/opt/certs/kube-proxy-client-key.pem .
[root@hdss7-21 cert]# scp hdss7-200:/opt/certs/kube-proxy-client.pem .
[root@hdss7-22 ~]# cd /opt/kubernetes/server/bin/cert/
[root@hdss7-22 cert]# scp hdss7-200:/opt/certs/kube-proxy-client-key.pem .
[root@hdss7-22 cert]# scp hdss7-200:/opt/certs/kube-proxy-client.pem .

3.创建配置

注意:在conf目录下

  • set-cluster
/opt/kubernetes/server/bin/conf

[root@hdss7-21 conf]# kubectl config set-cluster myk8s \
  --certificate-authority=/opt/kubernetes/server/bin/cert/ca.pem \
  --embed-certs=true \
  --server=https://10.4.7.10:7443 \
  --kubeconfig=kube-proxy.kubeconfig

Cluster "myk8s" set.
  • set-credentials
/opt/kubernetes/server/bin/conf
[root@hdss7-21 conf]# kubectl config set-credentials kube-proxy \
  --client-certificate=/opt/kubernetes/server/bin/cert/kube-proxy-client.pem \
  --client-key=/opt/kubernetes/server/bin/cert/kube-proxy-client-key.pem \
  --embed-certs=true \
  --kubeconfig=kube-proxy.kubeconfig

User "kube-proxy" set.
  • set-context
/opt/kubernetes/server/bin/conf
[root@hdss7-21 conf]# kubectl config set-context myk8s-context \
  --cluster=myk8s \
  --user=kube-proxy \
  --kubeconfig=kube-proxy.kubeconfig

Context "myk8s-context" created.
  • use-context
/opt/kubernetes/server/bin/conf

[root@hdss7-21 conf]# kubectl config use-context myk8s-context --kubeconfig=kube-proxy.kubeconfig

Switched to context "myk8s-context".

HDSS7-22.host.com不需要创建配置,需要将配置文件直接拷贝到HDSS7-22.host.com上就可以了。

[root@hdss7-22 conf]# pwd
/opt/kubernetes/server/bin/conf
[root@hdss7-22 conf]# scp hdss7-21:/opt/kubernetes/server/bin/conf/kube-proxy.kubeconfig .

4.创建kube-proxy启动脚本

HDSS7-21.host.comHDSS7-22.host.com

  • 加载ipvs模块
[root@hdss7-21 ~]# more /root/ipvs.sh 
#!/bin/bash
ipvs_mods_dir="/usr/lib/modules/$(uname -r)/kernel/net/netfilter/ipvs"
for i in $(ls $ipvs_mods_dir|grep -o "^[^.]*")
do
  /sbin/modinfo -F filename $i &>/dev/null
  if [ $? -eq 0 ];then
    /sbin/modprobe $i
  fi
done
[root@hdss7-21 ~]# 
[root@hdss7-21 ~]# sh /root/ipvs.sh 
[root@hdss7-21 ~]# lsmod |grep ip_vs
ip_vs_wrr              12697  0 
ip_vs_wlc              12519  0 
ip_vs_sh               12688  0 
ip_vs_sed              12519  0 
ip_vs_rr               12600  0 
ip_vs_pe_sip           12740  0 
nf_conntrack_sip       33860  1 ip_vs_pe_sip
ip_vs_nq               12516  0 
ip_vs_lc               12516  0 
ip_vs_lblcr            12922  0 
ip_vs_lblc             12819  0 
ip_vs_ftp              13079  0 
ip_vs_dh               12688  0 
ip_vs                 145497  24 ip_vs_dh,ip_vs_lc,ip_vs_nq,ip_vs_rr,ip_vs_sh,ip_vs_ftp,ip_vs_sed,ip_vs_wlc,ip_vs_wrr,ip_vs_pe_sip,ip_vs_lblcr,ip_vs_lblc
nf_nat                 26583  3 ip_vs_ftp,nf_nat_ipv4,nf_nat_masquerade_ipv4
nf_conntrack          137239  8 ip_vs,nf_nat,nf_nat_ipv4,xt_conntrack,nf_nat_masquerade_ipv4,nf_conntrack_netlink,nf_conntrack_sip,nf_conntrack_ipv4
libcrc32c              12644  4 xfs,ip_vs,nf_nat,nf_conntrack
  • 创建启动脚本
vi /opt/kubernetes/server/bin/kube-proxy.sh
#!/bin/sh
./kube-proxy \
  --cluster-cidr 172.7.0.0/16 \
  --hostname-override hdss7-21.host.com \
  --proxy-mode=ipvs \
  --ipvs-scheduler=nq \
  --kubeconfig ./conf/kube-proxy.kubeconfig
  • 检查配置,权限,创建日志目录
[root@hdss7-21 ~]#  cd /opt/kubernetes/server/bin/conf/
[root@hdss7-21 conf]# ls -l|grep kube-proxy.kubeconfig 
-rw------- 1 root root 6215 Feb  5 13:55 kube-proxy.kubeconfig
[root@hdss7-21 conf]# chmod  +x /opt/kubernetes/server/bin/kube-proxy.sh 
[root@hdss7-21 conf]# mkdir -p /data/logs/kubernetes/kube-proxy
  • 创建supervisor配置
 vi /etc/supervisord.d/kube-proxy.ini
[program:kube-proxy-7-21]
command=/opt/kubernetes/server/bin/kube-proxy.sh                 ; the program (relative uses PATH, can take args)
numprocs=1                                                           ; number of processes copies to start (def 1)
directory=/opt/kubernetes/server/bin                                 ; directory to cwd to before exec (def no cwd)
autostart=true                                                       ; start at supervisord start (default: true)
autorestart=true                                                     ; retstart at unexpected quit (default: true)
startsecs=22                                                         ; number of secs prog must stay running (def. 1)
startretries=3                                                       ; max # of serial start failures (default 3)
exitcodes=0,2                                                        ; 'expected' exit codes for process (default 0,2)
stopsignal=QUIT                                                      ; signal used to kill process (default TERM)
stopwaitsecs=10                                                      ; max num secs to wait b4 SIGKILL (default 10)
user=root                                                                 ; setuid to this UNIX account to run the program
redirect_stderr=false                                                    ; redirect proc stderr to stdout (default false)
stdout_logfile=/data/logs/kubernetes/kube-proxy/proxy.stdout.log     ; stdout log path, NONE for none; default AUTO
stdout_logfile_maxbytes=64MB                                             ; max # logfile bytes b4 rotation (default 50MB)
stdout_logfile_backups=4                                                 ; # of stdout logfile backups (default 10)
stdout_capture_maxbytes=1MB                                              ; number of bytes in 'capturemode' (default 0)
stdout_events_enabled=false                                              ; emit events on stdout writes (default false)
stderr_logfile=/data/logs/kubernetes/kube-proxy/proxy.stderr.log     ; stderr log path, NONE for none; default AUTO
stderr_logfile_maxbytes=64MB                                             ; max # logfile bytes b4 rotation (default 50MB)
stderr_logfile_backups=4                                                 ; # of stderr logfile backups (default 10)
stderr_capture_maxbytes=1MB                                                      ; number of bytes in 'capturemode' (default 0)
stderr_events_enabled=false                                                      ; emit events on stderr writes (default false)
  • 启动服务并检查
[root@hdss7-21 ~]# supervisorctl update
kube-proxy-7-21: added process group
[root@hdss7-21 ~]# supervisorctl status
etcd-server-7-21                 RUNNING   pid 29079, uptime 1 day, 21:35:45
kube-apiserver-7-21              RUNNING   pid 29587, uptime 1 day, 17:47:28
kube-controller-manager-7-21     RUNNING   pid 30315, uptime 23:57:34
kube-kubelet-7-21                RUNNING   pid 31647, uptime 3:34:23
kube-proxy-7-21                  RUNNING   pid 73993, uptime 0:01:07
kube-scheduler-7-21              RUNNING   pid 30240, uptime 1 day, 0:15:26
[root@hdss7-21 ~]# 
  • 再部署另外一个节点,省略配置,检查服务
    [root@hdss7-22 ~]# supervisorctl update
    kube-proxy-7-22: added process group
    [root@hdss7-22 ~]# supervisorctl status
    etcd-server-7-22                 RUNNING   pid 21749, uptime 4:07:23
    kube-apiserver-7-22              RUNNING   pid 20968, uptime 4:18:32
    kube-controller-manager-7-22     RUNNING   pid 20965, uptime 4:18:32
    kube-kubelet-7-22                RUNNING   pid 21098, uptime 4:09:32
    kube-proxy-7-22                  RUNNING   pid 70141, uptime 0:00:54
    kube-scheduler-7-22              RUNNING   pid 20966, uptime 4:18:32
    [root@hdss7-22 ~]# 
  • 验证
[root@hdss7-21 ~]# yum install ipvsadm -y
[root@hdss7-21 conf]# ipvsadm -Ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.0.1:443 nq
  -> 10.4.7.21:6443               Masq    1      0          0         
  -> 10.4.7.22:6443               Masq    1      0          0         
[root@hdss7-21 conf]# 
[root@hdss7-21 ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   

第七章:完成部署并验证集群

  • 验证kubernetes集群
  • 集群运算节点登录harbor
[root@hdss7-21 ~]# docker login harbor.od.com
Username: admin
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
  • 创建pod
[root@hdss7-21 ~]# cat /root/nginx-ds.yaml
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: nginx-ds
spec:
  template:
    metadata:
      labels:
        app: nginx-ds
    spec:
      containers:
      - name: my-nginx
        image: harbor.od.com/public/nginx:v1.7.9
        ports:
        - containerPort: 80
[root@hdss7-21 ~]# 
[root@hdss7-21 ~]# kubectl  create -f nginx-ds.yaml 
daemonset.extensions/nginx-ds created
  • 查看pod
[root@hdss7-21 ~]# kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-ds-8crpq   1/1     Running   0          2m41s
nginx-ds-hfzgk   1/1     Running   0          2m41s
[root@hdss7-21 ~]# kubectl get pods -o wide
NAME             READY   STATUS    RESTARTS   AGE     IP           NODE        NOMINATED NODE   READINESS GATES
nginx-ds-8crpq   1/1     Running   0          2m50s   172.7.22.2   10.4.7.22   <none>           <none>
nginx-ds-hfzgk   1/1     Running   0          2m50s   172.7.21.2   10.4.7.21   <none>           <none>
[root@hdss7-21 ~]# 
[root@hdss7-21 ~]# curl 172.7.21.2 
[root@hdss7-21 ~]# curl 172.7.22.2
[root@hdss7-21 ~]# curl 172.7.22.2 
curl: (7) Failed connect to 172.7.22.2:80; Connection timed out
[root@hdss7-21 ~]# 
  • 集群状态
[root@hdss7-21 ~]# kubectl  get cs
NAME                 STATUS    MESSAGE              ERROR
controller-manager   Healthy   ok                   
scheduler            Healthy   ok                   
etcd-2               Healthy   {"health": "true"}   
etcd-0               Healthy   {"health": "true"}   
etcd-1               Healthy   {"health": "true"}   
[root@hdss7-21 ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   192.168.0.1   <none>        443/TCP   27h
[root@hdss7-21 ~]# kubectl get nodes
NAME                STATUS   ROLES         AGE     VERSION
hdss7-21.host.com   Ready    master,node   5h5m    v1.15.12
hdss7-22.host.com   Ready    master,node   4h32m   v1.15.12
[root@hdss7-21 ~]# kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-ds-fw5mt   1/1     Running   0          13m
nginx-ds-sjtwx   1/1     Running   0          5m33s
[root@hdss7-21 ~]# 
文档更新时间: 2021-03-23 22:51   作者:xtyang