如何在 Dockerfile 中运行 bash 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32707839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run bash function in Dockerfile
提问by Quanlong
I have a bash function nvm
defined in /root/.profile
. docker build
failed to find that function when I call it in RUN
step.
我在 .bashrc 中nvm
定义了一个 bash 函数/root/.profile
。docker build
当我RUN
一步一步调用它时,未能找到该函数。
RUN apt-get install -y curl build-essential libssl-dev && \
curl https://raw.githubusercontent.com/creationix/nvm/v0.16.1/install.sh | sh
RUN nvm install 0.12 && \
nvm alias default 0.12 && \
nvm use 0.12
The error is
错误是
Step 5 : RUN nvm install 0.12
---> Running in b639c2bf60c0
/bin/sh: nvm: command not found
I managed to call nvm
by wrapping it with bash -ic
, which will load /root/.profile
.
我设法nvm
通过用 包装它来调用bash -ic
,这将加载/root/.profile
.
RUN bash -ic "nvm install 0.12" && \
bash -ic "nvm alias default 0.12" && \
bash -ic "nvm use 0.12"
The above method works fine, but it has a warning
上述方法工作正常,但有警告
bash: cannot set terminal process group (1): Inappropriate ioctl for device
bash: no job control in this shell
And I want to know is there a easier and cleaner way to call the bash function directly as it's normal binary without the bash -ic
wrapping? Maybe something like
我想知道有没有一种更简单、更简洁的方法来直接调用 bash 函数,因为它是没有bash -ic
包装的普通二进制文件?也许像
RUN load_functions && \
nvm install 0.12 && \
nvm alias default 0.12 && \
nvm use 0.12
采纳答案by hek2mgl
Docker's RUN
doesn't start the command in a shell. That's why shell functions and shell syntax (like cmd1
&& cmd2
) cannot being used out of the box. You need to call the shell explicitly:
DockerRUN
不在 shell 中启动命令。这就是 shell 函数和 shell 语法(如cmd1
&& cmd2
)不能开箱即用的原因。您需要显式调用 shell:
RUN bash -c 'nvm install 0.12 && nvm alias default 0.12 && nvm use 0.12'
If you are afraid of that long command line, put those commands into a shell script and call the script with RUN
:
如果您害怕那么长的命令行,请将这些命令放入 shell 脚本并使用以下命令调用脚本RUN
:
script.sh
脚本文件
#!/bin/bash
nvm install 0.12 && \
nvm alias default 0.12 && \
nvm use 0.12
and make it executable:
并使其可执行:
chmod +x script.sh
In Dockerfile put:
在 Dockerfile 中输入:
RUN /path/to/script.sh