Pass host environment variables to dockerfile

user5524899 picture user5524899 · Aug 1, 2017 · Viewed 20.7k times · Source

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

Answer

Serey picture Serey · Aug 1, 2017

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.