docker - exec形式的Docker RUN命令不起作用
问题描述
我正在构建一个基于 Alpine 的 docker 镜像。
FROM alpine
RUN apk update \
&& apk add lighttpd \
&& rm -rf /var/cache/apk/*
ENV COLOR red
COPY ./index.html /var/www/localhost/htdocs
RUN /bin/ash -c 'echo abcd'
#working
RUN /bin/ash -c "echo $COLOR; sed -i -e 's/red/\$COLOR/g' /var/www/localhost/htdocs/index.html; cat /var/www/localhost/htdocs/index.html;"
#not working
# RUN ["sh", "-c", "echo $COLOR; sed -i -e 's/red/\$COLOR/g' /var/www/localhost/htdocs/index.html; cat /var/www/localhost/htdocs/index.html;"]
CMD ["lighttpd","-D","-f","/etc/lighttpd/lighttpd.conf"]
当我以 shell 形式运行时,它工作正常,但是当我以 exec 形式运行时,它给出了
/bin/sh: [sh,: 未找到
我尝试使用bin/sh
, sh
, bin/ash
, ash
. 他们所有人都犯了同样的错误。
解决方案
Shell 负责扩展变量,但只有双引号中的变量才会被扩展。
您的错误来自\
之前的错误$COLOR
,实际上您从shell中获取值没有任何意义,正确的方法是下一个:
RUN ["sh", "-c", "echo $COLOR; sed -i -e \"s/red/$COLOR/g\" /var/www/localhost/htdocs/index.html; cat /var/www/localhost/htdocs/index.html;"]
显示效果的最小示例,仅供参考:
Dockerfile:
FROM alpine
ENV COLOR rednew
RUN echo "red" > /tmp/index.html
RUN ["sh", "-c", "sed -i -e \"s/red/$COLOR/g\" /tmp/index.html; cat /tmp/index.html;"]
结果:
$ docker build -t abc:1 . --no-cache
Sending build context to Docker daemon 5.632kB
Step 1/4 : FROM alpine
---> 28f6e2705743
Step 2/4 : ENV COLOR rednew
---> Running in 05c43146fab0
Removing intermediate container 05c43146fab0
---> 28ea1434e626
Step 3/4 : RUN echo "red" > /tmp/index.html
---> Running in 2c8fbbc5fd10
Removing intermediate container 2c8fbbc5fd10
---> f884892ad8c4
Step 4/4 : RUN ["sh", "-c", "sed -i -e \"s/red/$COLOR/g\" /tmp/index.html; cat /tmp/index.html;"]
---> Running in 6930b3d03438
rednew
Removing intermediate container 6930b3d03438
---> b770475672cc
Successfully built b770475672cc
Successfully tagged abc:1
推荐阅读
- sql - 前 5 周的 T-SQL 返回金额?
- java - 放心的 JsonPath 查询
- javascript - 如何使用 Webpack 4 公开 javascript 模块的默认导出对象?
- php - 获取嵌套父母的完整路径
- java - Codenameone 上的 Youtube 播放器
- powershell - pssession,调用命令没有得到变量
- actions-on-google - 保存用户信息 DialogFlow
- python - 调整大小和裁剪图像后查找新的 (X,Y)
- neural-network - Keras LSTM 让我的电脑崩溃了?
- typescript - 限制方法中的接口类型参数