问题
I've got a docker-compose.yml
:
master:
build: .
slave:
image: master
hostname: slave
command: run_slave
How can I make docker-compose scale slave=5
generate machines with unique hostnames?
...e.g. something like this:
slave1
slave2
slave3
slave4
slave5
回答1:
There is no way to set the hostname to that value.
If you need a unique identifier, I would use the unique container id, which you can get by running $(hostname)
.
回答2:
The accepted answer is correct, there is no way to set this using one scale
command. Here's one way to work around it.
Instead of scaling the slaves at once, scale them one at a time, using an environment variable to set the hostname at each step. This does defeat the convenience of scale
a bit, but it seems to work, at least in Compose 1.8.1.
docker-compose.yml
:
master:
build: .
slave:
build: .
hostname: slave${SLAVE_INDEX}
command: run_slave
Run them:
$ for i in $(seq 1 5); do SLAVE_INDEX=$i docker-compose scale slave=$i; done
Creating and starting so_slave_1 ... done
Creating and starting so_slave_2 ... done
Creating and starting so_slave_3 ... done
Creating and starting so_slave_4 ... done
Creating and starting so_slave_5 ... done
$ for i in $(docker ps --format '{{ .Names }}'); do
> echo -n "$i: "; docker inspect --type container $i | jq -r '.[].Config.Hostname'
> done
so_slave_5: slave5
so_slave_4: slave4
so_slave_3: slave3
so_slave_2: slave2
so_slave_1: slave1
$ for i in $(seq 1 5); do docker exec -it so_slave_${i} hostname; done
slave1
slave2
slave3
slave4
slave5
来源:https://stackoverflow.com/questions/35062468/scaling-with-docker-composer-and-appending-a-number-to-the-hostname