如果设置了变量,如何配置docker compose以使用给定的子网,如果没有设置,如何自行选择? [英] How do configure docker compose to use a given subnet if a variable is set, or choose for itself if it isn't?

查看:83
本文介绍了如果设置了变量,如何配置docker compose以使用给定的子网,如果没有设置,如何自行选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的docker compose文件中具有以下网络配置.

I have the following networks configuration in my docker compose file.

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

设置 DOCKER_SUBNET 后,将按预期使用该变量中指定的子网.当未设置变量时,我得到:错误:无效的子网:无效的CIDR地址:,因为变量为空(完全合理).

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).

是否可以配置ipam驱动程序,以便在未设置 DOCKER_SUBNET 变量时,docker-compose将选择可用的子网,就像通常不提供ipam配置一样?

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?

推荐答案

仅当您不为网络提供任何 ipam 配置时,Compose才会选择可用的子网.Compose没有高级功能来动态修改配置.

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.

您可以使用多个撰写文件或基于模板的系统,使用Shell或其他启动 docker-compose 命令的语言.

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}

然后创建一个脚本 launch.sh ,该脚本可以选择要包含的网络文件.

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

这篇关于如果设置了变量,如何配置docker compose以使用给定的子网,如果没有设置,如何自行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆