如何在 Alpine Docker 容器中 运行 一个 Bash 脚本?

How do I run a Bash script in an Alpine Docker container?

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

.
├── Dockerfile
└── sayhello.sh

Dockerfile 读取

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

sayhello.sh只包含

echo hello

Dockerfile 构建成功:

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 的图像中的 运行 脚本。所以也许它是 Alpine 特有的?

Alpine 默认带有 ash shell 而不是 bash

所以你可以

  1. 将 /bin/bash 定义为 sayhello.sh 的第一行,这样您的文件 sayhello.sh 将以 bin/sh[=14 开头=]

    #!/bin/sh
    
  2. 在您的 Alpine 映像中安装 Bash,正如您所期望的那样 Bash 存在,在您的 Dockerfile 中有这样一行:

    RUN apk add --no-cache --upgrade bash
    

通过使用 CMD,Docker 正在搜索 PATH 中的 sayhello.sh 文件,但您将其复制到 / 中,但不在PATH.

因此请使用您要执行的脚本的绝对路径:

CMD ["/sayhello.sh"]

顺便说一句,正如@user2915097 所说,请注意 Alpine 默认情况下没有 Bash,以防您的脚本在 shebang 中使用它。

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

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

完全正确,工作正常。

还有一个办法。您可以在基于 Alpine 的 Docker 容器中 运行 Bash 脚本。

您需要像下面这样更改 CMD:

CMD ["sh", "sayhello.sh"]

这也行。