Docker Compose with Rails
In this tutorial, learn how to integrate Dotenv Vault with Docker Compose and a Rails application.
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"]
Create your docker-compose.yml
version: "3.9"
services:
db:
image: postgres
volumes:
- ./tmp/db:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: password
web:
build: .
command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
volumes:
- .:/demo
ports:
- "3000:3000"
depends_on:
- db
environment:
SECRET_KEY_BASE: 1
DOTENV_KEY: ${DOTENV_KEY}
RAILS_ENV: ${RAILS_ENV}
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 compose"
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 compose build
Test that it is working locally.
$ docker compose up
It says Hello Rails on docker compose 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.
$ RAILS_ENV=production DOTENV_KEY="dotenv://:[email protected]/vault/.env.vault?environment=production" docker compose up
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’.