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

新手上路,请多包涵

我有一个只包含两个文件的目录, 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 的图像中运行脚本。所以也许它是阿尔卑斯山特有的?

原文由 Kurt Peek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.4k
2 个回答

Alpine 使用 ash 作为默认 shell 而不是 bash

这样你就可以

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

  1. 在你的 Alpine 镜像中安装 Bash,正如你所期望的那样,Bash 存在,在你的 Dockerfile 中有这样一行:
    RUN apk add --no-cache --upgrade bash

原文由 user2915097 发布,翻译遵循 CC BY-SA 4.0 许可协议

这个答案 是完全正确的并且工作正常。

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

您需要更改 CMD 如下:

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

这也有效。

原文由 Shahriar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题