Dockerfile 中的条件 ENV [英] Conditional ENV in Dockerfile

查看:19
本文介绍了Dockerfile 中的条件 ENV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据构建 ARG 的值在 Dockerfile 中有条件地设置 ENV 变量?

Is it possible to conditionally set an ENV variable in a Dockerfile based on the value of a build ARG?

例如:类似的东西

ARG BUILDVAR=sad
ENV SOMEVAR=if $BUILDVAR -eq "SO"; then echo "hello"; else echo "world"; fi

更新:基于马里奥回答的当前使用情况:

Update: current usage based on Mario's answer:

ARG BUILD_ENV=prod
ENV NODE_ENV=production
RUN if [ "${BUILD_ENV}" = "test" ]; then export NODE_ENV=development; fi

但是,使用 --build-arg BUILD_ENV=test 运行然后进入主机,我仍然得到

However, running with --build-arg BUILD_ENV=test and then going onto the host, I still get

docker run -it mycontainer bin/bash
[root@brbqw1231 /]# echo $NODE_ENV
production

推荐答案

是的,这是可能的,但是您需要使用您的构建参数作为标志.您可以使用 shell 的 参数扩展 功能来检查条件.这是一个概念验证 Docker 文件:

Yes, it is possible, but you need to use your build argument as flag. You can use parameter expansion feature of shell to check condition. Here is a proof-of-concept Docker file:

FROM debian:stable
ARG BUILD_DEVELOPMENT
# if --build-arg BUILD_DEVELOPMENT=1, set NODE_ENV to 'development' or set to null otherwise.
ENV NODE_ENV=${BUILD_DEVELOPMENT:+development}
# if NODE_ENV is null, set it to 'production' (or leave as is otherwise).
ENV NODE_ENV=${NODE_ENV:-production}

测试构建:

docker build --rm -t env_prod ./
...
docker run -it env_prod bash
root@2a2c93f80ad3:/# echo $NODE_ENV 
production
root@2a2c93f80ad3:/# exit
docker build --rm -t env_dev --build-arg BUILD_DEVELOPMENT=1 ./
...
docker run -it env_dev bash
root@2db6d7931f34:/# echo $NODE_ENV
development

这篇关于Dockerfile 中的条件 ENV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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