9

I have a Rails app. In the development and test environments, I want the Rails app to connect to a dockerized Postgres. The Rails app itself will not be in a container though - just Postgres.

What should my database.yml look like?

I have a docker default machine running. I created docker-compose.yml:

postgres:
  image: postgres
  ports:
    - "5432:5432"
  environment:
    - POSTGRES_USER=timbuktu
    - POSTGRES_PASSWORD=mysecretpassword

I ran docker-compose up to get Postgres running.

Then I ran docker-machine ip default to get the IP address of the Docker virtual machine, and I updated database.yml accordingly:

...
development: 
  adapter: postgresql
  host: 192.168.99.100
  port: 5432
  database: timbuktu_development
  username: timbuktu
  password: mysecretpassword
  encoding: unicode
  pool: 5
...

So all is well and I can connect to Postgres in its container.

But, if someone else pulls the repo, they won't be able to connect to Postgres using my database.yml, because the IP address of their Docker default machine will be different from mine.

So how can I change my database.yml to account for this?

One idea I have is to ask them to get the IP address of their Docker default machine by running docker-machine env default, and pasting the env DOCKER_HOST line into their bash_rc. For example,

export DOCKER_HOST="tcp://192.168.99.100:2376"

Then my database.yml host can include the line

host: <%= ENV['DOCKER_HOST'].match(/tcp:\/\/(.+):\d{3,}/)[1] %>

But this feels ugly and hacky. Is there a better way?

Sandy
  • 223
  • 3
  • 9

2 Answers2

3

You could set a correct environment variable first, and access it from your database.yml:

host: <%= ENV['POSTGRES_IP'] %>

With a bashrc like (using bash substring removal):

export DOCKER_HOST=$(docker-machine env default)
export POSTGRES_IP=${DOCKER_HOST#tcp://}
Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
3

I found a simpler way:

host: <%= `docker-machine ip default` %>
Sandy
  • 223
  • 3
  • 9
  • 1
    That should work too, I just prefer separating the config value (environment variable) from *how* that value is acquired/set. Still, +1. – VonC Oct 11 '15 at 17:41
  • or `host: <%= ENV['POSTGRES_IP'] || \`docker-machine ip default\`%>` – sites Sep 29 '16 at 15:40