Dockerfile添加启动脚本后执行报错:文件存在却提示不存在
问题:Docker容器执行脚本报错"exec /app/test.sh: no such file or directory"
我编写了如下Dockerfile:
FROM alpine:latest WORKDIR /app RUN echo -e "#!/bin/bash\necho test" > /app/test.sh RUN chmod 744 /app/test.sh ENTRYPOINT [ "/app/test.sh" ]
运行容器时,却报错:exec /app/test.sh: no such file or directory。
我尝试在ENTRYPOINT前添加命令验证文件状态:
FROM alpine:latest WORKDIR /app RUN echo -e "#!/bin/bash\necho test" > /app/test.sh RUN chmod 744 /app/test.sh RUN ls -al && exit 1 ENTRYPOINT [ "/app/test.sh" ]
构建结果显示test.sh确实存在且拥有执行权限:
[+] Building 0.6s (8/8) FINISHED docker:default => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 200B 0.0s => [internal] load metadata for docker.io/library/alpine:latest 0.3s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [1/5] FROM docker.io/library/alpine:latest@sha256:77726ef6b57ddf65bb551896826ec38bc3e53f75cdde31354fbffb4f25238ebd 0.0s => CACHED [2/5] WORKDIR /app 0.0s => CACHED [3/5] RUN echo -e "#!/bin/bash\necho test" > /app/test.sh 0.0s => CACHED [4/5] RUN chmod 744 /app/test.sh 0.0s => ERROR [5/5] RUN ls -al && exit 1 0.2s ------ > [5/5] RUN ls -al && exit 1: 0.171 total 16 0.171 drwxr-xr-x 1 root root 4096 May 31 05:21 . 0.171 drwxr-xr-x 1 root root 4096 May 31 05:28 .. 0.171 -rwxr--r-- 1 root root 22 May 31 05:21 test.sh ------ Dockerfile:5 -------------------- 3 | RUN echo -e "#!/bin/bash\necho test" > /app/test.sh 4 | RUN chmod 744 /app/test.sh 5 | >>> RUN ls -al && exit 1 6 | ENTRYPOINT [ "/app/test.sh" ] -------------------- ERROR: failed to solve: process "/bin/sh -c ls -al && exit 1" did not complete successfully: exit code: 1
明明文件存在且有权限,请问问题出在哪里?
问题原因与解决方案
原因分析
Alpine镜像默认只预装了轻量shell ash,没有安装bash。你的脚本开头用#!/bin/bash指定了解释器,容器执行脚本时找不到/bin/bash,就会抛出exec /app/test.sh: no such file or directory错误——这是Linux系统的常见行为:不是脚本文件不存在,而是脚本依赖的解释器不存在。
解决方案
有两种可行的解决方式:
方案1:改用Alpine默认的ash
把脚本的shebang改成#!/bin/sh,修改后的Dockerfile:
FROM alpine:latest WORKDIR /app RUN echo -e "#!/bin/sh\necho test" > /app/test.sh RUN chmod 744 /app/test.sh ENTRYPOINT [ "/app/test.sh" ]
方案2:在Alpine中安装bash
如果必须使用bash,可以在构建阶段通过apk安装:
FROM alpine:latest WORKDIR /app RUN apk add --no-cache bash RUN echo -e "#!/bin/bash\necho test" > /app/test.sh RUN chmod 744 /app/test.sh ENTRYPOINT [ "/app/test.sh" ]
内容的提问来源于stack exchange,提问作者Ahmad
相关产品推荐
相关产品推荐

