如何在docker build中提供和使用命令行参数?

时间:2016-02-22 11:46:34

标签: docker dockerfile

我有一个Dockerfile,如下所示:

FROM centos:centos6
MAINTAINER tapash

######  Helpful utils
RUN yum -y install sudo
RUN yum -y install curl
RUN yum -y install unzip

#########Copy hibernate.cfg.xml to Client

ADD ${hibernate_path}/hibernate.cfg.xml /usr/share/tomcat7/webapps/roc_client/WEB-INF/classes/

我需要在docker build期间传递一个命令行参数,以便为$ hibernate_path指定。

我该怎么做?

2 个答案:

答案 0 :(得分:8)

如果这纯粹是构建时变量,则可以使用--build-arg option of docker build

  

此标志允许您传递像Dockerfile的RUN指令中的常规环境变量一样访问的构建时变量。此外,这些值不会像ENV值那样在中间或最终图像中保留。

docker build --build-arg hibernate_path=/a/path/to/hibernate -t tag .

在1.7中,只有静态ENV Dockerfile directive可用 因此,一种解决方案是从模板Dockerfile.tpl生成所需的Dockerfile。

Dockerfile.tpl:

...
ENV hibernate_path=xxx
ADD xxx/hibernate.cfg.xml /usr/share/tomcat7/webapps/roc_client/WEB-INF/classes/
...

每当你想要构建图像时,首先生成Dockerfile:

sed "s,xxx,${hibernate_path},g" Dockerfile.tpl > Dockerfile

然后你正常建立:docker build -t myimage .

然后您(在docker 1.7中)受益:

  • 构建时环境替换
  • 运行时环境变量。

答案 1 :(得分:0)

您创建一个脚本,将Dockerfile中的所需值放入并启动docker build -t mytag .