Pass environment variables from docker to my GoLang.

Felipe Dutra Tine e Silva
1 min readJan 4, 2017

--

I don’t want to have my sensitive information in a config file.

I don’t want that my program know the connection string to the database.

If I want to change the connection string without altering my program, it should be possible.

So I will pass them throught the env variable in docker.

Passing variables to Docker

There are 2ways to pass variables environment to docker. There are all documented : https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables--e---env---env-file

  • using the option -e
$ sudo docker run  [...] -e my_connection_string="xxxxx" -e my_password="xxx" [...]
  • using env-file docker option.

So first you should create a file .list using, for each line, the format :

KEY_NAME=VALUE

exemple :

my_connection_string=xxxxxx
my_password=yyyyyyyy
my_secret=zzzzz

And giving this information to docker :

$ sudo docker run [...] --env-file ./my_env.list [...]

GET the variables in GoLang

All the variables pass to docker, will be found in os.Getenv(“{Key}”)

Try in a golang console app dockerize :

fmt.Println('Hello ' + os.Getenv("NAME"))

And of course pass to docker :

$ sudo docker run [...] -e NAME="Felipe"

You will get

$ Hello Felipe

--

--