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

How to provide and use command line arguments in docker build?

我有一个 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 构建过程中为 $hibernate_path.

指定一个命令行参数

我该怎么做?

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

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

This flag allows you to pass the build-time variables that are accessed like regular environment variables in the RUN instruction of the Dockerfile. Also, these values don’t persist in the intermediate or final images like ENV values do.

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 中):

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