Rails with Docker-compose: how to set up database host
Here is the solution I came to.
- 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"]
- 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:
- Create
.env/development/database
file as follows:
P
POSTGRES_USER=postgresPOSTGRES_DB=myapp_development
- Create
.env/development/web
file as follows:
DATABASE_HOST=database
- 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:
- Run
docker-compose build web
(whereweb
is the name of my service declared indocker-compose.yml
before). - Or just start and build it with
docker-compose up --build
. - Navigate to one of your routes to check if it works.
- Create the database if it does not exist yet:
docker-compose run --rm web rails db:create
. - Run some pending migrations if there are some:
docker-compose exec web rails db:migrate
. - You can combine the both:
docker-compose exec web rails db:create db:migrate
.
Hope this helps.