Pass host environment variables to dockerfile

Viewed 30606

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
4 Answers

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, as per the question I'm also including 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.

Related