Pass Environment Variables From the Host Machine to your Docker Container
An easy way to pass the values of your current environment variables to a Docker container.
Are you tired of typing out the values of
-e parameters every single time when you run your
containers? Maybe the values are even sensitive, and should not end up in your logs (if you’re
using a CI tool like Jenkins or GitLab CI) or bash history.
If there a way to pass values to environment variables of Docker containers, without typing them out?
Passing Environment Variable Values
You can pass the values of environment variables from the host to your containers without much effort. Simply don’t specify a value in the command line, and make sure that the environment variable is named the same as the variable the containerized app expects:
$ docker run -e var_name (...)
In the above snippet, the value of a
var_name variable in the current environment is used to set the value
var_name in the container environment upon startup.
Alternative: Ditch Command Line Arguments
Typing out variable names and values for every single command is tedious, apart from the downsides listed above.
You can use
env_files, to pass a bunch of environment variables and their values to a command at once.
$ docker run --env-file=env_file_name alpine env
Better yet, you might consider to switch away from using the Docker CLI, and make use of docker-compose.yml files instead. It is a convenient way to put all details you normally would have to specify into a single file and apply them automatically on every command where it matters with Docker Compose or Docker Stack.
In the article above, you’ve seen a way to pass the values of environment variables from the host machine to your Docker containers. Also, you’ve seen two ways to ditch a few tedious command-line-arguments when working with your Docker images and containers. There’s a lot more to really understand and master using ARG and ENV with Docker.
If you want to get a good overview of build-time arguments, environment variables, env_files and docker-compose templating with .env files - head over to this in-depth guide and give it a read.
I’m sure you’ll get quite a bit of value out of it, and will be able to use the knowledge to save yourself lots of bugs in the future.