【问题标题】:How to stop building When I use Dockerfile build image?当我使用 Dockerfile 构建映像时如何停止构建?
【发布时间】:2018-11-01 07:38:32
【问题描述】:

我在下面的 Dockerfile 中编写了一些 shell 代码来检查容器中的一些目录,如果它没有我想停止构建的那些文件夹。那么我应该在 Dockerfile 中写什么来停止它?

FROM XXX
...
RUN if [ -d "/app/bin" -a  -d "/app/lib" -a -d "/app/conf" -a -d "/app/resource" -a -d "/app/log" -a -f "/app/bin/start.sh" ]; then mkdir -p /app/control/bin;  else SOME_CODES_TO_STOP_BUILDING; fi
...

【问题讨论】:

    标签: docker cloud containers dockerfile


    【解决方案1】:

    任何失败的 shell 命令(返回 0 以外的退出状态)都将停止构建。一些例子:

    # Probably the most idiomatic shell scripting: if the test
    # returns false, then the "&&" won't run mkdir, and the whole
    # command returns false
    RUN test -d /app/bin -a ... \
     && mkdir /app/control/bin
    
    # "test" and "[" are the same thing
    RUN [ -d /app/bin -a ... ] \
     && mkdir /app/control/bin
    
    # This first step will just blow up the build if it fails
    RUN [ -d /app/bin -a ... ]
    # Then do the on-success command
    RUN mkdir /app/control/bin
    
    # Your original suggestion
    # /bin/false does nothing but returns 1
    RUN if [ -d /app/bin -a ... ]; \
        then mkdir /app/control/bin; \
        else false; \
        fi
    

    【讨论】:

    • 谢谢@David Maze。我同意你的看法。我只是在else 语句中写exit -1 并得到相同的结果,我认为您的方法更加简化。谢谢!
    • 我刚刚完成并手动测试了这个(之前是FROM busybox,之后是RUN echo x),所有这些情况都会停止构建。
    • 我最终在这里试图找到一种测试构建更改并在某个步骤退出的好方法,您的回答帮助了我,RUN false 成功了
    【解决方案2】:

    您不想在构建映像之前检查这些目录吗?我建议仅在目录存在时创建一个 shell 脚本并执行 docker build 命令。

    【讨论】:

    • 感谢@Siddharth Singh。我必须在我的 java 程序中编写检查逻辑,但我没有找到 docker-java 可以返回合适的值,因为它的 CreateContainerCmdITstartContainerCmd API 只返回容器 ID 和空警告。所以我必须使用Dockerfile 方法。
    猜你喜欢
    • 2018-04-23
    • 2021-01-22
    • 2018-05-06
    • 2018-08-05
    • 2020-10-17
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多