Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do configure docker compose to use a given subnet if a variable is set, or choose for itself if it isn't?

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?

like image 361
Lukeus_Maximus Avatar asked Oct 20 '17 08:10

Lukeus_Maximus


People also ask

Can you use variables in Docker compose file?

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.

What should my Docker subnet be?

By default, Docker uses 172.17. 0.0/16 subnet range.

What is subnet in Docker network?

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.

How do I set an environment variable in Docker?

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.


1 Answers

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
like image 133
Matt Avatar answered Sep 29 '22 20:09

Matt