Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure database.yml to work in a local environment and in Docker both?

Let's say some of my Rails colleagues would prefer to develop the app inside their own native local development environment they've setup all by themselves to match their needs, and some of my colleagues would prefer to develop the app run from inside a Docker container that comes along with all necessary tools preinstalled.

Now there's the config/database.yml which currently looks like following to match the setup of all the native folks and which is started with bin/rails db:setup.

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

But the Docker folks instead do need the following – most important of all a different host – and it would be started with docker-compose run web bin/rails db:setup. As the host is different now this database.yml wouldn't work anymore for the native folks.

default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password:
  pool: 5

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

What would be the most convenient or less intrusive way to cover both use cases at once? Can I fetch the host value dynamically? How? From an env variable? From a different database.yml? How to then tell Rails to take this one instead?

Note: The Docker setup basically follows https://docs.docker.com/compose/rails

like image 806
leymannx Avatar asked Feb 28 '18 20:02

leymannx


People also ask

How do I pass an environment variable in Docker run?

Using –env, -e When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.


1 Answers

Use the ENV vars Luke.

ENV['DATABASE_URL'] is merged with the settings from database.yml and takes precedence over the values from file.

To avoid developer wars database.yml should only contain the bare minimum of settings such as the adapter, encoding and the default names of the DBs:

default: &default
  adapter: postgresql
  encoding: unicode

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

Anything else such as hosts, passwords should be set by ENV['DATABASE_URL'] as this is local configuration - not application configuration. This also is preferable for security reasons as it removes the risk of passwords being leaked with the source code.

See:

  • http://guides.rubyonrails.org/configuring.html#configuring-a-database
  • https://12factor.net/config
like image 56
max Avatar answered Oct 21 '22 01:10

max