如何在Alpine Docker容器中运行bash脚本

我有一个目录只包含两个文件, Dockerfilesayhello.sh

 . ├── Dockerfile └── sayhello.sh 

Dockerfile读取

 FROM alpine COPY sayhello.sh sayhello.sh CMD ["sayhello.sh"] 

sayhello.sh包含简单

 echo hello 

Dockerfile成功build立:

 kurtpeek@Sophiemaries-MacBook-Pro ~/d/s/trybash> docker build --tag trybash . Sending build context to Docker daemon 3.072 kB Step 1/3 : FROM alpine ---> 665ffb03bfae Step 2/3 : COPY sayhello.sh sayhello.sh ---> Using cache ---> fe41f2497715 Step 3/3 : CMD sayhello.sh ---> Using cache ---> dfcc26c78541 Successfully built dfcc26c78541 

但是,如果我尝试run它,我得到一个executable file not found in $PATH错误:

 kurtpeek@Sophiemaries-MacBook-Pro ~/d/s/trybash> docker run trybash container_linux.go:247: starting container process caused "exec: \"sayhello.sh\": executable file not found in $PATH" docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"sayhello.sh\": executable file not found in $PATH". ERRO[0001] error getting events from daemon: net/http: request canceled 

有人可以解释是什么造成这个? (我记得在debian:jessie运行脚本debian:jessie基于debian:jessie的图像以类似的方式,所以也许这是阿尔卑斯特有的)?

Alpine以/ bin / sh作为默认shell而不是/ bin / bash

所以你可以

1)作为你的sayhello.sh的第一行有一个shebang定义/ bin / sh,所以你的文件sayhello.sh将以

#!/bin/sh

2)在你的Alpine图像中安装bash,因为你似乎期望bash存在,在你的Dockerfile中有这样一行

RUN apk add --update bash && rm -rf /var/cache/apk/*

通过使用CMDsayhello.sh正在searchPATHsayhello.sh ,但是您将其复制到/不在PATH

所以使用你想执行的脚本的绝对path:

 CMD ["/sayhello.sh"] 

顺便说一句,@ user2915097说,要小心,高山没有默认情况下,你的脚本在shebang中使用它。

记得授予所有脚本的执行权限。

 FROM alpine COPY sayhello.sh /sayhello.sh RUN chmod +x /sayhello.sh CMD ["/sayhello.sh"]