如果设置了变量,如何将 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?

查看:21
本文介绍了如果设置了变量,如何将 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 时,该变量中指定的子网将按预期使用.当变量未设置时,我得到:ERROR: Invalid subnet : invalid CIDR address: 因为变量为空(这是完全合理的).

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天全站免登陆