点击蓝字关注我吧
1、导读
如果你对微服务有了解,那么你看肯定知道,一个项目中微服务的数量可能上千,随着服务数量的越来越多,服务与服务之间的通信变得越来越复杂,我们的微服务也变得超级难管理,所以今天我给大家分享我在学习时的一篇笔记,如何设计出高可用的Dcoker服务架构,此架构可以自动发现进行注册,利用consul可以轻易的在众多服务中哪个服务出现了问题。以下代码本人亲测可用,环境为centos7,需要两台虚拟机一台用途为Registor Zabbix(192.168.10.252)一台Consul(192.168.10.253)
首先来看一下Cousul的官方解释:
Consul是一套开源的分布式服务发现和配置管理系统,支持多数据中心分布式高可用。Consul是HashiCorp(Vagrant的创建者)开发的一个服务发现与配置项目,用Go语言开发,基于 Mozilla Public License 2.0 的协议开源。
架构设计
这套架构有什么好处呢?我认为最好的就是它的自动发现,当你启动服务时不用修改任何的配置文件,当添加一个服务式,它便会自动进行配置的编写。
架构优势
使用Docker搭建部署
# 官方下载consul压缩包
mkdir consul
cd consul
# 将压缩包上传至consul目录下
unzip consul_1.5.2_linux_amd64.zip
mv consul /usr/bin
# 切换到root目录
consul agent -server -bootstrap -ui -data-dir=/var/lib/consul-data -bind=192.168.10.253 -client=0.0.0.0 -node=consul-server01
# 或者后台启动
nohup consul agent -server -bootstrap -ui -data-dir=/var/lib/consul-data -bind=192.168.10.253 -client=0.0.0.0 -node=consul-server01 &>/var/log/consul.log &
#查看集群信息
consul members
consul info |grep leader
容器服务自动加入Nginx集群
# 安装Glider/Registrator
docker run -d --name=registrator --net=host -v /var/run/docker.sock:/tmp/docker.sock --restart=always gliderlabs/registrator:latest -ip=192.168.10.252 consul://192.168.10.253:8500
# 测试服务是否正常
docker run -itd -p:83:80 --name test-01 -h test01 nginx
docker run -itd -p:84:80 --name test-02 -h test02 nginx
# 安装Consul-Template
# 准备Nginx模板文件
vim /root/consul/nginx.ctmpl
nginx.ctmpl
upstream http_backend{
{{range service "nginx"}}
server{{.Address}}:{{.Port}};
{{end}}
}
server{
listen 83;
server_name localhost 192.168.10.253;
access_log /var/log/nginx/kgc.cn-access.log;
index index.html index.php;
location/{
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Client-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://http_backend;
}
}
# 编译安装Nginx 上传nginx包至root目录
yum install gcc pcre-devel zlib-devel -y
tar zxvf nginx-1.16.0.tar.gz
cd nginx-1.16.0
./configure --prefix=/usr/local/nginx
make
make install
# 配置nginx
vim /usr/local/nginx/nginx.conf
nginx.conf
mkdir /usr/local/nginx/conf/vhost
# 启动nginx
/usr/local/nginx/sbin/nginx
# 查看是否启动
ps -C nginx -o pid
# 配置并启动temlate 服务
# 上传consul-template压缩包到 /root目录
unzip consul-template_0.19.3_linux_amd64.zip
mv consul-template /usr/bin/
# 在前台启动,启动后不要Ctrl+C终止
consul-template -consul-addr 192.168.10.253:8500 -template "/root/consul/nginx.ctmpl:/usr/local/nginx/conf/vhost/kgc.conf:/usr/local/nginx/sbin/nginx -s reload" --log-level=info
查看配置文件
cat /usr/local/nginx/conf/vhost/kgc.conf
此时增加一个Nginx容器节点
docker run -itd -p:85:80 --name test-05 -h test05 nginx
再次查看配置文件
好了是不是很神奇,配置文件最后自动增加了。
转载请联系我
本文参考:
https://www.jianshu.com/p/9976e874c099?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io
Docker容器技术与高可用实战