Rails with Docker-compose: how to set up database host Rails with Docker-compose: how to set up database host docker docker

Rails with Docker-compose: how to set up database host


Here is the solution I came to.

  1. Create a Dockerfile as follows in the Rails app:

F

FROM ruby:2.5.1LABEL maintainer="Serguei CAMBOUR <s.cambour@gmail.com>"RUN apt-get update -yqqRUN apt-get install -yqq --no-install-recommends nodejsCOPY Gemfile* /usr/src/app/WORKDIR /usr/src/appRUN bundle installCOPY . /usr/src/app/CMD ["rails", "s", "-b", "0.0.0.0"]
  1. Create docker-compose.yml as follows:

v

version: '3'services:  web:    build: .    ports:      - "3000:3000"    volumes:      - .:/usr/src/app    env_file:      - .env/development/database      - .env/development/web  redis:    image: redis  database:    image: postgres    env_file:      - .env/development/database    volumes:      - db-data:/var/lib/postgresql/datavolumes:  db-data:
  1. Create .env/development/database file as follows:

P

POSTGRES_USER=postgresPOSTGRES_DB=myapp_development
  1. Create .env/development/web file as follows:

DATABASE_HOST=database

  1. Change the settings in database.yml as follows to be able to read env variable values:

d

default: &default  adapter: postgresql  encoding: unicode  host: <%= ENV['DATABASE_HOST'] %>  username: <%= ENV['POSTGRES_USER'] %>  database: <%= ENV['POSTGRES_DB'] %>  pool: 5  variables:    statement_timeout: 5000development:  <<: *defaulttest:  <<: *default  database: myapp_testproduction:  <<: *default

Now, you can run your rails app as usual with rails s and it will work. The same is for running all the Rails generators, migrations etc, - it will work and communicate with your Postgresql DB in local.

To run your code in a docker container:

  1. Run docker-compose build web (where web is the name of my service declared in docker-compose.yml before).
  2. Or just start and build it with docker-compose up --build.
  3. Navigate to one of your routes to check if it works.
  4. Create the database if it does not exist yet: docker-compose run --rm web rails db:create.
  5. Run some pending migrations if there are some: docker-compose exec web rails db:migrate.
  6. You can combine the both: docker-compose exec web rails db:create db:migrate.

Hope this helps.