Search code examples
dockerenvironment-variablesdocker-composedocker-network

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?


Solution

  • 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 yaml 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 the custom compose network config into it's own yml file:

    docker-compose-net-subnet.yml

    networks:
      default:
        ipam:
          driver: default
          config:
            - subnet: ${DOCKER_SUBNET}
    

    docker-compose.yml

    <...>
    networks:
      default:
    

    Then create a script launch.sh that makes the choice of whether to merge the network config or not, based on the environment variable.

    #!/bin/sh
    if [ -z "$DOCKER_SUBNET" ]; then
      docker-compose -f docker-compose.yml up "$@"
    else
      docker-compose -f docker-compose.yml -f docker-compose-net-subnet.yml up "$@"
    fi