Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup database.yml to connect to Postgres Docker container?

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?

like image 381
Sandy Avatar asked Oct 11 '15 04:10

Sandy


People also ask

How do I connect to a docker container database?

First, we have to install Docker Desktop. Then, we should find an existing image of our database from the Docker Hub. Once we find it, we'll pick the docker pull command from the top right corner of the page. Next, we'll test our database container connection.


2 Answers

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://}
like image 134
VonC Avatar answered Oct 19 '22 09:10

VonC


I found a simpler way:

host: <%= `docker-machine ip default` %>
like image 22
Sandy Avatar answered Oct 19 '22 08:10

Sandy