1.前言
一次构建,随处运行,这是docker的理念
无论你是Ubuntu,还是centos8,还是麒麟,还是centos6,这些都不重要,重要的是我们需要一个docker的环境。有了docker的运行环境,那么docker的理念就能体现下去
keepalived+nginx高负载均衡集群是常见的组合,是一个标准负载均衡方式。
在docker环境下可以很方便的构建统一镜像,运行服务,实现keepalived多节点的高可用,nginx的负载均衡和反向代理功能。
其中keepalived轮询检查nginx是否存活,动态切换虚拟IP地址
2.构建镜像
2.1.配置nginx下载源
新建nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
2.2.生成nginx检测脚本
新建check_nginx.sh
#!/bin/bash
A=$(ps -ef | grep nginx: | grep -v grep | wc -l)
if [ $A -eq 0 ];thennginxecho "restart nginx, sleep 2 s"sleep 2num=$(ps -ef | grep nginx: | grep -v grep | wc -l)if [ $num -eq 0 ];thenps -ef | grep keepalived | grep -v grep | awk '{print $2}'| xargs kill -9echo "start nginx failed,kill keepalived"fi
elseecho "nginx not dead"
fi
2.3.生成Dockfile文件
新建Dockerfile
适当的优化,RUN命令通过&&合并了,并在最后清除缓存层。
避免build的镜像过大,降低build的效率
FROM centos:7
ENV TZ "Asia/Shanghai"
ADD nginx.repo /etc/yum.repos.d/
ADD check_nginx.sh /etc/keepalived/
RUN chmod +x /etc/keepalived/check_nginx.sh && \yum install -y iproute && \yum install -y net-tools && \yum install -y yum-utils && \yum install -y keepalived && \yum install -y nginx && \yum clean all
2.4.构建命令
docker build -t centos-base:7 .