Rails & MySQL on Docker: Quick Start

This is a MySQL version of “Quickstart: Compose and Rails”. You can create a new Ruby on Rails project with MySQL (instead of PostgreSQL) using docker-compose.

0. setup

Create a directory (with any name) for the project.

mkdir rails
cd rails

1. prepare five files

Only docker-compose.yml is different from the original Quickstart documentation.

Dockerfile

FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
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"]

Gemfile

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

Gemfile.lock

(empty file)

entrypoint.sh

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

docker-compose.yml

version: '3'
services:
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: root
    ports:
      - "3306:3306"
  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

Instead of PostgreSQL, the db service uses MySQL image with password and database name env vars.

2. generate skeleton app

Make sure to use mysql

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

“If you are running Docker on Linux, the files rails new created are owned by root.” Run the following to change the owner.

sudo chown -R $USER:$USER .

3. build image again

docker-compose build

4. adjust database config

“Replace the contents of config/database.yml with the following:”

default: &default
  adapter: mysql2
  encoding: utf8mb4
  host: db
  username: root
  password: password
  pool: 5

development:
  <<: *default
  database: myapp_development


test:
  <<: *default
  database: myapp_test

The difference from the original doc are:

  • adapter: postgresql -> mysql2
  • encoding: unicode -> utf8mb4
  • username: postgres -> root

5. run

docker-compose up

6. create database

“In another terminal, run:”

docker-compose run web rake db:create

7. check result

Access http://localhost:3000 to see the Rails Welcome page.

Comments

Popular posts from this blog

Selenide: Quick Start

Minikube Installation for M1 Mac

Server Testing Tools: Serverspec, InSpec, Testinfra, Goss