Docker, Rails and passing configuration via environment variables.

Docker has a really nice option to pass configuration variables to the inside of the container. Sadly it’s only available to the user that the container runs with.

Problems are starting when you want to su - user and do something which requires use of passed environment variables which are not there after executing su - command.

One solution to this is to use a entrypoint wrapper script which before starting anything else will execute


env > /etc/.docker_env

At this point we have all variables saved in a file and we’re able to source them when starting new shell. This is only a part of the complete solution as we would need to have all those variables available also inside our Rails app.

Digging a bit in Rails initialization process led me to config/boot.rb which is used to set ENV['BUNDLE_GEMFILE'] a variable defining location path of Gemfile. We can also use this file to import all environment variables from .docker_env file.

Simple:


require 'dotenv'
Dotenv.load('/etc/.docker_env')

does the trick and next time when we need to run any rails task we don’t have to worry about sourcing proper environment.

Docker, Rails and passing configuration via environment variables.