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