I have the following networks configuration in my docker compose file.
networks:
default:
ipam:
driver: default
config:
- subnet: ${DOCKER_SUBNET}
When DOCKER_SUBNET
is set, the subnet specified in that variable is used as expected. When the variable is not set I get: ERROR: Invalid subnet : invalid CIDR address:
because the variable is blank (which is entirely reasonable).
Is there a way to configure the ipam driver such that when the DOCKER_SUBNET
variable is not set, docker-compose will choose an available subnet as it would normally do if the ipam configuration was not given?
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.
By default, Docker uses 172.17. 0.0/16 subnet range.
This subnet is the network used for the Docker daemon environment running in the VM or Hyper-V container. On macOS, you can enter the Docker VM and look around, using the below command. docker run -it --rm --privileged --pid=host justincormack/nsenter1.
Use -e or --env value to set environment variables (default []). If you want to use multiple environments from the command line then before every environment variable use the -e flag. Note: Make sure put the container name after the environment variable, not before that.
Compose will only choose an available subnet if you don't provide any ipam
configuration for the network. Compose doesn't have advanced functionality to modify config on the fly.
You could make the decision outside of compose, either with multiple compose files or a template based system, in shell or some other language that launches the docker-compose
command.
Seperate your network config from you service config
docker-compose-net-auto.yml
version: "2.1"
networks:
default:
docker-compose-net-subnet.yml
version: "2.1"
networks:
default:
ipam:
driver: default
config:
- subnet: ${DOCKER_SUBNET}
Then create a script launch.sh
that makes the choice of which network file to include.
#!/bin/sh
if [ -z "$DOCKER_SUBNET" ]; then
docker-compose -f docker-compose.yml -f docker-compose-net-auto.yml up
else
docker-compose -f docker-compose.yml -f docker-compose-net-subnet.yml up
fi
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