First step, add Dockerfile:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
FROM ruby:2.6.3
RUN apt-get update -qq && apt-get install -y nodejs npm postgresql-client
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
COPY yarn.lock /myapp/yarn.lock
RUN gem update --system
RUN gem install bundler -v 2.0.1
RUN bundle install
RUN npm install -g yarn
COPY . /myapp
RUN yarn install --check-file

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

entrypoint.sh:

1
2
3
4
5
6
7
8
#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

Then add docker-compose:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
version: '3'
services:
db:
image: postgres
volumes:
- ./tmp/db:/var/lib/postgresql/data
web:
build: .
command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
volumes:
- .:/myapp
ports:
- "3000:3000"
depends_on:
- db
environment:
RAILS_ENV: development
APP_DATABASE_HOSTNAME: db

database.yml:

1
2
3
4
5
6
7
8
default: &default
encoding: unicode

# Host need to be set to work correctly with Docker
host: <%= ENV['APP_DATABASE_HOSTNAME'] || 'localhost' %>
username: postgres
password: password
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  • Username and password are required for Docker
  • With this setup it’s possible to run app with and without Docker

config/environments/development.rb:

1
2
# https://github.com/rails/webpacker/issues/1568
config.webpacker.check_yarn_integrity = false

That’s all configuration. Now a few useful commands:

Build & run containers

1
2
docker-compose build
docker-compose up

Run containers with build (flag is necessary when changes to Gemfile or Dockerfiles has been made)

1
docker-compose up --build

Shutdown containers:

1
docker-compose down

Run Rails console:

1
docker-compose run web bundle exec rails console

Run bash:

1
docker-compose run web bash

Run only pg container:

1
docker-compose run db

Check all running containers:

1
docker ps