简体   繁体   中英

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 ?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM