PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

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

 November 05, 2022     docker, docker-compose, docker-networking, environment-variables     No comments   

Issue

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 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 compose network config from the rest of the service config in files:

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


Answered By - Matt
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing