对于后台任务一般是不建议在容器中运行的,但是如果我们为了简化应用的部署,可能会使用后台任务进行服务的管理,类似的
工具很多,supervisor,systemd , init.d 同时对于docker 的alpine 容器镜像我们可以使用openrc,以下是一个简单的demo,也是
借鉴子haproxy 的ingress 组件
目的
通过使用openrc 管理容器中haproxy 服务的启动(可以在修改配置之后,重启服务,而不用重新启动容器)
环境准备
包含了haproxy 的监控,以及dataplaneapi 还有dashboard
- docker-compose 文件
version: "3"
services:
grafana:
image: grafana/grafana
ports:
- "3000:3000"
prometheus:
image: prom/prometheus
volumes:
- "./prometheus.yml:/etc/prometheus/prometheus.yml"
ports:
- "9090:9090"
haproxy:
image: dalongrong/dumb-init-haproxy-dataplan:2.0.5
build: ./
volumes:
- "./haproxy.cfg:/etc/haproxy/haproxy.cfg"
ports:
- "80:80"
- "6379:6379"
- "5555:5555"
- "8404:8404"
- "8080:8080"
- "9000:9000"
- "9001:9001"
- "9002:9002"
- "1000-1005:1000-1005"
- "10080:10080"
nginx1:
image: nginx
ports:
- "8090:80"
nginx2:
image: nginx
ports:
- "8091:80"
- haproxy dockerfile
FROM haproxy:2.0.5-alpine
# 添加依赖的服务openrc
RUN apk update && apk add --no-cache openrc htop
## 使用dumb-init 接管进程1
RUN wget -O /usr/local/bin/dumb-init https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_amd64
RUN chmod +x /usr/local/bin/dumb-init
COPY start.sh /start.sh
RUN chmod +x /start.sh
COPY haproxy /etc/init.d/haproxy
COPY dataplaneapi /usr/local/sbin/dataplaneapi
RUN chmod +x /usr/local/sbin/dataplaneapi
RUN chmod +x /etc/init.d/haproxy
ENTRYPOINT [ "/usr/local/bin/dumb-init","--","/start.sh" ]
- start.sh
很简单的一个脚本,规避容器停止的
#!/bin/sh
set -e
while true
do
sleep 10
echo "demo"
done
- prometheus 监控配置
scrape_configs:
- job_name: haproxy
metrics_path: /metrics
scrape_interval: 10s
scrape_timeout: 10s
static_configs:
- targets: [‘haproxy:8404‘]
- openrc haproxy 启动脚本
#!/bin/sh
?
case "$1" in
start)
if [ -e /var/run/haproxy.pid ]; then
echo haproxy is running, pid=`cat /var/run/haproxy.pid`
exit 1
else
haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid
fi
;;
stop)
kill -USR1 `cat /var/run/haproxy.pid`
rm /var/run/haproxy.pid
;;
restart)
$0 apply
;;
reload)
$0 apply
;;
status)
if [ -e /var/run/haproxy.pid ]; then
echo haproxy is running, pid=`cat /var/run/haproxy.pid`
else
echo haproxy is NOT running
exit 1
fi
;;
apply)
if [ -e /var/run/haproxy.pid ]; then
haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid)
else
$0 start
fi
;;
push_apply)
$0 apply
;;
validate)
haproxy -c -f /etc/haproxy/haproxy.cfg
;;
*)
echo "Usage: $0 {start|stop|status|reload}"
esac
?
exit 0
启动&&效果
- 启动
docker-compose build
docker-compose up -d
- 进入容器启动haproxy
docker-compose exec haproxy sh
service haproxy start
- 效果
容器服务
grafana(导入了haproxy2.0 的配置)
haproxy 代理服务
promethesu 服务
haproxy stats
说明
以上是一个简单的操作,实际上类似的需求在实际中还是有的(尽管推荐大家容器只跑一个服务),比如kubernetes 的ingress 组件好多就用了
这种方式解决运行的问题,比如以下nginx-ingress 的
参考资料
https://wiki.gentoo.org/wiki/OpenRC
https://github.com/OpenRC/openrc
https://wiki.alpinelinux.org/wiki/Writing_Init_Scripts
https://github.com/rongfengliang/alpine-docker-openrc-haproxy
原文地址:https://www.cnblogs.com/rongfengliang/p/11453481.html
时间: 2024-11-04 15:49:43