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

Pri*_*til 3 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/
Run Code Online (Sandbox Code Playgroud)

我需要在docker build期间传递一个命令行参数来为$ hibernate_path指定.

我该怎么做呢?

Von*_*onC 8

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

此标志允许您传递RUN在Dockerfile 的指令中像常规环境变量一样访问的构建时变量.而且,这些值不像像ENV值一样存在于中间或最终图像中.

docker build --build-arg hibernate_path=/a/path/to/hibernate -t tag .
Run Code Online (Sandbox Code Playgroud)

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

Dockerfile.tpl:

...
ENV hibernate_path=xxx
ADD xxx/hibernate.cfg.xml /usr/share/tomcat7/webapps/roc_client/WEB-INF/classes/
...
Run Code Online (Sandbox Code Playgroud)

无论何时想要构建映像,首先要生成Dockerfile:

sed "s,xxx,${hibernate_path},g" Dockerfile.tpl > Dockerfile
Run Code Online (Sandbox Code Playgroud)

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

然后你会受益于(在docker 1.7中):

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