Docker + Rails + React
Docker + Rails + React
streampack의 minsu입니다.
올해의 여름은 주로 실내에서 보내고 있었습니다만, 요전날 귀성한 때에 중고의 카메라를 손에 넣었으므로 앞으로는 아웃도어인 취미로서 산책 카메라를 섬세하고 싶다고 생각하고 있습니다. 시원해지면 아마
 목적
전면: React
뒤: Rails
Docker를 사용하여 빌드합니다.
React + Rails 입니다만 webpacker 를 이용하는 방법으로 실시합니다.
 파일 준비
먼저 Gemfile, Gemfile.lock, Dockerfile 및 dcocker-compose.yml를 준비합니다.
Gemfilesource 'https://rubygems.org'
gem 'rails', '5.1.4'
DockerfileFROM ruby:2.4.1
RUN apt-get update -qq && apt-get install -y mysql-client build-essential nodejs apt-transport-https
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 && apt-get install -y yarn
RUN mkdir /app
WORKDIR /app
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install
COPY . /app
docker-compose.ymlversion: '3'
services:
  app:
    build: . 
    command: /bin/sh -c "rm -f /app/tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    depends_on:
      - db
  db:
    image: mysql:5.7
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    environment:
      - MYSQL_ROOT_PASSWORD=root
    volumes:
      - mysql_vol:/var/lib/mysql
volumes:
  mysql_vol:
pid는 개발 웹 서버를 시작할 때 tmp/pids/server.pid에 기록되고 종료 될 때 삭제되지만, 어떤 요인으로 삭제되지 않고 종료하면 시작 중이라고 판단됩니다. 새 서버를 시작할 수 없으므로 rm -f /app/tmp/pids/server.pid 시작시 삭제합니다.
 rails new
컨테이너에서 rails 프로젝트를 만듭니다.
Gemfile은 덮어쓰고 DB는 MySQL을 지정합니다.
$ docker-compose run app rails new . --force --database=mysql
docker-compose.yml 의 mysql 의 root 패스워드를 MYSQL_ROOT_PASSWORD=root (으)로 설정했으므로 config/database.yml 의 development 에 설정을 추가했습니다.
host도 지정한 db로 변경합니다.
config/database.ymlusername: root
password: root
host: db
Gemfile
gem 'webpacker'
gem 'react-rails'
추가하고 bundle install 다시 한 번
$ docker-compose build
다음 명령을 실행합니다.
$ docker-compose run app rails webpacker:install
$ docker-compose run app rails webpacker:install:react
$ docker-compose run app rails generate react:install
위의 2행은 rails new 의 타이밍으로 --webpack=react 의 옵션을 추가해도 좋았던 것 같습니다.
package.json 업데이트 및app/javascript/packs/ 아래에 application.js 및 hello_react.jsx가 생성됩니다.
 db, model 작성
적절한 모델과 seeds 데이터를 준비하고 DB를 만든 후에 데이터를 넣습니다.
$ docker-compose run app rails g model List title:string desc:string
db/seeds.rb
5.times do
  List.create(
    title: 'title_' + SecureRandom.hex(4),
    desc: 'desc_' + SecureRandom.hex(4)
  )
end
$ docker-compose run app rails db:create
$ docker-compose run app rails db:migrate
작성한 모델을 나열해 보겠습니다.
controller, view 만들기
$ docker-compose run app rails g controller Lists index
lists_controller.rb  def index
    @lists = List.all
  end
view 에서는 javascript_pack_tag 와 react_component 의 태그를 사용해 js 를 호출합니다.
lists/index.html.erb<%= javascript_pack_tag 'application' %>
<h1>Lists#index</h1>
<%= react_component 'Lists', lists: @lists %>
 react component 작성
순서가 전후했습니다만, view 로 호출하고 있는 components 를 구현합니다.
$ rails g react:component Lists
의 명령으로 app/javascript/components/Lists.js 가 작성되므로 편집합니다.
Lists.jsimport React from "react"
import PropTypes from "prop-types"
export default class Lists extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      lists: []
    };
  }
  componentDidMount(){
    this.setState({
      lists: this.props.lists
    })
  }
  render () {
    return (
      <div>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Title</th>
              <th>Description</th>
              <th>created_at</th>
              <th>updated_at</th>
            </tr>
          </thead>
          <tbody>
            {this.state.lists.map((list) => {
              return (
                <tr key={list.id}>
                  <td>{list.id}</td>
                  <td>{list.title}</td>
                  <td>{list.desc}</td>
                  <td>{list.created_at}</td>
                  <td>{list.updated_at}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}
 동작 확인
rails, webpack을 시작합니다.
$ docker-compose up -d
$ docker-compose run app bin/webpack-dev-server
http://localhost:3000/lists/index로 이동합니다.
 
안전하게 목록이 표시되었습니다.
 요약
기동과 표시 확인까지를 실시했습니다.
이 상태에서는 아무 기능도 없기 때문에 React 에서의 CRUD 조작을 구현할 때까지를 추기, 또는 새롭게 기사로 하고 싶습니다.
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여(Docker + Rails + React), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/minsu/items/0ccbafff460e72b13d44
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
source 'https://rubygems.org'
gem 'rails', '5.1.4'
FROM ruby:2.4.1
RUN apt-get update -qq && apt-get install -y mysql-client build-essential nodejs apt-transport-https
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 && apt-get install -y yarn
RUN mkdir /app
WORKDIR /app
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install
COPY . /app
version: '3'
services:
  app:
    build: . 
    command: /bin/sh -c "rm -f /app/tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    depends_on:
      - db
  db:
    image: mysql:5.7
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    environment:
      - MYSQL_ROOT_PASSWORD=root
    volumes:
      - mysql_vol:/var/lib/mysql
volumes:
  mysql_vol:
$ docker-compose run app rails new . --force --database=mysql
username: root
password: root
host: db
gem 'webpacker'
gem 'react-rails'
$ docker-compose build
$ docker-compose run app rails webpacker:install
$ docker-compose run app rails webpacker:install:react
$ docker-compose run app rails generate react:install
$ docker-compose run app rails g model List title:string desc:string
5.times do
  List.create(
    title: 'title_' + SecureRandom.hex(4),
    desc: 'desc_' + SecureRandom.hex(4)
  )
end
$ docker-compose run app rails db:create
$ docker-compose run app rails db:migrate
$ docker-compose run app rails g controller Lists index
  def index
    @lists = List.all
  end
<%= javascript_pack_tag 'application' %>
<h1>Lists#index</h1>
<%= react_component 'Lists', lists: @lists %>
$ rails g react:component Lists
import React from "react"
import PropTypes from "prop-types"
export default class Lists extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      lists: []
    };
  }
  componentDidMount(){
    this.setState({
      lists: this.props.lists
    })
  }
  render () {
    return (
      <div>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Title</th>
              <th>Description</th>
              <th>created_at</th>
              <th>updated_at</th>
            </tr>
          </thead>
          <tbody>
            {this.state.lists.map((list) => {
              return (
                <tr key={list.id}>
                  <td>{list.id}</td>
                  <td>{list.title}</td>
                  <td>{list.desc}</td>
                  <td>{list.created_at}</td>
                  <td>{list.updated_at}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}
$ docker-compose up -d
$ docker-compose run app bin/webpack-dev-server
Reference
이 문제에 관하여(Docker + Rails + React), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/minsu/items/0ccbafff460e72b13d44텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)