Pass host environment variables to dockerfile
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
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.
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.