Skip to content

Instantly share code, notes, and snippets.

@maclunar
Created January 15, 2021 11:18
Show Gist options
  • Save maclunar/87a27536b7c7470dc076df7dd3cdf6f8 to your computer and use it in GitHub Desktop.
Save maclunar/87a27536b7c7470dc076df7dd3cdf6f8 to your computer and use it in GitHub Desktop.
Quickstart: Compose and Rails updated

This is an updated version of Quickstart: Compose and Rails from Docker docs. Updates are mostly about using Rails 6 and webpacker.

First, create a directory for the new app:

mkdir myapp; cd myapp

Fill in the Dockerfile:

FROM ruby:2.7
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client yarn
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

# 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

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

Create a bootstrap Gemfile:

source 'https://rubygems.org'
gem 'rails', '~>6'

Add an empty Gemfile.lock:

touch Gemfile.lock

Add entrypoint.sh script that clears up hanging pids:

#!/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 "$@"

Add docker-compose.yml:

version: "3.9"
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
  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

Build the rails app:

docker-compose run --no-deps web rails new . --force --database=postgresql

Change permissions of docker-generated files:

sudo chown -R $USER:$USER .

Build the image:

docker-compose build

Replace config/database.yml with:

default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password: password
  pool: 5

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

Install webpacker:

docker-compose run web rails webpacker:install

Create database

docker-compose run web rake db:create

And you should be able to start the container now with:

docker-compose up

The app should be available at localhost:3000.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment