基于腾讯云搭建简易k8s集群

时间:2024-02-18 20:05:45

二进制搭建K8S


k8s是目前相完善成熟的一个容器治理的解决方案,算是微服务的的基础设施之一。这篇随笔主要就记录下自己搭建k8s集群的这么一个过程。选择二进制的方式是这样的方式能更好的理解k8s各个组件的关系。


集群环境准备

本文选用腾讯云作为演示环境。

服务器列表

这3台服务器是买的时间不一样,所处可用区不一致,一台是广东3区的,两台是广东4区的,为了简化集群网络,需要使用腾讯云提供的私有网络的功能搭建一套私有网络。

HostName IP 角色 备注
tencent-3-10 10.47.3.10 cfssl,harbor,nfs,bind,etcd 基础设施
tencent-4-11 10.47.4.11 master,node,etcd k8s集群-1
tencent-4-12 10.47.4.12 master,node,etcd k8s集群-2

k8s网络规划图

k8snetwork

节点网络:宿主机网络
容器网络:docker容器间的网络
service网络:虚拟网络,通过kube-proxy连接到具体的pod网络


前期准备

安装bind

在宿主网络提供dns解析服务,方便后续操作。 这些基础设施为了使操作简历,使用yum安装,如果在封闭的生产环境,请自行查询离线安装方式,不在本文讨论范围内。

10.47.3.10

  • 安装bind
[root@tencent-3-10 ~]# yum install -y bind
  • 修改named配置
# 修改配置,主要修改
[root@tencent-3-10 ~]# vi /etc/named.conf
options {
        //宿主机ip
        listen-on port 53 { 10.47.3.10; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        recursing-file  "/var/named/data/named.recursing";
        secroots-file   "/var/named/data/named.secroots";
        //允许访问的网段,根据实际情况修改
        allow-query     { 10.47.3.0/24; 10.47.4.0/24;  };
        //上级dns服务器,183.60.83.19为腾讯云私有网络的dns,202.96.134.133为深圳主dns
        forwarders      { 183.60.83.19; 202.96.134.133; };
        //递归查询
        recursion yes;

        dnssec-enable no;
        dnssec-validation no;

        bindkeys-file "/etc/named.root.key";

        managed-keys-directory "/var/named/dynamic";

        pid-file "/run/named/named.pid";
        session-keyfile "/run/named/session.key";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
        type hint;
        file "named.ca";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
  • 添加区域文件配置
[root@tencent-3-10 ~]# vi /etc/named.rfc1912.zones
// 在文件末尾添加
//要解析域名,根据实际需要修改
zone "limitest.cn" IN {
        type  master;
        //文件名,需保证文件名与下一步操作文件相同
        file  "limitest.cn.zone";
        allow-update { 10.47.3.10; };
};
  • 添加区域文件
[root@tencent-3-10 ~]# vi /var/named/limitest.cn.zone
// 创建文件
$ORIGIN limitest.cn.
$TTL 600  ; 10 minutes
@       IN SOA  dns.limitest.cn. dnsadmin.limitest.cn. (
        2020090101 ; serial
        10800      ; refresh (3 hours)
        900        ; retry (15 minutes)
        604800     ; expire (1 week)
        86400      ; minimum (1 day)
        )
        NS   dns.limitest.cn.
$TTL 60 ; 1 minute
dns                A    10.47.3.10
harbor             A    10.47.3.10
  • 启动服务并测试
[root@tencent-3-10 ~]# systemctl start named
[root@tencent-3-10 ~]# systemctl enable named
[root@tencent-3-10 ~]# dig -t A harbor.limitest.cn @10.47.3.10 +short
10.47.3.10

  • 在所有宿主机上配置dns,以tencent-3-10为例
[root@tencent-3-10 ~]# vi /etc/sysconfig/network-scripts/ifcfg-eth0
BOOTPROTO=dhcp
DEVICE=eth0
HWADDR=52:54:00:46:85:b4
ONBOOT=yes
PERSISTENT_DHCLIENT=yes
TYPE=Ethernet
USERCTL=no
DNS1=10.47.3.10
  • 重启服务并测试
[root@tencent-3-10 ~]# systemctl restart network
//检查域名对应的ip是否为我们前面所配
[root@tencent-3-10 ~]# ping harbor.limitest.cn
PING harbor.limitest.cn (10.47.3.10) 56(84) bytes of data.
64 bytes from tencent-3-10.host.com (10.47.3.10): icmp_seq=1 ttl=64 time=0.015 ms
64 bytes from tencent-3-10.host.com (10.47.3.10): icmp_seq=2 ttl=64 time=0.034 ms

签发证书

k8s各个组件之间都需要通过证书来访问,给各个组件签发证书是二进制安装k8s中最繁琐复杂的工作了。这里先总结下各个组件所需证书。一次性签发好所需的所有证书,方便后续部署。

  1. etcd:需要server证书,对外提供服务
  2. etcd:需要peer证书,各节点之间通讯使用
  3. kube-apiserver:需要client证书,访问etcd
  4. kube-apiserver:需要server证书,对外提供服务
  5. kube-scheduler:需要client证书,访问apiserver
  6. kube-controller-manager:需要client证书,访问apiserver
  7. kube-controller-manager:需要CA证书,签署service account的证书
  8. kube-proxy:需要client证书,访问apiserver
  9. kubelet:需要client证书,访问apiserver
  10. kubelet: 需要server证书,对外提供服务

其中大多数client证书可复用,因此合计下来部署k8s集群需要6套证书(包括ca证书)。明确了这些关系后,就可以开始准备证书。

文件名 说明
ca 根证书
etcd-peer etcd节点通讯用peer证书
apiserver apiserver服务端证书
kubelet kubelet服务端证书
kube-proxy kube-proxy 客户端证书(kube-proxy的CN需要为k8s种的角色,因此不用使用通用客户端证书)
client 通用客户端证书

10.47.3.10

  • 安装cfssl工具
[root@tencent-3-10 ~]# wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 -O /usr/local/bin/cfssl
[root@tencent-3-10 ~]# wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64 -O /usr/local/bin/cfssljson
[root@tencent-3-10 ~]# wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64 -O /usr/local/bin/cfssl-certinfo
[root@tencent-3-10 ~]# chmod u+x /usr/local/bin/cfssl*
  • 创建证书配置文件
[root@tencent-3-10 ~]# vi /opt/certs/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"
                ]
            }
        }
    }
} 
  • 创建证书签名请求文件
[root@tencent-3-10 ~]# vi /opt/certs/ca-csr.json
{
    "CN": "limitest.cn",
    "hosts": [
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "guangdong",
            "L": "shenzhen",
            "O": "limitest",
            "OU": "dev"
        }
    ],
    "ca": {
        "expiry": "175200h"
    }
}
[root@tencent-3-10 ~]# vi /opt/certs/apiserver-csr.json
{
    "CN": "k8s-apiserver",
    //host必须把所有需要部署kube-apiserver的节点ip都列入,考虑后续集群拓展,建议多列几个
    "hosts": [
        "127.0.0.1",
        "10.47.4.1",
        "kubernetes.default",
        "kubernetes.default.svc",
        "kubernetes.default.svc.cluster",
        "kubernetes.default.svc.cluster.local",
        "10.47.4.10",
        "10.47.4.11",
        "10.47.4.12",
        "10.47.4.13"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "guangdong",
            "L": "shenzhen",
            "O": "limitest",
            "OU": "dev"
        }
    ]
}
[root@tencent-3-10 ~]# vi /opt/certs/etcd-peer-csr.json
{
    "CN": "k8s-etcd",
    //host必须把所有需要部署etcd的节点ip都列入
    "hosts": [
        "10.47.3.10",
        "10.47.4.11",
        "10.47.4.12"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "guangdong",
            "L": "shenzhen",
            "O": "limitest",
            "OU": "dev"
        }
    ]
}
[root@tencent-3-10 ~]# vi /opt/certs/kubelet-csr.json
{
    "CN": "k8s-kubelet",
    "hosts": [
    "127.0.0.1",
    "10.47.3.10",
    "10.47.4.10",
    "10.47.4.11",
    "10.47.4.12",
    "10.47.4.13",
    "10.47.4.14",
    "10.47.4.15"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "guangdong",
            "L": "shenzhen",
            "O": "limitest",
            "OU": "dev"
        }
    ]
}
[root@tencent-3-10 ~]# vi /opt/certs/kube-proxy-csr.json
{
    "CN": "system:kube-proxy",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "guangdong",
            "L": "shenzhen",
            "O": "limitest",
            "OU": "dev"
        }
    ]
}
[root@tencent-3-10 ~]# vi /opt/certs/client-csr.json
{
    "CN": "k8s-node",
    "hosts": [
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "guangdong",
            "L": "shenzhen",
            "O": "limitest",
            "OU": "dev"
        }
    ]
}
  • 生成ca根证书
[root@tencent-3-10 ~]# cd /opt/certs
[root@tencent-3-10 certs]# cfssl gencert -initca ca-csr.json | cfssljson -bare ca
[root@tencent-3-10 certs]# ll | grep ca
-rw-r--r-- 1 root root  836 Aug 28 17:37 ca-config.json
-rw-r--r-- 1 root root 1009 Aug 28 17:43 ca.csr
-rw-r--r-- 1 root root  339 Aug 27 16:29 ca-csr.json
-rw------- 1 root root 1675 Aug 28 17:43 ca-key.pem
-rw-r--r-- 1 root root 1375 Aug 28 17:43 ca.pem
  • 签发etcd-peer证书
[root@tencent-3-10 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=peer etcd-peer-csr.json |cfssljson -bare etcd-peer
[root@tencent-3-10 certs]# ll | grep etcd-peer
-rw-r--r-- 1 root root 1066 Aug 29 23:59 etcd-peer.csr
-rw-r--r-- 1 root root  355 Aug 29 23:37 etcd-peer-csr.json
-rw------- 1 root root 1679 Aug 29 23:59 etcd-peer-key.pem
-rw-r--r-- 1 root root 1448 Aug 29 23:59 etcd-peer.pem
  • 签发apiserver证书
[root@tencent-3-10 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=server apiserver-csr.json |cfssljson -bare apiserver
[root@tencent-3-10 certs]# ll | grep apiser
-rw-r--r-- 1 root root 1261 Aug 30 00:01 apiserver.csr
-rw-r--r-- 1 root root  578 Aug 29 23:35 apiserver-csr.json
-rw------- 1 root root 1675 Aug 30 00:01 apiserver-key.pem
-rw-r--r-- 1 root root 1627 Aug 30 00:01 apiserver.pem
  • 签发kubelet证书
[root@tencent-3-10 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=server kubelet-csr.json | cfssljson -bare kubelet
[root@tencent-3-10 certs]# ll | grep kubelet
-rw-r--r-- 1 root root 1110 Aug 30 00:02 kubelet.csr
-rw-r--r-- 1 root root  435 Aug 29 23:56 kubelet-csr.json
-rw------- 1 root root 1679 Aug 30 00:02 kubelet-key.pem
-rw-r--r-- 1 root root 1476 Aug 30 00:02 kubelet.pem
  • 签发kube-proxy证书
[root@tencent-3-10 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=client kube-proxy-csr.json |cfssljson -bare kube-proxy
[root@tencent-3-10 certs]# ll | grep kube-proxy
-rw-r--r-- 1 root root 1017 Aug 30 00:04 kube-proxy.csr
-rw-r--r-- 1 root root  277 Aug 29 23:57 kube-proxy-csr.json
-rw------- 1 root root 1675 Aug 30 00:04 kube-proxy-key.pem
-rw-r--r-- 1 root root 1403 Aug 30 00:04 kube-proxy.pem
  • 签发client证书
[root@tencent-3-10 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=client client-csr.json |cfssljson -bare client
[root@tencent-3-10 certs]# ll | grep client
-rw-r--r-- 1 root root 1005 Aug 30 00:01 client.csr
-rw-r--r-- 1 root root  290 Aug 29 23:53 client-csr.json
-rw------- 1 root root 1675 Aug 30 00:01 client-key.pem
-rw-r--r-- 1 root root 1391 Aug 30 00:01 client.pem
  • 签发harbor证书
[root@tencent-3-10 certs]# vi /opt/certs/harbor-csr.json
{
    "CN": "harbor.limitest.cn",
    "hosts": [
        "10.47.3.10",
        "10.47.4.11",
        "10.47.4.12"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "guangdong",
            "L": "shenzhen",
            "O": "limitest",
            "OU": "dev"
        }
    ]
}
[root@tencent-3-10 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=peer harbor-csr.json |cfssljson -bare harbor
[root@tencent-3-10 certs]# ll | grep harbor
-rw-r--r-- 1 root root 1082 Aug 28 18:02 harbor.csr
-rw------- 1 root root 1679 Aug 28 18:02 harbor-key.pem
-rw-r--r-- 1 root root  364 Aug 28 18:02 harbor.limitest.cn-csr.json
-rw-r--r-- 1 root root 1460 Aug 28 18:02 harbor.pem

安装docker&docker-compose

docker容器服务是我们使用k8s必不可少的基础设施,docker-compose则提供一个简易的docker容器编排方案,都是本文需要的基础设施,因此3台宿主机都需要安装docker&docker-compose。

之前在中标麒麟安装docker服务的时候,使用yum安装折腾了半天。因此个人建议通过二进制安装方式部署比较具有普适性。官网文档很详细,操作也很简单,也不会太复杂。

本文使用docker-19.03.9docker-compose-1.26.2 作为安装演示。

10.47.3.10,10.47.4.11,10.47.4.12

  • 确认主机系统架构
[root@tencent-3-10 ~]# uname -a
Linux tencent-3-10.host.com 3.10.0-1062.18.1.el7.x86_64 #1 SMP Tue Mar 17 23:49:17 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
  • 安装docker
[root@tencent-3-10 ~]# wget https://download.docker.com/linux/static/stable/x86_64/docker-19.03.9.tgz
[root@tencent-3-10 ~]# tar xzvf docker-19.03.9.tgz
[root@tencent-3-10 ~]# cp docker/* /usr/bin/
  • 配置docker

设置docker开机自启动,由于是通过binaries方式安装,因此需要使用systemctl来管理则需要创建docker.service&docker.socket两个文件

[root@tencent-3-10 ~]# vi /etc/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd
ExecStartPost=/usr/sbin/iptables -P FORWARD ACCEPT
ExecReload=/bin/kill -s HUP $MAINPID
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
# Uncomment TasksMax if your systemd version supports it.
# Only systemd 226 and above support this version.
#TasksMax=infinity
TimeoutStartSec=0
# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes
# kill only the docker process, not all processes in the cgroup
KillMode=process
# restart the docker process if it exits prematurely
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target
[root@tencent-3-10 ~]# vi /etc/systemd/system/docker.socket
[Unit]
Description=Docker Socket for the API
PartOf=docker.service

[Socket]
ListenStream=/var/run/docker.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target
  • 配置docker参数
[root@tencent-3-10 ~]# vi /etc/docker/daemon.json
{
  //docker服务路径
  "graph": "/home/docker",
  "storage-driver": "overlay2",
  //如果使用的是内网的私有仓储,需要加可信任域
  "insecure-registries": ["harbor.limitest.cn"],
  //腾讯云服务肯定使用腾讯的源了
  "registry-mirrors": ["https://mirror.ccs.tencentyun.com"],
  //因为我们的网络规划图设计的容器网络是172.0.0.0/24,因此可根据宿主机的ip设置,如10.47.3.10对应bip为172.3.10.1
  "bip": "172.3.10.1/24",
  "live-restore": true
}
  • 启动docker服务,并设置为开机启动
[root@tencent-3-10 ~]# systemctl start docker
[root@tencent-3-10 ~]# systemctl enable docker
  • 安装docker-compose
[root@tencent-3-10 ~]# wget https://github.com/docker/compose/releases/download/1.26.2/docker-compose-Linux-x86_64
[root@tencent-3-10 ~]# mv docker-compose-Linux-x86_64 /usr/local/bin/docker-compose
[root@tencent-3-10 ~]# chmod +x /usr/local/bin/docker-compose
[root@tencent-3-10 ~]# ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
  • 查看是否安装成功
[root@tencent-3-10 src]# docker -v
Docker version 19.03.9, build 9d988398e7
[root@tencent-3-10 src]# docker-compose -v
docker-compose version 1.26.2, build eefe0d31

安装harbor

harbor提供私有镜像仓储的功能,方便环境的后续镜像发布管理。阿里、腾讯、京东等主流云厂商也有提供仓储服务,可直接购买使用。

本文使用的是harbor 1.9.4版本,harbor依赖docker&docker-compose,因此在安装前要确认docker服务是否OK

10.47.3.10

  • 从官网下载文件

如果网速比较慢,建议使用github文件加速服务,一般来说就是在链接前加上https://g.ioiox.com/

[root@tencent-3-10 ~]# wget https://g.ioiox.com/https://github.com/goharbor/harbor/releases/download/v1.9.4/harbor-offline-installer-v1.9.4.tgz
  • 解压建立软连接,方便后续升级
[root@tencent-3-10 ~]# tar xzvf harbor-offline-installer-v1.9.4.tgz
[root@tencent-3-10 ~]# mv harbor /opt/harbor-v1.9.4
[root@tencent-3-10 ~]# ln -s /opt/harbor-v1.9.4 /opt/harbor
  • 创建文件夹,证书

创建harbor数据&log路径,并将之前生成的harbor证书迁至当前文件夹

[root@tencent-3-10 ~]# mkdir -p /data/harbor/log
[root@tencent-3-10 ~]# mkdir -p /opt/harbor/certs
[root@tencent-3-10 ~]# cp /opt/certs/harbor.pem /opt/harbor/certs/
[root@tencent-3-10 ~]# cp /opt/certs/harbor-key.pem /opt/harbor/certs/
  • 修改harbor启动配置文件
[root@tencent-3-10 ~]# vi /opt/harbor/harbor.yml
hostname: harbor.limitest.cn

http:
  # 指定服务监听180端口
  port: 180

https:
  # https服务监听4431端口
  port: 4431
  # 证书
  certificate: /opt/harbor/certs/harbor.pem
  private_key: /opt/harbor/certs/harbor-key.pem

# admin登录密码
harbor_admin_password: 123456

database:
  password: root123
  max_idle_conns: 50
  max_open_conns: 100

# 数据目录
data_volume: /data/harbor

with self signed certificate.

clair:
  updaters_interval: 12

jobservice:
  max_job_workers: 10

notification:
  webhook_job_max_retry: 10

chart:
  absolute_url: disabled

log:
  level: info
  local:
    rotate_count: 50
    rotate_size: 200M
    # 日志目录
    location: /data/harbor/log

_version: 1.9.0

proxy:
  http_proxy:
  https_proxy:
  no_proxy:
  components:
    - core
    - jobservice
    - clair
  • 启动harbor服务
[root@tencent-3-10 ~]# cd /opt/harbor/
[root@tencent-3-10 harbor]# ./install.sh

主控节点部署

组件 部署节点 功能描述
etcd 10.47.3.10
10.47.4.11
10.47.4.12
提供高性能键值存储,因为etcd集群的选举机制,官方推荐部署奇数个节点。
kube-apiserver 10.47.4.11
10.47.4.12
负责对外提供restful的kubernetes api服务
kube-scheduler 10.47.4.11
10.47.4.12
监控节点信息,负责管理各个pod,节点之类的数据的调度
kube-controller-manager 10.47.4.11
10.47.4.12
控制器的集合,维护集群,包括拓展,滚动更新等

10.47.3.10,10.47.4.10,10.47.4.12

  • supervisor安装

在正式部署master节点前,安装一个辅助工具supervisor。supervisor是一套通用的进程管理程序,能将一个普通的命令行进程变为后台daemon,并进行进程管控。安装这个工具主要是方便我们后续各个组件的管理。

[root@tencent-3-10 ~]# yum install -y supervisor
[root@tencent-3-10 ~]# systemctl start supervisord
[root@tencent-3-10 ~]# systemctl enable supervisord

etcd部署

本文使用etcd-v3.1.20版本

10.47.4.11,10.47.4.12

  • 创建etcd用户
[root@tencent-3-10 ~]# useradd -s /sbin/nologin -M etcd
  • 解压软件包
[root@tencent-3-10 ~]# cd /opt/src
[root@tencent-3-10 src]# tar xzvf etcd-v3.1.20-linux-amd64.tar.gz
[root@tencent-3-10 src]# mv etcd-v3.1.20-linux-amd64 /opt/etcd-v3.1.20
[root@tencent-3-10 src]# ln -s /opt/etcd-v3.1.20/ /opt/etcd
  • 创建文件夹
[root@tencent-3-10 src]# mkdir -p /opt/etcd/certs/ /data/etcd /data/logs/etcd-server
  • 证书
[root@tencent-3-10 src]# cd /opt/certs
[root@tencent-3-10 certs]# cp ca.pem etcd-peer.pem etcd-peer-key.pem /opt/etcd/certs/
  • 创建启动脚本
[root@tencent-3-10 src]# cd /opt/etcd
[root@tencent-3-10 etcd]# vi etcd-server-startup.sh
[root@tencent-3-10 etcd]# chmod u+x etcd-server-startup.sh
[root@tencent-3-10 etcd]# chown -R etcd.etcd /opt/etcd/ /data/etcd /data/logs/etcd-server

#!/bin/sh
./etcd --name etcd-server-3-10 \
    --data-dir /data/etcd/etcd-server \
    --listen-peer-urls https://10.47.3.10:2380 \
    --listen-client-urls https://10.47.3.10:2379,http://127.0.0.1:2379 \
    --quota-backend-bytes 8000000000 \
    --initial-advertise-peer-urls https://10.47.3.10:2380 \
    --advertise-client-urls https://10.47.3.10:2379,http://127.0.0.1:2379 \
    --initial-cluster  etcd-server-3-10=https://10.47.3.10:2380,etcd-server-4-11=https://10.47.4.11:2380,etcd-server-4-12=https://10.47.4.12: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

name:集群环境中唯一标识,不要重复,建议根据ip来设置
listen-peer-urls:本节点与其他节点进行数据交换的监听地址,根据节点所在宿主机ip设置
listen-client-urls:本节点访问地址,对外提供服务,根据节点所在宿主机ip设置
initial-advertise-peer-urls:告知其他集群节点访问URL,根据节点所在宿主机ip设置
advertise-client-urls:用于通知其他节点,客户端接入本节点的监听地址,根据节点所在宿主机ip设置

  • 创建supervisor脚本
[root@tencent-3-10 etcd]# cat /etc/supervisord.d/etcd-server.ini 
[program:etcd-server-3-10]
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=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=etcd                                             ; setuid to this UNIX account to run the program
redirect_stderr=true                                  ; 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=5                              ; # 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)
  • 启动服务
[root@tencent-3-10 etcd]# supervisorctl update
[root@tencent-3-10 etcd]# supervisorctl status
  • 查看服务是否启动成功
[root@tencent-3-10 etcd]# netstat -lutup | grep etcd
tcp        0      0 tencent-3-10.host.:2379 0.0.0.0:*               LISTEN      24948/./etcd        
tcp        0      0 VM-3-10-centos:2379     0.0.0.0:*               LISTEN      24948/./etcd        
tcp        0      0 tencent-3-10.host.:2380 0.0.0.0:*               LISTEN      24948/./etcd 
  • 在将其他节点都成功启动后,查看集群状态
[root@tencent-3-10 ~]# ln -s /opt/etcd/etcdctl /usr/local/bin/
[root@tencent-3-10 ~]# etcdctl cluster-health
member 2963c955cf08aef0 is healthy: got healthy result from http://127.0.0.1:2379
member 786faa045851f444 is healthy: got healthy result from http://127.0.0.1:2379
member bc1a1af47878cad5 is healthy: got healthy result from http://127.0.0.1:2379
cluster is healthy
[root@tencent-3-10 ~]# etcdctl member list
2963c955cf08aef0: name=etcd-server-4-12 peerURLs=https://10.47.4.12:2380 clientURLs=http://127.0.0.1:2379,https://10.47.4.12:2379 isLeader=false
786faa045851f444: name=etcd-server-3-10 peerURLs=https://10.47.3.10:2380 clientURLs=http://127.0.0.1:2379,https://10.47.3.10:2379 isLeader=true
bc1a1af47878cad5: name=etcd-server-4-11 peerURLs=https://10.47.4.11:2380 clientURLs=http://127.0.0.1:2379,https://10.47.4.11:2379 isLeader=false

kube-apiserver部署

本文使用的kubernetes版本为kubernetes-server-v1.15.12

10.47.4.11,10.47.4.12

  • 下载文件并解压安装
[root@tencent-4-11 ~]# wget https://dl.k8s.io/v1.15.12/kubernetes-server-linux-amd64.tar.gz
[root@tencent-4-11 ~]# tar xzvf kubernetes-server-linux-amd64.tar.gz
[root@tencent-4-11 ~]# mv kubernetes /opt/kubernetes-v1.15.12
[root@tencent-4-11 ~]# ln -s /opt/kubernetes-v1.15.12/ /opt/kubernetes
  • 创建文件夹
[root@tencent-4-11 ~]# cd /opt/kubernetes/server/bin
[root@tencent-4-11 bin]# mkdir certs conf
  • 证书文件
[root@tencent-4-11 bin]# scp tencent-3-10:/opt/certs/apiserver.pem certs/  
[root@tencent-4-11 bin]# scp tencent-3-10:/opt/certs/apiserver-key.pem certs/
[root@tencent-4-11 bin]# scp tencent-3-10:/opt/certs/ca.pem certs/  
[root@tencent-4-11 bin]# scp tencent-3-10:/opt/certs/ca-key.pem certs/ 
[root@tencent-4-11 bin]# scp tencent-3-10:/opt/certs/client.pem certs/  
[root@tencent-4-11 bin]# scp tencent-3-10:/opt/certs/client-key.pem certs/
  • 配置apiserver日志
[root@tencent-4-11 bin]# vi conf/audit.yaml
apiVersion: audit.k8s.io/v1beta1 # This is required.
kind: Policy
omitStages:
  - "RequestReceived"
rules:
  - level: RequestResponse
    resources:
    - group: ""
      resources: ["pods"]
  - level: Metadata
    resources:
    - group: ""
      resources: ["pods/log", "pods/status"]

  - level: None
    resources:
    - group: ""
      resources: ["configmaps"]
      resourceNames: ["controller-leader"]

  - level: None
    users: ["system:kube-proxy"]
    verbs: ["watch"]
    resources:
    - group: "" # core API group
      resources: ["endpoints", "services"]

  - level: None
    userGroups: ["system:authenticated"]
    nonResourceURLs:
    - "/api*" # Wildcard matching.
    - "/version"

  - level: Request
    resources:
    - group: "" # core API group
      resources: ["configmaps"]
    namespaces: ["kube-system"]

  - level: Metadata
    resources:
    - group: "" # core API group
      resources: ["secrets", "configmaps"]

  - level: Request
    resources:
    - group: "" # core API group
    - group: "extensions" # Version of group should NOT be included.

  - level: Metadata
    omitStages:
      - "RequestReceived"
  • 运行脚本
[root@tencent-4-11 bin]# vi 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 ./certs/ca.pem \
  --requestheader-client-ca-file ./certs/ca.pem \
  --enable-admission-plugins NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota \
  --etcd-cafile ./certs/ca.pem \
  --etcd-certfile ./certs/client.pem \
  --etcd-keyfile ./certs/client-key.pem \
  --etcd-servers https://10.47.3.10:2379,https://10.47.4.11:2379,https://10.47.4.12:2379 \
  --service-account-key-file ./certs/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 ./certs/client.pem \
  --kubelet-client-key ./certs/client-key.pem \
  --log-dir  /data/logs/kubernetes/kube-apiserver \
  --tls-cert-file ./certs/apiserver.pem \
  --tls-private-key-file ./certs/apiserver-key.pem \
  --v 2
[root@tencent-4-11 bin]# chmod +x kube-apiserver.sh
  • 创建日志目录
[root@tencent-4-11 bin]# mkdir /data/logs/kubernetes/kube-apiserver
  • 创建supervisor文件
[root@tencent-4-11 bin]# vi /etc/supervisord.d/kube-apiserver.ini
[program:kube-apiserver-4-11]
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=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)
stdout_logfile=/data/logs/kubernetes/kube-apiserver/apiserver.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)
  • 启动&验证
[root@tencent-4-11 bin]# supervisorctl update
[root@tencent-4-11 bin]# netstat -lntp|grep api
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      22881/./kube-apiser 
tcp6       0      0 :::6443                 :::*                    LISTEN      22881/./kube-apiser
  • 部署apiserver L4网络

在其他master节点上的apiserver部署成功后,进行L4反代网络部署

[root@tencent-4-11 ~]# yum install -y nginx keepalived
[root@tencent-4-11 ~]# vim /etc/nginx/nginx.conf  
# 末尾加上以下内容
stream {
    upstream kube-apiserver {
        server 10.47.4.12:6443     max_fails=3 fail_timeout=30s;
        server 10.47.5.11:6443     max_fails=3 fail_timeout=30s;
    }
    server {
        listen 7443;
        proxy_connect_timeout 2s;
        proxy_timeout 900s;
        proxy_pass kube-apiserver;
    }
}
[root@tencent-4-11 ~]# vi /etc/keepalived/check_port.sh
#!/bin/bash
if [ $# -eq 1 ] && [[ $1 =~ ^[0-9]+ ]];then
    [ $(netstat -lntp|grep ":$1 " |wc -l) -eq 0 ] && echo "[ERROR] nginx may be not running!" && exit 1 || exit 0
else
    echo "[ERROR] need one port!"
    exit 1
fi
[root@tencent-4-11 ~]# chmod +x /etc/keepalived/check_port.sh

在tencent-4-11上进行从节点配置

[root@tencent-4-11 ~]# vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id 10.47.4.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.47.4.11
    nopreempt

    authentication {
        auth_type PASS
        auth_pass 11111111
    }
    track_script {
         chk_nginx
    }
    virtual_ipaddress {
        10.47.4.10
    }
}

在tencent-4-12上进行从节点配置

[root@tencent-4-12 ~]# vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
  router_id 10.47.4.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.47.4.12
  priority 90
  advert_int 1
  authentication {
    auth_type PASS
    auth_pass 11111111
  }
  track_script {
    chk_nginx
  }
  virtual_ipaddress {
    10.47.4.10
  }
}

所有master都启动服务

[root@tencent-4-11 ~] systemctl start nginx
[root@tencent-4-11 ~] systemctl enable nginx
[root@tencent-4-11 ~] systemctl start keepalived
[root@tencent-4-11 ~] systemctl enable keepalived
[root@tencent-4-11 keepalived]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 52:54:00:a4:05:fa brd ff:ff:ff:ff:ff:ff
    inet 10.47.4.11/24 brd 10.47.4.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.47.4.10/32 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::5054:ff:fea4:5fa/64 scope link 
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:ae:39:d7:54 brd ff:ff:ff:ff:ff:ff
    inet 172.4.11.1/24 brd 172.4.11.255 scope global docker0
       valid_lft forever preferred_lft forever

kube-controller-manager 部署

  • 创建启动脚本
[root@tencent-4-11 ~]# cd /opt/kubernetes/server/bin
[root@tencent-4-11 bin]# vi kube-controller-manager-startup.sh 
#!/bin/sh
./kube-controller-manager \
  --cluster-cidr 172.4.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 ./certs/ca-key.pem \
  --service-cluster-ip-range 192.168.0.0/16 \
  --root-ca-file ./certs/ca.pem \
  --v 2 
  • 创建supervisor文件
[root@tencent-4-11 bin]# vi /etc/supervisord.d/kube-controller-manager.ini 
[program:kube-controller-manager-4-11]
command=/opt/kubernetes/server/bin/kube-controller-manager-startup.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)
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)
  • 创建日志文件夹
[root@tencent-4-11 bin]# mkdir -p /data/logs/kubernetes/kube-controller-manager/
  • 启动服务
[root@tencent-4-11 bin]# supervisorctl update

kube-scheduler 部署

10.47.4.11,10.47.4.12

  • 创建启动脚本
[root@tencent-4-11 ~]# cd /opt/kubernetes/server/bin
[root@tencent-4-11 bin]# vi kube-scheduler-startup.sh 
#!/bin/sh
./kube-scheduler \
  --leader-elect  \
  --log-dir /data/logs/kubernetes/kube-scheduler \
  --master http://127.0.0.1:8080 \
  --v 2
  • 创建supervisor文件
[root@tencent-4-11 bin]# vi /etc/supervisord.d/kube-scheduler.ini 
[program:kube-scheduler-4-11]
command=/opt/kubernetes/server/bin/kube-scheduler-startup.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)
stdout_logfile=/data/logs/kubernetes/kube-scheduler/scheduler.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)
  • 创建日志文件夹
[root@tencent-4-11 bin]# mkdir -p /data/logs/kubernetes/kube-scheduler
  • 启动服务
[root@tencent-4-11 bin]# supervisorctl update

查看master节点状态

[root@tencent-4-11 bin]# kubectl get cs
NAME                 STATUS    MESSAGE              ERROR
scheduler            Healthy   ok                   
controller-manager   Healthy   ok                   
etcd-2               Healthy   {"health": "true"}   
etcd-1               Healthy   {"health": "true"}   
etcd-0               Healthy   {"health": "true"}

运算节点部署

kubelet参数设置

kubelet.kubeconfig配置文件是各个节点通用,只用生成一份,拷贝到各个node节点。

10.47.4.11,10.47.4.12

  • 准备证书
[root@tencent-4-11 ~]# cd /opt/kubernetes/server/bin/certs
[root@tencent-4-11 certs]# scp tencent-3-10:/opt/certs/kubelet.pem .
[root@tencent-4-11 certs]# scp tencent-3-10:/opt/certs/kubelet-key.pem .
  • 设置集群参数
[root@tencent-4-11 ~]# kubectl config set-cluster myk8s --certificate-authority=/opt/kubernetes/server/bin/certs/ca.pem --embed-certs=true --server=https://10.47.4.10:7443  --kubeconfig=/opt/kubernetes/server/bin/conf/kubelet.kubeconfig
  • 设置客户端认证参数
[root@tencent-4-11 ~]# kubectl config set-credentials k8s-node --client-certificate=/opt/kubernetes/server/bin/certs/client.pem --client-key=/opt/kubernetes/server/bin/certs/client-key.pem --embed-certs=true --kubeconfig=/opt/kubernetes/server/bin/conf/kubelet.kubeconfig

这里需要特别注意的是,kubelet使用的client证书中设置的CN为k8s-node,那么也就表明使用kubectl进行声明式管理的用户为k8s-node,我们需要在后续给这个用户绑定集群角色 system:node ,ClusterRoleBinding的name也需要是k8s-node,让 k8s-node 成为具备运算节点的权限。

  • 设置上下文参数
[root@tencent-4-11 ~]# kubectl config set-context myk8s-context --cluster=myk8s --user=k8s-node --kubeconfig=/opt/kubernetes/server/bin/conf/kubelet.kubeconfig
  • 设置默认上下文
[root@tencent-4-11 ~]# kubectl config use-context myk8s-context --kubeconfig=/opt/kubernetes/server/bin/conf/kubelet.kubeconfig
  • 授权k8s-node用户,只需在集群执行一次
[root@tencent-4-11 ~]# vi 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@tencent-4-11 ~]# kubectl apply -f k8s-node.yaml

kubelet部署

10.47.4.11,10.47.4.12

  • 准备pause镜像

只需在tencent-3-10上操作,k8s集群中的pod的基础组件

[root@tencent-3-10 ~]# docker login harbor.limitest.cn -uadmin
[root@tencent-3-10 ~]# docker pull kubernetes/pause
[root@tencent-3-10 ~]# docker tag kubernetes/pause:latest harbor.limitest.cn/public/pause:latest
[root@tencent-3-10 ~]# docker push harbor.limitest.cn/public/pause:latest
  • 创建kubelet启动脚本
[root@tencent-4-11 ~]# cd /opt/kubernetes/server/bin
[root@tencent-4-11 bin]# vi kubelet.sh
#!/bin/sh
./kubelet \
  --anonymous-auth=false \
  --cluster-dns 192.168.0.2 \
  --cluster-domain cluster.local \
  --fail-swap-on="false" \
  --client-ca-file ./certs/ca.pem \
  --tls-cert-file ./certs/kubelet.pem \
  --tls-private-key-file ./certs/kubelet-key.pem \
  --hostname-override tencent-4-11.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.limitest.cn/public/pause:latest \
  --root-dir /data/kubelet
[root@tencent-4-11 bin]# chmod +x kubelet.sh
  • 创建日志文件夹&数据文件夹
[root@tencent-4-11 bin]# mkdir -p /data/logs/kubernetes/kube-kubelet /data/kubelet
  • 创建supervisorctl脚本
[root@tencent-4-11 ~]# vi /etc/supervisord.d/kube-kubelet.ini 
[program:kube-kubelet-4-11]
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=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)
stdout_logfile=/data/logs/kubernetes/kube-kubelet/kubelet.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)
  • 启动服务
[root@tencent-4-11 ~]# supervisorctl update
  • 查看node节点是否启动成功
[root@tencent-4-11 ~]# kubectl get nodes -o wide
NAME                    STATUS   ROLES    AGE   VERSION    INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                CONTAINER-RUNTIME
tencent-4-11.host.com   Ready    <none>   16m   v1.15.12   10.47.4.11    <none>        CentOS Linux 7 (Core)   3.10.0-1062.18.1.el7.x86_64   docker://19.3.9
tencent-4-12.host.com   Ready    <none>   46s   v1.15.12   10.47.4.12    <none>        CentOS Linux 7 (Core)   3.10.0-862.el7.x86_64         docker://19.3.9
  • 设置节点的role标签(可选,用于在节点网络庞大时区分各个节点角色)
[root@tencent-4-11 ~]# kubectl label node tencent-4-11.host.com node-role.kubernetes.io/node=
node/tencent-4-11.host.com labeled
[root@tencent-4-11 ~]# kubectl label node tencent-4-11.host.com node-role.kubernetes.io/master=
node/tencent-4-11.host.com labeled
[root@tencent-4-11 ~]# kubectl label node tencent-4-12.host.com node-role.kubernetes.io/master=
node/tencent-4-12.host.com labeled
[root@tencent-4-11 ~]# kubectl label node tencent-4-12.host.com node-role.kubernetes.io/node=
node/tencent-4-12.host.com labeled
[root@tencent-4-11 ~]# kubectl get nodes -o wide
NAME                    STATUS   ROLES         AGE     VERSION    INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                CONTAINER-RUNTIME
tencent-4-11.host.com   Ready    master,node   24m     v1.15.12   10.47.4.11    <none>        CentOS Linux 7 (Core)   3.10.0-1062.18.1.el7.x86_64   docker://19.3.9
tencent-4-12.host.com   Ready    master,node   8m18s   v1.15.12   10.47.4.12    <none>        CentOS Linux 7 (Core)   3.10.0-862.el7.x86_64         docker://19.3.9

kube-proxy参数设置

kube-proxy.kubeconfig配置文件是各个节点通用,只用生成一份,拷贝到各个node节点

  • 准备证书
[root@tencent-4-11 ~]# cd /opt/kubernetes/server/bin/certs
[root@tencent-4-11 certs]# scp tencent-3-10:/opt/certs/kube-proxy.pem .
[root@tencent-4-11 certs]# scp tencent-3-10:/opt/certs/kube-proxy-key.pem .

10.47.4.11,10.47.4.12

  • 设置集群参数
[root@tencent-4-11 ~]# kubectl config set-cluster myk8s --certificate-authority=/opt/kubernetes/server/bin/certs/ca.pem --embed-certs=true --server=https://10.47.4.10:7443  --kubeconfig=/opt/kubernetes/server/bin/conf/kube-proxy.kubeconfig
  • 设置客户端认证参数
[root@tencent-4-11 ~]# kubectl config set-credentials kube-proxy --client-certificate=/opt/kubernetes/server/bin/certs/kube-proxy.pem --client-key=/opt/kubernetes/server/bin/certs/kube-proxy-key.pem --embed-certs=true --kubeconfig=/opt/kubernetes/server/bin/conf/kube-proxy.kubeconfig

这里需要特别注意的是,kube-proxy使用的kube-proxy证书中设置的CN为system:kube-proxy,是默认用户,因此后续不需要声明角色绑定。

  • 设置上下文参数
[root@tencent-4-11 ~]# kubectl config set-context myk8s-context --cluster=myk8s --user=kube-proxy --kubeconfig=/opt/kubernetes/server/bin/conf/kube-proxy.kubeconfig
  • 设置默认上下文
[root@tencent-4-11 ~]# kubectl config use-context myk8s-context --kubeconfig=/opt/kubernetes/server/bin/conf/kube-proxy.kubeconfig

kube-proxy部署

10.47.4.11,10.47.4.12

  • 启动ipvs模块

kube-proxy共有3中流量调度模式,分别是 namespace,iptables,ipvs。本文使用ipvs。

[root@tencent-4-11 ~]# 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
[root@tencent-4-11 ~]# 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       33780  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          139224  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  3 ip_vs,nf_nat,nf_conntrack
  • 创建启动脚本
[root@tencent-4-11 ~]# vi /opt/kubernetes/server/bin/kube-proxy.sh
#!/bin/sh
./kube-proxy \
  --cluster-cidr 172.4.0.0/16 \
  --hostname-override tencent-4-11.host.com \
  --proxy-mode=ipvs \
  --ipvs-scheduler=nq \
  --kubeconfig ./conf/kube-proxy.kubeconfig
[root@tencent-4-11 ~]# chmod +x /opt/kubernetes/server/bin/kube-proxy.sh
  • 创建文件夹
[root@tencent-4-11 ~]# mkdir -p /data/logs/kubernetes/kube-proxy/
  • 创建supervisor文件
[root@tencent-4-11 ~]# vi /etc/supervisord.d/kube-proxy.ini 
[program:kube-proxy-4-11]
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=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)
stdout_logfile=/data/logs/kubernetes/kube-proxy/proxy.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)
  • 启动服务
[root@tencent-4-11 ~]# supervisorctl update
  • 查看是否启动成功
[root@tencent-4-11 ~]# supervisorctl status
etcd-server-4-11                 RUNNING   pid 28410, uptime 3 days, 13:33:51
kube-apiserver-4-11              RUNNING   pid 3456, uptime 2 days, 19:55:53
kube-controller-manager-4-11     RUNNING   pid 5458, uptime 1 day, 15:53:41
kube-kubelet-4-11                RUNNING   pid 4513, uptime 13:55:03
kube-proxy-4-11                  RUNNING   pid 6240, uptime 0:10:40
kube-scheduler-4-11              RUNNING   pid 29034, uptime 1 day, 14:38:07
[root@tencent-4-11 ~]# netstat -lntup | grep proxy
tcp        0      0 127.0.0.1:10249         0.0.0.0:*               LISTEN      6241/./kube-proxy   
tcp6       0      0 :::10256                :::*                    LISTEN      6241/./kube-proxy
  • 通过ipvsadm查看(可选)
[root@tencent-4-11 ~]# yum install -y ipvsadm
[root@tencent-4-11 ~]# 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.47.4.11:6443              Masq    1      0          0         
  -> 10.47.4.12:6443              Masq    1      0          0 

安装Flannel

当前各个node节点间的pod网络并未打通,需要使用flannel插件打通各个容器间的网络。在公有云上,基于路由协议的网络插件(如calico, flannel host-gw)都无法和vpc的路由打通,因此这里使用的是vxlan模式

flannel-v0.12.0

10.47.4.11,10.47.4.12

  • 下载文件
[root@tencent-4-11 ~]# wget https://github.com/coreos/flannel/releases/download/v0.12.0/flannel-v0.12.0-linux-amd64.tar.gz
[root@tencent-4-11 ~]# mkdir -p /opt/flannel-v0.12.0
[root@tencent-4-11 ~]# tar xzvf flannel-v0.12.0-linux-amd64.tar.gz -C /opt/flannel-v0.12.0/
[root@tencent-4-11 ~]# ln -s /opt/flannel-v0.12.0 /opt/flannel
  • 准备证书
[root@tencent-4-11 ~]# mkdir -p /opt/flannel/certs
[root@tencent-4-11 ~]# scp tencent-3-10:/opt/certs/ca.pem /opt/flannel/certs/
[root@tencent-4-11 ~]# scp tencent-3-10:/opt/certs/client.pem /opt/flannel/certs/
[root@tencent-4-11 ~]# scp tencent-3-10:/opt/certs/client-key.pem /opt/flannel/certs/
  • 创建子网信息
[root@tencent-4-11 ~]# vi /opt/flannel/subnet.env
FLANNEL_NETWORK=172.4.0.0/16
FLANNEL_SUBNET=172.4.11.1/24
FLANNEL_MTU=1450
FLANNEL_IPMASQ=false
  • 设置etcd配置(只需在一台etcd执行即可)
[root@tencent-4-11 ~]# /opt/etcd/etcdctl set /coreos.com/network/config \'{"Network": "172.4.0.0/16", "Backend": {"Type": "VxLAN"}}\'
  • 创建启动脚本
[root@tencent-4-11 ~]# vi /opt/flannel/flanneld.sh
#!/bin/sh
./flanneld \
    --public-ip=10.47.4.11 \
    --etcd-endpoints=https://10.47.3.10:2379,https://10.47.4.11:2379,https://10.47.4.12:2379 \
    --etcd-keyfile=./certs/client-key.pem \
    --etcd-certfile=./certs/client.pem \
    --etcd-cafile=./certs/ca.pem \
    --iface=eth0 \
    --subnet-file=./subnet.env \
    --healthz-port=2401
  • 创建supervisorctl脚本
[root@tencent-4-11 ~]# vi /etc/supervisord.d/flannel.ini 
[program:flanneld-4-11]
command=/opt/flannel/flanneld.sh                 ; the program (relative uses PATH, can take args)
numprocs=1                                                   ; number of processes copies to start (def 1)
directory=/opt/flannel                                  ; 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)
stdout_logfile=/data/logs/flanneld/flanneld.stdout.log       ; stderr log path, NONE for none; default AUTO
stdout_logfile_maxbytes=64MB                                 ; max # logfile bytes b4 rotation (default 50MB)
stdout_logfile_backups=5                                     ; # 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)
[root@tencent-4-11 ~]# mkdir -p /data/logs/flanneld/
  • 启动服务
[root@tencent-4-11 ~]# supervisorctl update
  • 验证跨主机容器通讯
[root@tencent-4-11 ~]# ping 172.4.12.2
PING 172.4.12.2 (172.4.12.2) 56(84) bytes of data.
64 bytes from 172.4.12.2: icmp_seq=1 ttl=63 time=0.373 ms
64 bytes from 172.4.12.2: icmp_seq=2 ttl=63 time=0.265 ms
64 bytes from 172.4.12.2: icmp_seq=3 ttl=63 time=0.246 ms

优化节点NAT网络

pod网络已经搭建完毕,但目前容器间访问ip都是宿主机的ip,而不是我们的pod网络,因此这里需要做处理,实现集群内的访问交互走的是pod网络。

  • 修改输出规则
#查看postrouting规则
[root@tencent-4-11 ~]# iptables-save |grep POSTROUTING
:POSTROUTING ACCEPT [87:5284]
:KUBE-POSTROUTING - [0:0]
-A POSTROUTING -m comment --comment "kubernetes postrouting rules" -j KUBE-POSTROUTING
-A POSTROUTING -s 172.4.11.0/24 ! -o docker0 -j MASQUERADE
-A KUBE-POSTROUTING -m comment --comment "kubernetes service traffic requiring SNAT" -m mark --mark 0x4000/0x4000 -j MASQUERADE

# 当访问172.4.0.0/16网段时不做伪装处理
[root@tencent-4-11 ~]# iptables -t nat -D POSTROUTING -s 172.4.11.0/24 ! -o docker0 -j MASQUERADE
[root@tencent-4-11 ~]# iptables -t nat -I POSTROUTING -s 172.4.11.0/24 ! -d 172.4.0.0/16  ! -o docker0 -j MASQUERADE
[root@tencent-4-11 ~]# iptables-save |grep POSTROUTING
:POSTROUTING ACCEPT [68:4087]
:KUBE-POSTROUTING - [0:0]
-A POSTROUTING -s 172.4.11.0/24 ! -d 172.4.0.0/16 ! -o docker0 -j MASQUERADE
-A POSTROUTING -m comment --comment "kubernetes postrouting rules" -j KUBE-POSTROUTING
-A KUBE-POSTROUTING -m comment --comment "kubernetes service traffic requiring SNAT" -m mark --mark 0x4000/0x4000 -j MASQUERADE

[root@tencent-4-11 ~]# iptables-save > /etc/sysconfig/iptables

集群网络环境部署

CoreDNS交付

CoreDns将作为一个插件交付至集群中,为集群提供dns功能。

  • 下载docker镜像,并推送至harbor中
[root@tencent-4-11 ~]# docker pull coredns/coredns:1.7.0
[root@tencent-4-11 ~]# docker tag coredns/coredns:1.7.0 harbor.limitest.cn/public/coredns:1.7.0
[root@tencent-4-11 ~]# docker push harbor.limitest.cn/public/coredns:1.7.0
  • 创建资源文件

rabc.yaml

[root@tencent-4-11 ~]# vi rbac.yaml 
apiVersion: v1
kind: ServiceAccount
metadata:
  name: coredns
  namespace: kube-system
  labels:
      kubernetes.io/cluster-service: "true"
      addonmanager.kubernetes.io/mode: Reconcile
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
    addonmanager.kubernetes.io/mode: Reconcile
  name: system:coredns
rules:
- apiGroups:
  - ""
  resources:
  - endpoints
  - services
  - pods
  - namespaces
  verbs:
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
    addonmanager.kubernetes.io/mode: EnsureExists
  name: system:coredns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:coredns
subjects:
- kind: ServiceAccount
  name: coredns
  namespace: kube-system

configmap.yaml(根据实际情况修改kubernetes和forward参数)

[root@tencent-4-11 ~]# vi configmap.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
data:
  Corefile: |
    .:53 {
        errors
        log
        health
        ready
        kubernetes cluster.local 192.168.0.0/16
        forward . 10.47.3.10
        cache 30
        loop
        reload
        loadbalance
    }

deployment.yaml

[root@tencent-4-11 ~]# vi deployment.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coredns
  namespace: kube-system
  labels:
    k8s-app: coredns
    kubernetes.io/name: "CoreDNS"
spec:
  replicas: 1
  selector:
    matchLabels:
      k8s-app: coredns
  template:
    metadata:
      labels:
        k8s-app: coredns
    spec:
      priorityClassName: system-cluster-critical
      serviceAccountName: coredns
      containers:
      - name: coredns
        image: harbor.limitest.cn/public/coredns:1.7.0
        args:
        - -conf
        - /etc/coredns/Corefile
        volumeMounts:
        - name: config-volume
          mountPath: /etc/coredns
        ports:
        - containerPort: 53
          name: dns
          protocol: UDP
        - containerPort: 53
          name: dns-tcp
          protocol: TCP
        - containerPort: 9153
          name: metrics
          protocol: TCP
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 60
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
      dnsPolicy: Default
      volumes:
        - name: config-volume
          configMap:
            name: coredns
            items:
            - key: Corefile
              path: Corefile

service.yaml

[root@tencent-4-11 ~]# vi service.yaml 
apiVersion: v1
kind: Service
metadata:
  name: coredns
  namespace: kube-system
  labels:
    k8s-app: coredns
    kubernetes.io/cluster-service: "true"
    kubernetes.io/name: "CoreDNS"
spec:
  selector:
    k8s-app: coredns
  clusterIP: 192.168.0.2
  ports:
  - name: dns
    port: 53
    protocol: UDP
  - name: dns-tcp
    port: 53
  - name: metrics
    port: 9153
    protocol: TCP
  • 交付coredns至集群中
[root@tencent-4-11 ~]# kubectl apply -f rbac.yaml
[root@tencent-4-11 ~]# kubectl apply -f configmap.yaml
[root@tencent-4-11 ~]# kubectl apply -f deployement.yaml
[root@tencent-4-11 ~]# kubectl apply -f service.yaml
  • 查看并验证dns是否生效
[root@tencent-4-11 ~]# kubectl get all -n kube-system
NAME                           READY   STATUS    RESTARTS   AGE
pod/coredns-86b4c48bcb-c99mz   1/1     Running   0          34s


NAME              TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)                  AGE
service/coredns   ClusterIP   192.168.0.2   <none>        53/UDP,53/TCP,9153/TCP   10s


NAME                      READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/coredns   1/1     1            1           34s

NAME                                 DESIRED   CURRENT   READY   AGE
replicaset.apps/coredns-86b4c48bcb   1         1         1       34s

[root@tencent-4-11 ~]# dig -t A tencent-3-10.host.com @192.168.0.2 +short
10.47.3.10
[root@tencent-4-11 ~]# dig -t A kubernetes.default.svc.cluster.local @192.168.0.2 +short
192.168.0.1

Ingress-Controller交付

ingress通过基于七层的流量转发策略,将流量转发到指定的service上,再有service转发至具体的pod中。

  • 下载docker镜像,并推送至harbor中
[root@tencent-4-11 ~]# docker pull traefik:v1.7.2
[root@tencent-4-11 ~]# docker tag traefik:v1.7.2 harbor.limitest.cn/public/traefik:v1.7.2
[root@tencent-4-11 ~]# docker push harbor.limitest.cn/public/traefik:v1.7.2
  • 创建资源声明文件

rbac.yaml

[root@tencent-4-11 ~]# vi rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: traefik-ingress-controller
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: traefik-ingress-controller
rules:
  - apiGroups:
      - ""
    resources:
      - services
      - endpoints
      - secrets
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - extensions
    resources:
      - ingresses
    verbs:
      - get
      - list
      - watch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: traefik-ingress-controller
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: traefik-ingress-controller
subjects:
- kind: ServiceAccount
  name: traefik-ingress-controller
  namespace: kube-system

daemonset.yaml

[root@tencent-4-11 ~]# vi deamonset.yaml
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: traefik-ingress
  namespace: kube-system
  labels:
    k8s-app: traefik-ingress
spec:
  template:
    metadata:
      labels:
        k8s-app: traefik-ingress
        name: traefik-ingress
    spec:
      serviceAccountName: traefik-ingress-controller
      terminationGracePeriodSeconds: 60
      containers:
      - image: harbor.limitest.cn/public/traefik:v1.7.2
        name: traefik-ingress
        ports:
        - name: controller
          containerPort: 80
          hostPort: 801
        - name: admin-web
          containerPort: 8080
        securityContext:
          capabilities:
            drop:
            - ALL
            add:
            - NET_BIND_SERVICE
        args:
        - --api
        - --kubernetes
        - --logLevel=INFO
        - --insecureskipverify=true
        - --kubernetes.endpoint=https://10.47.4.10:7443
        - --accesslog
        - --accesslog.filepath=/var/log/traefik_access.log
        - --traefiklog
        - --traefiklog.filepath=/var/log/traefik.log
        - --metrics.prometheus

service.yaml

[root@tencent-4-11 ~]# vi service.yaml
kind: Service
apiVersion: v1
metadata:
  name: traefik-ingress-service
  namespace: kube-system
spec:
  selector:
    k8s-app: traefik-ingress
  ports:
    - protocol: TCP
      port: 80
      name: controller
    - protocol: TCP
      port: 8080
      name: admin-web

ingress.yaml

[root@tencent-4-11 ~]# vi ingress.yaml 
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: traefik-web-ui
  namespace: kube-system
  annotations:
    kubernetes.io/ingress.class: traefik
spec:
  rules:
  - host: traefik.limitest.cn
    http:
      paths:
      - path: /
        backend:
          serviceName: traefik-ingress-service
          servicePort: 8080
  • 交付traefik至集群中
[root@tencent-4-11 ~]# kubectl apply -f rbac.yaml
[root@tencent-4-11 ~]# kubectl apply -f daemonset.yaml
[root@tencent-4-11 ~]# kubectl apply -f service.yaml
[root@tencent-4-11 ~]# kubectl apply -f ingress.yaml

发布简单服务

到这一步k8s集群已经部署安装完毕,已经可以交付服务进行使用了。这里简单介绍下怎么交付服务至集群中,其中一些集群的概念就不做记录了。

  • 创建hello world

一个简单的web api,演示用,不多做描述。

hello world

  • 生成镜像并推送至镜像仓库
    10.47.3.10
[root@tencent-3-10 ~]# yum install -y git
[root@tencent-3-10 ~]# git clone http://gitlab.limitest.cn/mintong.li/helloworld.git
[root@tencent-3-10 ~]# cd helloworld/src
[root@tencent-3-10 src]# docker build -t helloworld:v1.0 .
[root@tencent-3-10 src]# docker tag helloworld:v1.0 harbor.limitest.cn/hello/helloworld:1.0
[root@tencent-3-10 src]# docker push harbor.limitest.cn/hello/helloworld:1.0
  • 创建k8s资源文件

dp.yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: helloworld-dp
  namespace: app-hello
spec:
  replicas: 1
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        appName: helloworld
    spec:
      containers:
      - name: helloworld
        image: harbor.limitest.cn/hello/helloworld:1.0
        imagePullPolicy: Always
        ports:
        - containerPort: 80
      imagePullSecrets:
      - name: registry-harbor

svc.yaml

apiVersion: v1
kind: Service
metadata:
  name: helloworld-svc
  namespace: app-hello
  labels:
    appName: helloworld
spec:
  selector:
    appName: helloworld
  ports:
  - port: 80
    targetPort: 80

ingress.yaml

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: helloworld-ingress
  namespace: app-hello
spec:
  rules:
  - host: hello.limitest.cn
    http:
      paths:
      - path: /api/hello
        backend:
          serviceName: helloworld-svc
          servicePort: 80
  • 创建命名空间
[root@tencent-4-11 ~]# kubectl create ns app-hello
  • 创建harbor secret
# 这里根据自己设置进行命令编写(推送到的是hello私有库,因此需要secret进行身份认证才能拉去镜像)
[root@tencent-4-11 ~]# kubectl create secret docker-registry registry-harbor -n app-hello --docker-server=harbor.limitest.cn --docker-username=\'hello\' --docker-password=\'hello\'
[root@tencent-4-11 ~]# kubectl get secret -n app-hello
NAME                  TYPE                                  DATA   AGE
default-token-zdsnm   kubernetes.io/service-account-token   3      30m
registry-harbor       kubernetes.io/dockerconfigjson        1      20s
  • 创建k8s资源
[root@tencent-4-11 ~]# kubectl apply -f dp.yaml
deployment.extensions/helloworld-dp created
[root@tencent-4-11 ~]# kubectl apply -f svc.yaml
service/helloworld-svc created
[root@tencent-4-11 ~]# kubectl apply -f ingress.yaml
ingress.extensions/helloworld-ingress created
  • 查看资源启动情况
kubectl get all -n app-hello -o wide
NAME                                 READY   STATUS    RESTARTS   AGE   IP           NODE                    NOMINATED NODE   READINESS GATES
pod/helloworld-dp-578f69d8b8-9hgdq   1/1     Running   0          25s   172.4.12.5   tencent-4-12.host.com   <none>           <none>


NAME                     TYPE        CLUSTER-IP        EXTERNAL-IP   PORT(S)   AGE     SELECTOR
service/helloworld-svc   ClusterIP   192.168.249.169   <none>        80/TCP    9m12s   appName=helloworld


NAME                            READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES                                    SELECTOR
deployment.apps/helloworld-dp   1/1     1            1           9m17s   helloworld   harbor.limitest.cn/hello/helloworld:1.0   appName=helloworld

NAME                                       DESIRED   CURRENT   READY   AGE     CONTAINERS   IMAGES                                    SELECTOR
replicaset.apps/helloworld-dp-578f69d8b8   1         1         1       9m17s   helloworld   harbor.limitest.cn/hello/helloworld:1.0   appName=helloworld,pod-template-hash=578f69d8b8
  • 配置nginx反向代理(由于公有云不支持vip设置,因此我将域名绑定在10.4.3.10机子上,通过反向代理ingress暴露的801端口实现7层代理,你可以根据你实际网络情况进行处理。这样子)
[root@tencent-3-10 ~]# vi /etc/nginx/conf.d/kubernetes.conf 
server {
    server_name *.limitest.cn;
  
    location / {
        proxy_pass http://default_backend_traefik;
        proxy_set_header Host       $http_host;
        proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
    }
}

upstream default_backend_traefik {
    server 10.47.4.11:801    max_fails=3 fail_timeout=10s;
    server 10.47.4.12:801    max_fails=3 fail_timeout=10s;
}
[root@tencent-3-10 ~]# nginx -s reload
  • 测试接口

从互联网直接访问域名:http://hello.limitest.cn/api/hello

helloworldTest