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
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.
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
you need to use the ENV
setting in your dockerfile
ENV myuser=$USER
https://docs.docker.com/engine/reference/builder/#env