动态伸缩你的服务

490 阅读3分钟

1.前言

如你所知,服务的常规部署方式如下:

对外暴露的服务都会在前面部署nginx用于提供反向代理负载均衡能力

下面会快速部署一套类似的服务,分析其存在的问题并给出相应解决方案

2.应用相关

2.1 启动服务

使用boot-cloud-openfeign-provider启动3个服务实例,端口分别为8081、8082、8083

2.2 服务验证

在浏览器中分别输入:http://localhost:8081/index/nginxhttp://localhost:8082/index/nginxhttp://localhost:8083/index/nginx,保证3个服务实例均可被访问

服务运行依赖5.15.2中的consul

3.nginx相关

3.1 安装

3.1.1 搜索镜像

docker search nginx

3.1.2 拉取镜像

docker pull nginx

3.1.3 运行镜像

docker run --name nginx -p 80:80 -d nginx

3.1.4 拷贝镜像配置文件

docker cp nginx:/etc/nginx/nginx.conf path/nginx[宿主机放配置文件路径]

3.1.5 删除容器

docker rm -f nginx

3.1.6 指定配置文件运行镜像

docker run --name nginx -p 80:80 -v [宿主机路径]/nginx/nginx.conf:/etc/nginx/nginx.conf:ro -v [宿主机路径]/nginx/conf.d:/etc/nginx/conf.d -d nginx

3.2 配置

3.2.1 配置负载均衡

[宿主机路径]/nginx/conf.d目录下创建load-balancer.conf文件,内容如下:

upstream backend {
    server 10.100.40.243:8081;
    server 10.100.40.243:8082;
    server 10.100.40.243:8083;
}
​
server{
    listen 80;
​
    location / {
        proxy_pass http://backend;
    }
}

3.3 验证

3.3.1 重启nginx服务

docker exec -it nginx nginx -s reload

3.3.2 访问nginx服务

在浏览器中输入:http://localhost/index/nginx,多次请求依次可以看到openfeign service:hello nginx from 8081openfeign service:hello nginx from 8082openfeign service:hello nginx from 8083结果,则说明nginx负载均衡配置正常。

4.问题

如你所见,服务的负载均衡能力是通过在load-balancer.conf配置文件中写死服务列表来实现的,同时也意味着,只要后端服务列表发生变化,就需要修改配置并通过nginx -s reload命令来重新加载。

5.方案

有了问题,自然会有对应的解决方案,本文要介绍的解决方案就是consulconsul template

5.1 安装consul

根据Install Consul官网教程安装consul

5.2 运行consul

consul agent -dev

5.3 安装consul template

5.3.1 下载压缩包

wget https://releases.hashicorp.com/consul-template/0.20.0/consul-template_0.20.0_linux_amd64.zip

5.3.2 解压

unzip consul-template_0.20.0_linux_amd64.zip

Mac os可以通过brew install consul-template进行安装,简单、方便

5.4 创建负载均衡配置文件模板

创建load-balancer.ctmpl文件,编辑如下内容:

upstream backend {
    {{- range service "openfeign-provider-service" }}
        server {{ .Address }}:{{ .Port }};
    {{- end }}
}
​
server {
   listen 80;
​
   location / {
      proxy_pass http://backend;
   }
}

5.5 清空配置文件

清空3.2.1章节load-balancer.conf文件内容

5.6 创建consul template配置

创建consul-template-config.hcl文件,编辑如下内容:

consul {
  address = "localhost:8500"
​
  retry {
    enabled  = true
    attempts = 12
    backoff  = "250ms"
  }
}
template {
  source      = "[5.4章节指定的路径]/load-balancer.conf.ctmpl"
  destination = "[5.5章节指定的路径]/load-balancer.conf"
  perms       = 0600
  command     = "sh -c docker exec -it nginx nginx -s reload"
}
​

address:指定consul地址;source:用于指定负载均衡配置模板文件路径;destination:负载均衡配置生成文件路径;command:用于指定要执行的命令。整体流程:consul template从address地址拉取服务地址列表,根据source模板文件生成负载均衡配置到destination文件中,执行command重新加载nginx

5.7 运行consul template

consul-template -config=consul-template-config.hcl

运行consul template之后,会发现load-balancer.conf文件中有了负载均衡配置

5.8 服务关闭、启动

到这里,你会发现伴随着服务关闭服务启动load-balancer.conf配置文件中的内容也在一直跟着改变,从而实现服务动态伸缩