如何简单地扩展 docker-compose 服务并将索引和计数传递给每个服务? [英] How to simply scale a docker-compose service and pass the index and count to each?

查看:30
本文介绍了如何简单地扩展 docker-compose 服务并将索引和计数传递给每个服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a way to scale up a docker-compose service & saw the --scale option but could not find any method to get the index & count within each container.

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

Here's a simplified compose file:

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 个).

If I did docker-compose up my_thing --scale 5 within the entry I'd like to be able to see which instance I am (1 to 5) & how many instances there are in total (5 in this example).

我需要这个,因为 API 'my_thing' 连接需要这个信息来将事件委派给每个实例.

I need this as the API 'my_thing' connects to needs this information to delegate events to each instance.

例如我的条目可能是

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

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

& then when I run docker-compose up my_thing --scale 5 (note that I'd prefer not to hard-code the the count)

然后每个容器将分别运行入口 &输出:

Then each container would respectively run the entry & output:

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

如果任何容器崩溃了,我希望它在知道它的索引的情况下重新启动.

If any container crashed I'd like it restarted knowing it's index.

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

Is this possible or do I need to figure out some alternative or build my own tooling?

如果有任何关于如何使用 docker swarm 执行此类操作的示例也可能有所帮助.

If there's any example of how to do something like this with docker swarm that may help too.

推荐答案

#!/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"

这篇关于如何简单地扩展 docker-compose 服务并将索引和计数传递给每个服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆