Johackim
Johackim

Reputation: 31

How to get and set random service port as env var inside docker-compose file?

Here an example of a docker-compose.yml :

# docker-compose.yml

version: '3'

services:
  web:
    image: ghost:latest
    ports:
      - 0:2368
    environment:
      url: http://ghost.localhost:30001

I would like to get service random port and set inside url env variable like this:

url: "http://ghost.localhost:{{.Service.Port}}"

The final goal it's to deploy multiple stacks without manually set port.

docker stack deploy --compose-file=docker-compose.yml ghost1
docker stack deploy --compose-file=docker-compose.yml ghost2
docker stack deploy --compose-file=docker-compose.yml ghost3

It's possible ?

Upvotes: 2

Views: 1951

Answers (3)

Constantin Galbenu
Constantin Galbenu

Reputation: 17683

No, this is not possible now. There is a feature request but it is still open (it is more than 4 years old).

Upvotes: 1

sorabzone
sorabzone

Reputation: 1017

Use .env file to define dynamic values in docker-compse.yml. Be it port or any other value.

Sample docker-compose:

testcore.web:
       image: xxxxxxxxxxxxxxx.dkr.ecr.ap-northeast-2.amazonaws.com/testcore:latest
       volumes: 
            - c:/logs:c:/logs
       ports:
            - ${TEST_CORE_PORT}:80
       environment:
            - CONSUL_URL=http://${CONSUL_IP}:8500 
            - HOST=${HOST_ADDRESS}:${TEST_CORE_PORT}

Inside .env file you can define the value of these variables:

CONSUL_IP=172.31.28.151
HOST_ADDRESS=172.31.16.221
TEST_CORE_PORT=10002

Upvotes: 0

maxm
maxm

Reputation: 3667

Yes, you can select a port range (I would recommend using a higher range, like 9000-9100), but keep in mind that a process is being launched for every open port: Why does Docker run so many processes to map ports though to my application? So the performance is likely going to be less than ideal.

You might want to look into using docker "host networking" or some other non-default networking setup.

Upvotes: 0

Related Questions