Dockerでrails api×react×MySQLの開発環境を構築する
1. 各種ファイルの準備
ディレクトリ構成
rails_react
├── api/
│ ├── Dockerfile
│ ├── entrypoint.sh
│ ├── Gemfile
│ └── Gemfile.lock
├── front/
│ └── Dockerfile
└── docker-compose.yml
docker-compose.yml
version: "3"
services:
api:
build:
context: ./api/
dockerfile: Dockerfile
ports:
- "3333:3333"
volumes:
- ./api:/var/www/api
- gem_data:/usr/local/bundle
command: /bin/sh -c "rm -f /var/www/api/tmp/pids/server.pid && bundle exec rails s -p 3333 -b '0.0.0.0'"
my-database:
image: mysql:5.7
environment:
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
phpmyadmin:
image: phpmyadmin
ports:
- "1080:80"
environment:
- PMA_ARBITRARY=1
- PMA_HOST=my-database
- PMA_USER=root
front:
build:
context: ./front/
dockerfile: Dockerfile
volumes:
- ./front:/var/www/front
command: sh -c "cd react-app && yarn start"
ports:
- "3000:3000"
volumes:
gem_data:
api/Dockerfile
FROM ruby:2.7.1
ARG WORKDIR=/var/www/api
# デフォルトの locale `C` を `C.UTF-8` に変更する
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
# タイムゾーンを日本時間に変更
ENV TZ Asia/Tokyo
RUN apt-get update && apt-get install -y nodejs npm mariadb-client
RUN npm install -g yarn@1
RUN mkdir -p $WORKDIR
WORKDIR $WORKDIR
COPY Gemfile $WORKDIR/Gemfile
COPY Gemfile.lock $WORKDIR/Gemfile.lock
RUN bundle install
# 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 3333
# Start the main process
CMD ["rails", "server", "-p", "3333", "-b", "0.0.0.0"]
api/Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.7.1'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3', '>= 6.0.3.6'
api/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 "$@"
front/Dockerfile
FROM node:12.18.2-alpine
ARG WORKDIR=/var/www/front
RUN mkdir -p $WORKDIR
WORKDIR $WORKDIR
2. コマンド実行
$ docker-compose run api rails new . --force --no-deps --database=mysql --api
$ docker-compose build
$ docker-compose run --rm front sh -c "npm install -g create-react-app && create-react-app react-app"
api/config/database.ymlの書き換え
default: &default
adapter: mysql2
encoding: utf8mb4
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password:
host: my-database
development:
<<: *default
database: api_development
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: api_test
$ docker-compose up -d
$ docker-compose run api rake db:create
以上で環境構築完了