Dockerfile中的条件ENV [英] Conditional ENV in Dockerfile
本文介绍了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
更新:基于Mario答案的当前用法:
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
推荐答案
是的,可以,但是您需要使用build参数作为标志。您可以使用外壳程序的参数扩展功能来检查条件。这是概念验证的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屋!
查看全文