git - Docker 将变量传递给运行 git clone 的 shell 脚本

标签 git bash shell docker environment-variables

我正在创建一个 Dockerfile,作为该文件的一部分,我想让最终用户可以选择传入他们的 git 存储库。

我看了this SO post , 和其他一些网站,但我仍然停留在 git clone 语法上。

git clone 命令返回错误,因为作为它一部分的变量在 docker build 阶段不包含值。

我有一个名为 gitclone.sh 的 bash 脚本

#!/bin/bash
git clone $1 /app

在我的 Dockerfile 中有这一行:

运行 ./gitclone.sh $LOCATION

shell 脚本具有正确的运行权限,并且在从容器内运行它时它可以工作,因为我将一个实际的存储库传递给它。

在 Docker 构建阶段,我收到以下错误:

fatal: repository '/app' does not exist

目录在那里,但是 $1 是空的,命令不起作用。

问题 如何使 Dockerfile 工作?我想要的期望输出:

docker run -e LOCATION=https://github.com/something.git -d jwknz/pg02

更新 更改我的 Dockerfile 以包含 CMD ["../gitclone.sh","$LOCATION"] 而不是 RUN ./gitclone.sh $LOCATION 无法修复它。

Dockerfile 将构建,但容器在运行 docker run 命令后停止。

最佳答案

首先,您必须注意 Dockerfile 用于构建您的镜像(使用 docker build 命令)和 docker run用于从已经构建的 docker 镜像启动容器。

您必须定义一个入口点 脚本。这是每次从您使用 Dockerfile 构建的镜像启动容器时执行的脚本。

假设您想克隆一个 git 存储库并在之后运行 apache httpd,您可以在 Dockerfile 所在的同一文件夹中创建这样的脚本。命名它,例如gitCloneAndRunHttpd.sh

#!/bin/bash 

git clone $LOCATION /app 
/usr/local/apache2/bin/apachectl -f /usr/local/apache2/conf/httpd.conf 

然后你必须修改你的 Dockerfile 告诉 docker 将脚本文件复制到你的 docker 镜像,使其可执行,然后告诉它在创建容器时运行它:

[...]

COPY ["gitCloneAndRunHttpd.sh", "/gitCloneAndRunHttpd.sh"]
RUN chmod +x /gitCloneAndRunHttpd.sh
ENTRYPOINT ["/gitCloneAndRunHttpd.sh"]

在此之后,您可以使用 docker build 命令构建您的 docker 镜像,然后您可以开始从您的镜像创建容器。

每次你使用 docker run -e LOCATION=https://github.com/some-git-repo.url -d your/image 从它启动一个容器时,repo https://github.com/some-git-repo.url 将从容器内克隆到/app 文件夹,并启动 apache httpd。

注意:如果您想知道 SO post 中发生了什么你提到过,那里使用了默认的入口点 (/bin/sh),/file.sh abc 是传递给那个入口点的参数,因此 file.sh 脚本被执行。

关于git - Docker 将变量传递给运行 git clone 的 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44352933/

相关文章:

shell - 我们如何才能使 ls --color = 始终在 Sun Os 中工作

git - 新 github 分支的 sha/hash

git - git merge 冲突的不同方案

python - 使用命令行垂直分割csv文件

linux - 使用 TOP 命令获取所有 CPU 使用率

bash - FFmpeg 通过文件输入计算出 mp3 持续时间,但使用管道失败?

git - Gerrit - 如何在 Jenkins 运行后自动发布更改

Git 魔术引用

Bash 信号捕获未检测到声明 'trap' block 后更改的变量

json - 使用 jq 就地修改 json 中的键值