实操:搭建前端LB负载均衡+keepalived并指定apiserver的vip

一:搭建前端LB负载均衡+keepalived

lb 装两个服务,nginx,keepalived

vip也将会成为api server地址,被绑定

node指向apiserver——vip

node指向apiserver的IP若为物理地址,则需要指定多个,且后期若是增改master节点,还会增加工作量

1.1 环境优化

LB1

[root@localhost ~]# hostnamectl set-hostname lb1
[root@localhost ~]# su
[root@lb1 ~]# systemctl stop NetworkManager
[root@lb1 ~]# systemctl disable NetworkManager
Removed symlink /etc/systemd/system/multi-user.target.wants/NetworkManager.service.
Removed symlink /etc/systemd/system/dbus-org.freedesktop.nm-dispatcher.service.
Removed symlink /etc/systemd/system/network-online.target.wants/NetworkManager-wait-online.service.
[root@lb1 ~]# setenforce 0
[root@lb1 ~]# sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
[root@lb1 ~]# iptables -F

LB2

[root@localhost ~]# hostnamectl set-hostname lb2
[root@localhost ~]# su
[root@lb2 ~]# systemctl stop NetworkManager
[root@lb2 ~]# systemctl disable NetworkManager
Removed symlink /etc/systemd/system/multi-user.target.wants/NetworkManager.service.
Removed symlink /etc/systemd/system/dbus-org.freedesktop.nm-dispatcher.service.
Removed symlink /etc/systemd/system/network-online.target.wants/NetworkManager-wait-online.service.
[root@lb2 ~]# setenforce 0
[root@lb2 ~]# sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
[root@lb2 ~]# iptables -F

1.2 yum 安装nginx(两个lb都做)

[root@lb1 ~]# echo -e '[nginx]\nname=nginx.repo\nbaseurl=http://nginx.org/packages/centos/7/$basearch/\ngpgcheck=0' > /etc/yum.repos.d/nginx.repo
[root@lb1 ~]# yum makecache
[root@lb1 ~]# yum install nginx -y

1.3 添加四层转发 upstream(两个lb都做)

另外一一个节点也是如此操作

nginx用来做四层负载

再events和http之间加入stream配置

[root@lb1 ~]# vim /etc/nginx/nginx.conf 
events {
    worker_connections  1024;
}
stream {
    log_format  main    '$remote_addr $upstream_addr - [$time_local] $status $upstream_bytes_sent';
    access_log /var/log/nginx/k8s-access.log main;

    upstream k8s-apiserver {
        server 192.168.247.149:6443;
        server 192.168.247.148:6443;
        #两个master地址,apiserver端口号6443
    }
    server {
        listen 6443;
        proxy_pass k8s-apiserver;
    }
}

http {
[root@lb1 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

1.4 开启nginx(两个lb都做)

[root@lb1 ~]# systemctl start nginx
[root@lb1 ~]# systemctl status nginx
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since Sat 2020-05-02 18:02:40 CST; 5s ago
     Docs: http://nginx.org/en/docs/
  Process: 29485 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 29488 (nginx)
    Tasks: 2
   CGroup: /system.slice/nginx.service
           ├─29488 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
           └─29489 nginx: worker process

May 02 18:02:40 lb1 systemd[1]: Starting nginx - high performance web server...
May 02 18:02:40 lb1 systemd[1]: Started nginx - high performance web server.
[root@lb1 ~]# systemctl enable nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.

1.5 本地验证一下(两个lb都做)

在这里插入图片描述

二:接下来部署keepalived服务

2.1 安装keepalived

[root@lb1 ~]# yum install keepalived -y

2.2 编辑keepalived配置文件

[root@lb1 ~]# mkdir /abc
[root@lb1 ~]# mount.cifs //192.168.0.88/linuxs /abc
Password for root@//192.168.0.88/linuxs:  
[root@lb1 ~]# cp /abc/k8s/keepalived.conf /etc/keepalived/keepalived.conf 
cp: overwrite ‘/etc/keepalived/keepalived.conf’? y
[root@lb1 ~]# vim /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
   # 接收邮件地址
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   # 邮件发送地址
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id NGINX_MASTER
}

vrrp_script check_nginx {
    script "/etc/check_nginx.sh"		#这个配置文件后面会编辑
}	

vrrp_instance VI_1 {
    state MASTER
    interface ens32		#指定物理网口
    virtual_router_id 51 # VRRP 路由 ID实例,每个实例是唯一的
    priority 100    # 优先级,备服务器设置 90
    advert_int 1    # 指定VRRP 心跳包通告间隔时间,默认1秒
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.247.100/24	#指定虚拟IP
    }
    track_script {			#监控脚本
        check_nginx
    }
}

第二个lb的虚拟路由IP不要一致,state为BACKUP,其他一样

vrrp_instance VI_1 {
    state BACKUP
    interface ens32
    virtual_router_id 52
    priority 90

2.3 编辑检查nginx脚本

这个脚本会将keepalived和nginx结合在一起

[root@lb1 ~]# vim /etc/nginx/check_nginx.sh

count=$(ps -ef |grep nginx |egrep -cv "grep|$$")
#这个变量是建厂nginx是否开启,如果没有开启,那么就关闭keepalived
if [ "$count" -eq 0 ];then
    /etc/init.d/keepalived stop
fi
[root@lb1 ~]# chmod +x /etc/nginx/check_nginx.sh

2.4 开启keepalived,是否设置自启动自己考虑

先启动lb1节点master,然后在启动lb2节点backup

[root@lb1 ~]# systemctl start keepalived.service 

2.5 使用ip a可以查看到虚拟IP

此时虚拟IP在lb1上

[root@lb1 ~]# ip a
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:ef:81:b6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.247.145/24 brd 192.168.247.255 scope global noprefixroute dynamic ens32
       valid_lft 5355394sec preferred_lft 5355394sec
    inet 192.168.247.100/24 scope global secondary ens32

三:将k8s中的node节点关于apiserver地址指向为vip

3.1 这样node去找master就会去找vip

[root@node01 ~]# cd /k8s/cfg/
[root@node01 cfg]# ls
bootstrap.kubeconfig  kubelet.config      kube-proxy
kubelet               kubelet.kubeconfig  kube-proxy.kubeconfig
[root@node01 cfg]# vim bootstrap.kubeconfig 
    server: https://192.168.247.100:6443
[root@node01 cfg]# vim kubelet.kubeconfig 
    server: https://192.168.247.100:6443
[root@node01 cfg]# vim kube-proxy.kubeconfig 
    server: https://192.168.247.100:6443

3.2 重启服务kubelet、proxy

[root@node01 cfg]# systemctl restart kubelet.service 
[root@node01 cfg]# systemctl restart kube-proxy.service 

3.3 替换完成直接自检

[root@node01 cfg]# grep 100 *
bootstrap.kubeconfig:    server: https://192.168.247.100:6443
kubelet.kubeconfig:    server: https://192.168.247.100:6443
kube-proxy.kubeconfig:    server: https://192.168.247.100:6443

四:验证apiserver漂移地址

备注:先在lb1节点关掉nginx,再在lb2查看虚拟IP是否生效

若是检测到nginx发现关闭,keepalived会自动关闭

[root@lb1 ~]# pkill nginx
[root@lb1 ~]# ps -ef |grep nginx |egrep -cv "grep|$$"
0
[root@lb1 ~]# ip a
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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:ef:81:b6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.247.145/24 brd 192.168.247.255 scope global noprefixroute dynamic ens32
       valid_lft 5354179sec preferred_lft 5354179sec
    inet6 fe80::d8f:d3dc:3ef7:446/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

这时vip已经不在lb1上

查看lb2,发现出现

[root@lb2 ~]# ip a
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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:df:af:4e brd ff:ff:ff:ff:ff:ff
    inet 192.168.247.146/24 brd 192.168.247.255 scope global noprefixroute dynamic ens32
       valid_lft 5354144sec preferred_lft 5354144sec
    inet 192.168.247.100/24 scope global secondary ens32

五:重新开启lb1nginx

要先开启nginx,然后再开启keepalived

此时发现vip又回到了lb1

[root@lb1 ~]# systemctl restart nginx
[root@lb1 ~]# ip a
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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:ef:81:b6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.247.145/24 brd 192.168.247.255 scope global noprefixroute dynamic ens32
       valid_lft 5354038sec preferred_lft 5354038sec
    inet 192.168.247.100/24 scope global secondary ens32

nginx站点/usr/share/nginx/html

六:查看lb1上的关于nginx的k8s日志

里面有192.168.247.144node02和143node01去访问192.168.247.148master2,原因是重启了服务

[root@lb1 ~]# tail -f /var/log/nginx/k8s-access.log 
192.168.247.143 192.168.247.148:6443 - [02/May/2020:19:03:52 +0800] 200 3842
192.168.247.144 192.168.247.148:6443 - [02/May/2020:19:06:29 +0800] 200 1122
192.168.247.144 192.168.247.148:6443 - [02/May/2020:19:06:29 +0800] 200 1122
[root@lb2 ~]# tail -f /var/log/nginx/k8s-access.log 
192.168.247.143 192.168.247.148:6443 - [02/May/2020:19:05:02 +0800] 200 1566

七:创建pod测试

7.1 此时node节点docker状态

node01

[root@node01 cfg]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
39f034a2f24e        centos:7            "/bin/bash"         3 days ago          Up 3 days                               beautiful_jennings
[root@node01 cfg]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              7                   5e35e350aded        5 months ago        203MB

node02

[root@node02 cfg]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              7                   5e35e350aded        5 months ago        203MB
[root@node02 cfg]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
fea29d0ff39b        centos:7            "/bin/bash"         3 days ago          Up 3 days                               kind_burnell

在部署flannel组件时为了测试不同节点间的容器可以互联互通时创建

7.2 使用kubectl创建pod

run 在集群中运行一个指定的镜像

[root@master1 cfg]# kubectl run nginx --image=nginx
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx created
[root@master1 cfg]# kubectl get pods
NAME                    READY   STATUS    RESTARTS   AGE
nginx-dbddb74b8-sx4m6   1/1     Running   0          49s

pod有在run运行状态前,还有一个containercreating创建状态

kubectl controls the Kubernetes cluster manager. 

Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/

Basic Commands (Beginner):
  create         从文件或stdin创建资源。
  expose         使用 replication controller, service, deployment 或者 pod 并暴露它作为一个 新的 Kubernetes Service
  run            在集群中运行一个指定的镜像
  set            为 objects 设置一个指定的特征

Basic Commands (Intermediate):
  explain        查看资源的文档
  get            显示一个或更多 resources
  edit           在服务器上编辑一个资源
  delete         按文件名、stdin、资源和名称删除资源,或按资源和标签选择器删除资源

Deploy Commands:
  rollout        管理资源的推出
  scale          为 Deployment, ReplicaSet, Replication Controller 或者 Job 设置一个新的副本数量
  autoscale      自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController 的副本数量

Cluster Management Commands:
  certificate    修改 certificate 资源.
  cluster-info   显示集群信息
  top            Display Resource (CPU/Memory/Storage) usage.
  cordon         标记 node 为 unschedulable
  uncordon       标记 node 为 schedulable
  drain          Drain node in preparation for maintenance
  taint          更新一个或者多个 node 上的 taints

Troubleshooting and Debugging Commands:
  describe       显示一个指定 resource 或者 group 的 resources 详情
  logs           输出容器在 pod 中的日志
  attach         Attach 到一个运行中的 container
  exec           在一个 container 中执行一个命令
  port-forward   Forward one or more local ports to a pod
  proxy          运行一个 proxy 到 Kubernetes API server
  cp             复制 files 和 directories 到 containers 和从容器中复制 files 和 directories.
  auth           Inspect authorization

Advanced Commands:
  apply          通过文件名或标准输入流(stdin)对资源进行配置
  patch          使用 strategic merge patch 更新一个资源的 field(s)
  replace        通过 filename 或者 stdin替换一个资源
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        在不同的 API versions 转换配置文件

Settings Commands:
  label          更新在这个资源上的 labels
  annotate       更新一个资源的注解
  completion     Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  alpha          Commands for features in alpha
  api-resources  Print the supported API resources on the server
  api-versions   Print the supported API versions on the server, in the form of "group/version"
  config         修改 kubeconfig 文件
  plugin         Provides utilities for interacting with plugins.
  version        输出 client 和 server 的版本信息

Usage:
  kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

7.3 查看pod日志,发现有报错

[root@master1 cfg]# kubectl logs nginx-dbddb74b8-sx4m6
Error from server (Forbidden): Forbidden (user=system:anonymous, verb=get, resource=nodes, subresource=proxy) ( pods/log nginx-dbddb74b8-sx4m6)

创建一个集群角色用户,系统中的匿名用户,并给其一个admin权限,只需要授权一次就可以

[root@master1 cfg]# kubectl create clusterrolebinding cluster-system-anonymous --clusterrole=cluster-admin --user=system:anonymous
clusterrolebinding.rbac.authorization.k8s.io/cluster-system-anonymous created

此时便可以查看日志了

7.4 查看pod网络,这也可以查看出此pod被部署到哪个node上

[root@master1 cfg]# kubectl get pods -o wide
NAME                    READY   STATUS    RESTARTS   AGE   IP            NODE              NOMINATED NODE
nginx-dbddb74b8-sx4m6   1/1     Running   0          16m   172.17.42.3   192.168.247.144   <none>

在node02节点上

此时有三个容器,一个刚刚创建的,一个是容器仓库,还有一个是之前测试flannel

[root@node02 cfg]# docker ps -a
CONTAINER ID        IMAGE                                                                 COMMAND                  CREATED             STATUS              PORTS               NAMES
6eff0af2c578        nginx                                                                 "nginx -g 'daemon of…"   16 minutes ago      Up 16 minutes                           k8s_nginx_nginx-dbddb74b8-sx4m6_default_cd5a2ea4-8c68-11ea-a668-000c29db840b_0
c4ca11690aa1        registry.cn-hangzhou.aliyuncs.com/google-containers/pause-amd64:3.0   "/pause"                 16 minutes ago      Up 16 minutes                           k8s_POD_nginx-dbddb74b8-sx4m6_default_cd5a2ea4-8c68-11ea-a668-000c29db840b_0
fea29d0ff39b        centos:7                                                              "/bin/bash"              3 days ago          Up 3 days                               kind_burnell
[root@node02 cfg]# docker images
REPOSITORY                                                        TAG                 IMAGE ID            CREATED             SIZE
nginx                                                             latest              602e111c06b6        8 days ago          127MB
centos                                                            7                   5e35e350aded        5 months ago        203MB
registry.cn-hangzhou.aliyuncs.com/google-containers/pause-amd64   3.0                 99e59f495ffa        3 years ago         747kB

7.5 在node02节点上可以直接访问容器nginx

[root@node02 cfg]# curl 172.17.42.3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>

7.6 此时查看容器日志

[root@master1 cfg]# kubectl logs nginx-dbddb74b8-sx4m6
172.17.42.1 - - [02/May/2020:11:52:45 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值