dockerfile中的docker run命令仅在未在cli上指定命令时才执行 [英] Docker run command in dockerfile executes only if dont specifiy a command on cli

查看:158
本文介绍了dockerfile中的docker run命令仅在未在cli上指定命令时才执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个Dockerfile:

Say I have a Dockerfile:

.
.
RUN echo 'source /root/script.sh' >> /etc/bash.bashrc

(脚本添加了一些env变量)

(The script adds some env variables)

如果我:

1)执行以下操作:

docker run -it -v /home/user/script.sh:/root/script.sh image

如果我叫 env,它将带我进入外壳,我会看到脚本设置的变量

It takes me to shell where if I call "env" I see the variable set by the script

但是如果我:

2)执行以下操作:

docker run -it -v /home/user/script.sh:/root/script.sh image env

打印出env并退出和我的变量丢失了

It prints out env and exits and my variable is missing

我缺少了什么?我需要变量存在,即使我在docker run命令的末尾指定了 env之类的命令/脚本

What am I missing? I need the variable to exists even if I specify a command/script like "env" at the end of the docker run command

推荐答案

当您运行类似命令

docker run ... image command

Docker 直接运行命令给;它不会启动任何类型的shell,也没有机会读取 .bashrc 或类似文件。

Docker directly runs the command you give; it doesn’t launch any kind of shell, and there’s no opportunity for a .bashrc or similar file to be read.

我在这里建议两件事:


  1. 如果您的程序确实需要以某种形式设置环境变量,请进行设置直接使用Dockerfile ENV 指令。不要尝试编辑 .bashrc / etc / profile 或任何其他Shell点文件;他们不会可靠地运行。

  1. If your program does need environment variables set in some form, set them directly using Dockerfile ENV directives. Don’t try to edit .bashrc or /etc/profile or any other shell dotfile; they won’t reliably get run.

尽可能多地将它们安装在适当的位置,从而无需更改环境变量。例如,Python支持虚拟环境概念,该概念允许隔离的库环境,这需要更改 $ PATH 和类似的东西;但是Docker本身提供了相同的隔离,因此只需将它们安装到全局包空间中即可。

As much as you can install things in places so that you don’t need to change environment variables. For instance, Python supports a "virtual environment" concept that allows an isolated library environment, which requires changing $PATH and similar things; but Docker provides the same isolation on its own, so just install things into the "global" package space.

如果您确实无法管理这两项,然后可以编写一个入口点脚本来设置环境变量,然后启动容器的命令。看起来像是

If you really can’t manage either of these things, then you can write an entrypoint script that sets environment variables and then launches the container’s command. This might look like

#!/bin/sh
. /root/script.sh
exec "$@"

然后可以包含此内容在您的Dockerfile中,例如

And then you could include this in your Dockerfile like

...
COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
CMD ["/app/myapp"]

(如果您需要使用 docker exec 在容器中获取调试外壳,那么它将不是入口点的子进程,也不会获取其环境变量。)

(If you need to use docker exec to get a debugging shell in the container, that won’t be a child process of the entrypoint and won’t get its environment variables.)

这篇关于dockerfile中的docker run命令仅在未在cli上指定命令时才执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆