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

发布于 2021-02-01 13:01:28

我的目录仅包含两个文件,Dockerfile并且sayhello.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特有的)?

关注者
0
被浏览
190
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    Alpine附带ash作为默认外壳,而不是bash

    所以你可以

    1. 有一个shebang将/ bin / bash定义为sayhello.sh的第一行,因此您的文件sayhello.sh将以bin / sh开头

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

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


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看