Pass host environment variables to dockerfile

前端 未结 4 414
执笔经年
执笔经年 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 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.

提交回复
热议问题