I would like to use integer expression in docker-compose.yml
to set ports based on the BASE_PORT
variable.
I have a .env
file with the following content:
BASE_PORT=57900
My start bash script looks like this:
#/bin/sh
. .env
docker-compose stop
docker-compose rm -v -f
docker-compose up -d adminserver
docker-compose.yml
...
services:
adminserver:
image: ....
hostname: ...
ports:
- ${BASE_PORT}:8001
...
This configuration works like a charm, docker ps | grep 8001
returns with a proper content.
But I would like to use more port configurations and more ports
sections:
...
services:
adminserver:
image: ....
hostname: ...
ports:
- $((BASE_PORT+1)):8001
- $((BASE_PORT+2)):8002
- $((BASE_PORT+3)):8003
...
databaseserver:
image: ....
hostname: ...
ports:
- $((BASE_PORT+10)):1541
zookeeper:
image: ....
hostname: ...
ports:
- $((BASE_PORT+30)):2181
kafka:
image: ....
hostname: ...
ports:
- $((BASE_PORT+40)):9092
- $((BASE_PORT+41)):9093
- $((BASE_PORT+42)):9094
The $((BASE_PORT+1))
expression works in shell but it does not work in my *.yml file.
I get this error back:
ERROR: Invalid interpolation format for "ports" option in service "adminserver": "$((BASE_PORT+1)):8001"
Any idea how to make it works?
If you want to pass variables through the docker-compose process into any of the Dockerfiles present within docker-compose. yml , use the --build-arg parameter for each argument to flow into all of the Dockerfiles.
Docker Compose allows us to pass environment variables in via command line or to define them in our shell. However, it's best to keep these values inside the actual Compose file and out of the command line.
You can use ARG variable defaultValue and during the run command you can even update this value using --build-arg variable=value . To use these variables in the docker file you can refer them as $variable in run command.
Using –env, -e When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.
Docker Compose just doesn't support that.
In your example you have a range of contiguous ports on both the host and container side. The ports:
syntax does support this mode:
ports:
- '10000-10003:8000-8003'
There is still no expression parser or math capability, but you could write
ports:
- '${BASE_PORT}-${FINAL_PORT}:8000-8003'
and that would be closer to what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With