将主机环境变量传递给 dockerfile [英] Pass host environment variables to dockerfile
问题描述
如何将主机环境变量(如用户和主机名)传递给 dockerfile?
How can I pass a host environment variable (like user and hostname) to a dockerfile?
例如,如果我的用户名是taha
:
For example, if my username is taha
:
echo $USER
taha
如何编写我的 Docker 文件以获得相同的输出?
How do I write my Docker file to get the same output?
FROM centos:centos7
ARG myuser=$USER
CMD echo $myuser
推荐答案
我遇到了同样的问题.我的解决方案是在 docker-compose.yml 中提供变量,因为 yml 支持使用环境变量.
I was experiencing the same issue. My solution was to provide the variable inside of a docker-compose.yml because yml supports the use of environment variables.
在我看来,这对我来说是最有效的方法,因为我不喜欢在命令行中使用类似 docker run -e myuser=$USER 之类的东西一遍又一遍地输入它...
In my opinion this is the most efficient way for me because I didn't like typing it over and over again in the command line using something like docker run -e myuser=$USER . . .
声明 ENV myuser=$USER
将不起作用,在容器中,$myuser
将被设置为 null
.
Declaring ENV myuser=$USER
will NOT work, in the container, $myuser
will be set to null
.
所以你的 docker-compose.yml 可能看起来像这样:
So your docker-compose.yml could look something like this:
version: '3'
services:
app:
build:
context: .
dockerfile: Dockerfile
environment:
- "myuser=${USER}"
并且可以使用短命令 docker-compose up
要检查变量是否已应用,请运行 docker exec -it container-name printenv
以列出容器中的所有变量.
To check that the variable has been applied, run docker exec -it container-name printenv
to list all variables in the container.
这篇关于将主机环境变量传递给 dockerfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!