一段时间以来,我一直在使用 docker。我遇到过一种情况,我需要根据某些条件执行 Dockerfile 中存在的指令。例如这里是 Dockerfile 的片段
FROM centos:centos7
MAINTAINER Akshay <akshay@dm.com>
# Update and install required binaries
RUN yum update -y \
&& yum install -y which wget openssh-server sudo java-1.8.0-openjdk \
&& yum clean all
#install Maven
RUN curl -Lf http://archive.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz -o /tmp/apache-maven-3.3.9.tar.gz
RUN tar -xzf /tmp/apache-maven-3.3.9.tar.gz -C /opt \
&& rm /tmp/apache-maven-3.3.9.tar.gz
ENV M2_HOME "/opt/apache-maven-3.3.9"
ENV PATH ${PATH}:${M2_HOME}/bin:
# Install Ant
ENV ANT_VERSION 1.9.4
RUN cd && \
wget -q http://archive.apache.org/dist/ant/binaries/apache-ant-${ANT_VERSION}-bin.tar.gz && \
tar -xzf apache-ant-${ANT_VERSION}-bin.tar.gz && \
mv apache-ant-${ANT_VERSION} /opt/ant && \
rm apache-ant-${ANT_VERSION}-bin.tar.gz
ENV ANT_HOME /opt/ant
ENV PATH ${PATH}:/opt/ant/bin
......
Run Code Online (Sandbox Code Playgroud)
所以正如你在我的 docker 文件中看到的,我有 maven 和 ant 的安装说明。但是现在我必须根据条件安装其中任何一个。我知道我可以ARG在构建时使用Dockerfile 中的指令来获取参数,但问题是我找不到任何关于如何将它们包含在if/else块。
我看过一些其他的计算器帖子太关于这一点,但在那些我看到,他们纷纷要求使用指令如内部条件语句RUN if $BUILDVAR -eq "SO"; then export SOMEVAR=hello; else export SOMEVAR=world; fi链接,或写像一个单独的脚本文件,这
可是你可以看到,我的情况是不同的。我不能让我们知道这一点,因为我也会有一堆其他指令,这取决于那个论点。我必须做这样的事情
ARG BUILD_TOOL
if [ "${BUILD_TOOL}" = "MAVEN" ]; then
--install maven
elif [ "${BUILD_TOOL}" = "ANT" ]; then
--install ant
fi
.... other instructions ....
if [ "${BUILD_TOOL}" = "MAVEN" ]; then
--some other dependent commands
elif [ "${BUILD_TOOL}" = "ANT" ]; then
--some other dependent commands
fi
Run Code Online (Sandbox Code Playgroud)
如果您不想使用所有这些RUN if语句,您可以使用设置过程创建一个 bash 脚本,并从 Dockerfile 中调用它。例如:
FROM centos:centos7
MAINTAINER Someone <someone@email.com>
ARG BUILD_TOOL
COPY setup.sh /setup.sh
RUN ./setup.sh
RUN rm /setup.sh
Run Code Online (Sandbox Code Playgroud)
和setup.sh文件(不要忘记使其可执行):
FROM centos:centos7
MAINTAINER Someone <someone@email.com>
ARG BUILD_TOOL
COPY setup.sh /setup.sh
RUN ./setup.sh
RUN rm /setup.sh
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用docker build --build-arg BUILD_TOOL=MAVEN .(或ANT)构建它。
请注意,我在这里使用了 shell 脚本,但如果您有其他可用的解释器(例如:python 或 ruby),您也可以使用它们来编写安装脚本。
| 归档时间: |
|
| 查看次数: |
2953 次 |
| 最近记录: |