问题描述
我有一个 Dockerfile
,该文件当前使用以下内容:
I have a Dockerfile
which currently uses the following:
COPY ./compose/local/django/start.sh /start.sh
RUN sed -i 's/\r//' /start.sh
RUN chmod +x /start.sh
您可以看到它复制了文件,然后使其可执行。现在,我需要根据构建映像时提供的参数来更改此设置。我试过使用此命令:
As you can see it copies the file and then makes it executable. I now need to change this depending on a argument provided when I build the image. I have tried using this:
RUN if [ "$arg" = "True" ]; then \
COPY ./compose/local/django/new.sh /new.sh \
RUN sed -i 's/\r//' /new.sh \
RUN chmod +x /new.sh; else \
COPY ./compose/local/django/start.sh /start.sh \
RUN sed -i 's/\r//' /start.sh \
RUN chmod +x /start.sh; fi
但这失败了,因为看来我不能运行 COPY
或 RUN
命令在条件语句中。它总是失败,并显示以下内容:
But this fails as it appears that I can't run COPY
or RUN
commands inside a conditional statement. It always fails with:
/bin/sh: 1: COPY: not found
或
/bin/sh: 1: RUN: not found
所以,我认为最好的做法是创建一个单独的bash
So, I think that the best course of action is to create a separate bash file which does the copies, something like:
#!/usr/bin/env bash
if [ "${arg}" = "True" ]; then
echo "arg = ${arg}"
cp ./compose/local/django/new.sh /new.sh
elif [ "${arg}" = "False" ]; then
echo "arg = ${arg}"
cp ./compose/local/django/start.sh /start.sh
fi
但是我在努力使复制的bash文件可执行。我知道我可以通过在命令行中运行 chmod + x
来做到这一点,但是由于我不是唯一要构建此代码的人,所以我希望会是一个更好的解决方案,就像我以前在原始 Dockerfile
脚本中所做的一样。
But I am struggling with how to make the copied bash files executable. I know I can do it by running chmod +x
in the command line, but as I am not the only person who is going to be building this, I was hoping that there would be a better solution, something like I was doing previously in the original Dockerfile
script.
有人可以帮助我吗?有了这个?任何帮助将不胜感激。
Can anyone help me with this? Any help would be much appreciated.
推荐答案
仅使用一个 RUN语句。这是一种最佳做法,因为它会减小图像占用的大小。
Use only one 'RUN' statement. It's a best practice as it will reduce the size taken by your image.
这是将参数传递给docker build的方式。
This is how you can pass an argument to docker build.
Dockerfile:
Dockerfile:
...
ARG NEW
COPY ./compose/local/django/new.sh /new.sh
COPY ./compose/local/django/start.sh /start.sh
RUN if [ "$NEW" = "True" ]; then \
sed -i 's/\r//' /new.sh && \
chmod +x /new.sh; \
else \
sed -i 's/\r//' /start.sh && \
chmod +x /start.sh; \
fi
并像这样构建它
docker build --build-arg NEW="True" .
这篇关于在Dockerfile中的条件语句中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!