Docker with Rails
In this tutorial, learn how to integrate Dotenv Vault with Docker and a Rails application.
You can find a complete example repo here.
Dockerfile
Create your Dockerfile in your rails application
# Dockerfile
FROM ruby:2.7.4
RUN apt-get update && apt-get install -y nodejs
WORKDIR /app
COPY Gemfile* .
RUN bundle install
COPY . .
EXPOSE 3000
CMD ["rails", "server", "-b", "0.0.0.0"]
Here’s an example of a simple welcome index page that runs on docker.
// welcome/index.html.erb
<h1>Welcome <%= ENV["HELLO"] %></h1>
Install dotenv-vault
Create your local .env
file.
HELLO="Rails on docker"
Add dotenv-vault-rails gem to Gemfile
// Add 'dotenv-vault-rails' to Gemfile
gem 'dotenv-vault-rails'
Require dotenv-vault as early as possible in your Rails application. For a Rails application require dotenv-vault/load in application.rb
// config/application.rb
require 'dotenv-vault/load'
Build your rails application via docker by running
docker build -t demo .
Test that it is working locally.
$ docker run -p 3000:3000 demo
It says Hello Rails on docker at http://localhost:3000.
Build .env.vault
First set a production value for when we deploy. I set it to HELLO=Production. Run dotenv-vault open to edit production values.
$ npx dotenv-vault open production
Then build your localized encrypted .env.vault file.
$ npx dotenv-vault build
Great! Commit your .env.vault
file to code. It is safe to do so. It is a localized encrypted vault of your environment variables.
Set DOTENV_KEY
Lastly, set the DOTENV_KEY on the docker run command.
Run npx dotenv-vault keys production to get your production decryption key.
$ npx dotenv-vault keys production
remote: Listing .env.vault decryption keys... done
dotenv://:[email protected]/vault/.env.vault?environment=production
Set it for Docker run. The important part here is the -e
flag.
$ docker build -t demo . && docker run -e DOTENV_KEY="dotenv://:[email protected]/vault/.env.vault?environment=production" -p 3000:3000 --init demo
That’s it!
Commit your changes to code and deploy your Docker image to your infrastructure.
When Docker runs, it will recognize the DOTENV_KEY
, decrypt the .env.vault file, and load the production environment variables inside of Docker. If a DOTENV_KEY
is not set (like during development on your local machine) it will fall back to regular dotenv.
It worked if you see the message ‘Loading env from encrypted .env.vault’.