Pass host environment variables to dockerfile

2020-02-23 08:05发布

How can I pass a host environment variable (like user and hostname) to a dockerfile?

For example, if my username is taha:

echo $USER
taha

How do I write my Docker file to get the same output?

FROM centos:centos7   
ARG myuser=$USER  
CMD echo $myuser

3条回答
Ridiculous、
2楼-- · 2020-02-23 08:43

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.

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 . . .

Declaring ENV myuser=$USER will NOT work, in the container, $myuser will be set to null.

So your docker-compose.yml could look something like this:

version: '3'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
       - "myuser=${USER}"

and can be run with the short command docker-compose up

To check that the variable has been applied, run docker exec -it container-name printenv to list all variables in the container.

查看更多
劫难
3楼-- · 2020-02-23 08:44

When you start your docker container you can pass environment variables using the -e option like so:

docker run -it <image> -e USER=$USER /bin/bash 
查看更多
劳资没心,怎么记你
4楼-- · 2020-02-23 08:58

you need to use the ENV setting in your dockerfile

ENV myuser=$USER

https://docs.docker.com/engine/reference/builder/#env

查看更多
登录 后发表回答