Pass host environment variables to dockerfile

前端 未结 4 415
执笔经年
执笔经年 2020-12-28 20:23

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

For example, if my username is taha:

echo $USER
tah         


        
相关标签:
4条回答
  • 2020-12-28 20:51

    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 
    
    0 讨论(0)
  • 2020-12-28 21:00

    I had a similar use-case where I wanted to be able to specify a version for the image. This has a slight extra requirement that you must specify the ARG before the FROM.

    First we specify IMAGE_VERSION in the Dockerfile, I'm also include a USER arg that we can pass in too:

    # give it a default of latest
    # declare the ARG before FROM
    ARG IMAGE_VERSION=latest
    FROM centos:${IMAGE_VERSION}
    ARG myuser  
    CMD echo $myuser
    

    Then, as from the Docker compose docs on args:

    Add build arguments, which are environment variables accessible only during the build process.

    You can add these in your docker-compose.yml for example:

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

    Then as long as you have IMAGE_VERSION set in your environment it will be passed through.

    0 讨论(0)
  • 2020-12-28 21:09

    you need to use the ENV setting in your dockerfile

    ENV myuser=$USER

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

    0 讨论(0)
  • 2020-12-28 21:18

    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.

    0 讨论(0)
提交回复
热议问题