如何简单地扩展 docker-compose 服务并将索引和计数传递给每个服务?

2024-02-26

我正在寻找一种扩展 docker-compose 服务的方法并看到了 --scale 选项,但找不到任何方法来获取每个容器内的索引和计数。

这是一个简化的撰写文件:

version: '2.1'
services:
  my_thing:
    restart: always
    build: .
    entrypoint: /entry.sh
    depends_on:
      - database
  database:
    restart: always
    image: postgres:12.1-alpine
    ...

如果我这样做了docker-compose up my_thing --scale 5在条目中我希望能够 查看我是哪个实例(1 到 5)以及总共有多少个实例(本例中为 5)。

我需要这个,因为 API“my_thing”连接需要此信息来将事件委托给每个实例。

例如我的条目可以是

echo "Hello I'm container $index of $count";

然后当我跑步时docker-compose up my_thing --scale 5(请注意,我不想对计数进行硬编码)

然后每个容器将分别运行条目和输出:

Hello I'm container 1 of 5
Hello I'm container 2 of 5
Hello I'm container 3 of 5
... and so on

如果任何容器崩溃,我希望它能够重新启动,知道它的索引。

这是可能的还是我需要找出一些替代方案或构建我自己的工具?

编辑: 如果有任何关于如何使用 docker swarm 执行类似操作的示例,也可能会有所帮助。


#!/bin/bash
# get the container IP
IP=`ifconfig eth0 | grep 'inet ' | awk '{print $2}'`

# get the service name you specified in the docker-compose.yml 
# by a reverse DNS lookup on the IP
SERVICE=`dig -x $IP +short | cut -d'_' -f2`

# the number of replicas is equal to the A records 
# associated with the service name
COUNT=`dig $SERVICE +short | wc -l`

# extract the replica number from the same PTR entry
INDEX=`dig -x $IP +short | sed 's/.*_\([0-9]*\)\..*/\1/'`

# Hello I'm container 1 of 5 
echo "Hello I'm container $INDEX of $COUNT"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何简单地扩展 docker-compose 服务并将索引和计数传递给每个服务? 的相关文章

随机推荐