LoginSignup
6
6

More than 3 years have passed since last update.

Windows10 + heroku + github + Ruby on Rails 事始め①(2020/02版)

Last updated at Posted at 2020-02-02

概要

Ruby on Railsプロジェクトを作成して、githubにあげて、heroku にデプロイします。

使用言語・フレームワーク

  • Ruby 2.6.5
  • Rails 5.2.3

使用サービス・ツール

  • github (git for windows)
  • heroku (heroku CLI)
  • Visual Studo Code

作業手順

作業用ディレクトリ作成

適当なパスにワークディレクトリ(作業用ディレクトリ)を作成します。
空白・2バイト文字等は使用しないで下さい。

アカウント作成

以下サービスのアカウントを作成します。

  • github
  • heroku

git アカウント設定

git インストール

以下を参考に、GitをWindowsにインストールします。

git bash 起動

スタートメニュー > Git > Git Bash を起動します。

image.png

ワークディレクトリに移動します。

config設定

gitアカウントを設定します。

$ git config --global user.name <gitアカウント名>
$ git config --global user.email <gitアカウントメールアドレス>

catコマンドで設定を確認します。

$ cat ~/.gitconfig
[user]
        name = <githubアカウント名>
        email = <githubアカウントメールアドレス>

SSH接続設定

github に SSHで接続するための設定を行います。

.ssh ディレクトリをワークディレクトリに作成し、その中に移動します。

$ mkdir .ssh
$ cd .ssh

githubメールアドレスをコメントとして、SSH公開鍵を生成します。

$ ssh-keygen -t rsa -b 4096 -C <githubアカウントメールアドレス>

鍵の生成先を確認されるので、ワークディレクトリ以下に作成します。

Generating public/private rsa key pair.
Enter file in which to save the key (/<ユーザディレクトリ>/.ssh/id_rsa): ./id_rsa

パスフレーズを設定します。

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

公開鍵が生成されます。

Your identification has been saved in ./id_rsa.
Your public key has been saved in ./id_rsa.pub.
The key fingerprint is:
<フィンガープリント> <githubアカウントメールアドレス>
The key's randomart image is:
+---[RSA 4096]----+
(略)
+----[SHA256]-----+

生成結果を確認します。

$ ls -la
total 8
drwxr-xr-x 1 <アカウント> 197121    0 1月  31 17:37 ./
drwxr-xr-x 1 <アカウント> 197121    0 1月  31 17:35 ../
-rw-r--r-- 1 <アカウント> 197121 3326 1月  31 17:37 id_rsa
-rw-r--r-- 1 <アカウント> 197121  751 1月  31 17:37 id_rsa.pub

githubアカウントとSSH鍵を紐付ける

image.png

githubのアイコンから Settingsを選択します。

image.png

Settings メニューから SSH and GPG keys を選択し、SSH keysの「New SSH key」を選択します。

一旦、git bash に戻って、キーをクリップボードにコピーします。

$ clip < ./id_rsa.pub

Key欄にペーストします。
Titleは任意のキー名(半角英数がよいでしょう)を設定します。

image.png

「Add SSH Key」をクリックするとパスワードを求められるので入力確認します。

image.png

登録が完了すると、キー名とフィンガープリントが表示されます。

image.png

git bash から SSH で github に接続する

一旦 .sshディレクトリからワークディレクトリのルートに戻ります。

$ cd ../

github に SSH接続します。
SSH鍵を<ユーザディレクトリ>以外で作成した場合、-iオプションで鍵のパスを指定する必要があります。
SSH鍵のパスフレーズを求められるので、入力し、Enterでログインします。

$ ssh -T git@github.com -i ./.ssh/id_rsa
Enter passphrase for key './.ssh/id_rsa': <パスフレーズ>
Hi miu200521358! You've successfully authenticated, but GitHub does not provide shell access.

参考:Testing your SSH connection

github接続用のconfigファイルを作成し、ユーザディレクトリ>.sshディレクトリ配下に配置します。

$ cat ~/.ssh/config
Host github
  HostName github.com
  IdentityFile <ワークディレクトリ>/.ssh/id_rsa
  User git

host名でのSSH接続を確認します。

$ ssh -T github
Enter passphrase for key '<ワークディレクトリ>/.ssh/id_rsa':
Hi miu200521358! You've successfully authenticated, but GitHub does not provide shell access.

heroku CLI のインストール

heroku にデプロイ等を行うために、CLIをインストールします。

image.png

CLIのインストールexeをDLできたら、起動します。
インストール内容すべてにチェックが入っている事を確認して、「Next」をクリックします。

image.png

インストール先を指定(デフォルトで Program Files の下)して、「Install」をクリックします。

image.png

git bash で heroku コマンドを確認します。

$ heroku -v
heroku/7.37.0 win32-x64 node-v12.13.0

heroku にログインします

$ heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/a0611f64-184e-465d-8f88-12e96b1004d7
heroku: Waiting for login...

image.png

image.png

ログインが完了しても、コンソールに何も出ないので、exitで終了します。

Ruby のインストール

RubyInstaller を使って、コンパイル済みの ruby をインストールします。

image.png

image.png

image.png

image.png

image.png

コマンドプロンプトが現れたら、3を選択してインストールを続行します。

image.png

Ruby on Rails のインストール

git bash を再起動し、ワークディレクトリに移動します。
Rubyのインストールが成功していることを確認します。

$ ruby -v
ruby 2.6.5p114 (2019-10-01 revision 67812) [x64-mingw32]

Railsのインストールコマンドを実行します。

$ gem install rails -v "5.2.3"
Successfully installed rails-5.2.3
Parsing documentation for rails-5.2.3
Done installing documentation for rails after 0 seconds
1 gem installed

インストール結果を確認します。

$ rails -v
Rails 5.2.3

sqlite3 のインストール

RoRのデフォルトDBはsqlite3なので、とりあえずインストールしてしまいます。

$ gem install sqlite3
Temporarily enhancing PATH for MSYS/MINGW...
Installing required msys2 packages: mingw-w64-x86_64-sqlite3
Building native extensions. This could take a while...
Successfully installed sqlite3-1.4.2
Parsing documentation for sqlite3-1.4.2
Installing ri documentation for sqlite3-1.4.2
Done installing documentation for sqlite3 after 1 seconds
1 gem installed

実際にsqlite3は触らないので、exe等のインストールはスキップします。

bundle のインストール

rbenv を使うと一緒にインストールされるが、生のrubyをそのまま入れたため、別途インストールします。

<ワークディレクトリ>/ror-sample (master)
$ gem install bundler
Successfully installed bundler-2.1.4
Parsing documentation for bundler-2.1.4
Installing ri documentation for bundler-2.1.4
Done installing documentation for bundler after 12 seconds
1 gem installed

<ワークディレクトリ>/ror-sample (master)
$ bundle -v
Bundler version 1.17.2

サンプルアプリの作成

RoRアプリが扱えることを確認するため、サンプルアプリを作成します。
後ほどgithubに登録します。

$ rails new ror-sample
      create
      create  README.md
      create  Rakefile
      create  .ruby-version
      create  config.ru
      create  .gitignore
      create  Gemfile
         run  git init from "."
Initialized empty Git repository in D:/Project/20200201_heroku_ror/ror-sample/.git/
      create  package.json
      create  app
()
         run  bundle install
Fetching gem metadata from https://rubygems.org/.............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies.....
Using rake 13.0.1
()
Bundle complete! 16 Gemfile dependencies, 76 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.

Railsサーバーを起動します。
※これは git bashではなく、コマンドプロンプトで実行すること。

D:\Project\20200201_heroku_ror>cd ror-sample

D:\Project\20200201_heroku_ror\ror-sample>rails server
=> Booting Puma
=> Rails 5.2.4.1 application starting in development
=> Run `rails server -h` for more startup options
*** SIGUSR2 not implemented, signal based restart unavailable!
*** SIGUSR1 not implemented, signal based restart unavailable!
*** SIGHUP not implemented, signal based logs reopening unavailable!
Puma starting in single mode...
* Version 3.12.2 (ruby 2.6.5-p114), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

localhost サーバーにアクセスします。

http://localhost:3000/
Started GET "/" for ::1 at 2020-02-01 11:40:38 +0900
Processing by Rails::WelcomeController#index as HTML
  Rendering C:/Development/Ruby26-x64/lib/ruby/gems/2.6.0/gems/railties-5.2.4.1/lib/rails/templates/rails/welcome/index.html.erb
  Rendered C:/Development/Ruby26-x64/lib/ruby/gems/2.6.0/gems/railties-5.2.4.1/lib/rails/templates/rails/welcome/index.html.erb (7.0ms)
Completed 200 OK in 49ms (Views: 33.1ms | ActiveRecord: 0.0ms)

image.png

とりあえずここまで出来たらOKです。
Ctrl+C でRailsサーバーを止めます。

- Gracefully stopping, waiting for requests to finish
=== puma shutdown: 2020-02-01 11:40:45 +0900 ===
- Goodbye!
Exiting
バッチ ジョブを終了しますか (Y/N)? y

D:\Project\20200201_heroku_ror\ror-sample>

github に登録

githubにリポジトリを作成します。

image.png

git bash でpushします。

先ほど作成したサンプルアプリの下に入ります。

<ワークディレクトリ>
$ cd ror-sample/

add して、全ファイルを登録対象とします。

<ワークディレクトリ>/ror-sample (master)
$ git add -A
warning: LF will be replaced by CRLF in .gitignore.
The file will have its original line endings in your working directory.
()

コメントを入れて、commitします。

<ワークディレクトリ>/ror-sample (master)
$ git commit -m "first commit"
[master (root-commit) 3ff8be7] first commit
 78 files changed, 1215 insertions(+)
 create mode 100644 .gitignore
()

ローカルのアプリディレクトリとgithubのリポジトリを紐付けます。

<ワークディレクトリ>/ror-sample (master)
$ git remote add origin github:miu200521358/ror-sample.git

リポジトリにpushします。

<ワークディレクトリ>/ror-sample (master)
$ git push -u origin master
Enter passphrase for key '/d/Project/20200201_heroku_ror/.ssh/id_rsa':
Counting objects: 85, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (70/70), done.
Writing objects: 100% (85/85), 20.96 KiB | 499.00 KiB/s, done.
Total 85 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), done.
To github:miu200521358/ror-sample.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

ひとまずこれでgithubに登録できました。

image.png

herokuへデプロイ

git bash から heroku CLI を通じて、herokuにデプロイを行います。

まず、herokuアプリを作成します。
アプリ名はそのままURLとなるため、他のユーザーやアプリと被らない名前を指定して下さい。

$ heroku create miu200521358-ror-sample
Creating miu200521358-ror-sample... done
https://miu200521358-ror-sample.herokuapp.com/ | https://git.heroku.com/miu200521358-ror-sample.git

アプリの作成が完了すると、herokuのダッシュボードにアプリが追加されます。

image.png

Railsの設定変更

heroku にデプロイする前に、RoRの設定を変更しておきます。
これは、IDEもしくはテキストエディタで修正して下さい。

/Gemfile

  • sqlite3 を開発環境・テスト環境に限定する(sqlite3をコメントアウト)
  • postgresql をリリース環境に設定する(pg をリリース用に追記)

image.png

image.png

参考: Gemfileの設定

設定の変更が終わったら、一旦インストールします。
これは、コードのルートディレクトリで実行してください。
(今回の場合、<ワークディレクトリ>/ror-sampleになります)

$ bundle install --without production

config/datebase.yml

image.png

参考: config/datebase.ymlの設定

設定変更が完了したら、github へ commit → push します。

$ git add -A
$ git commit -m "config postgresql"
$ git push

image.png

github から heroku へデプロイ

git bash を通じて、github から heroku へデプロイします。

$ git push heroku master
Counting objects: 91, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (76/76), done.
()
remote: -----> Discovering process types
remote:        Procfile declares types     -> (none)
remote:        Default types for buildpack -> console, rake, web
remote:
remote: -----> Compressing...
remote:        Done: 47.9M
remote: -----> Launching...
remote:        Released v6
remote:        https://miu200521358-ror-sample.herokuapp.com/ deployed to Herok
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/miu200521358-ror-sample.git
 * [new branch]      master -> master

deploy が完了すると、herokuのダッシュボードにも表示されます。

image.png

DBのマイグレーション(作成)

$ heroku run rails db:migrate
Running rails db:migrate on miu200521358-ror-sample... starting, run.2971 (Free)
Running rails db:migrate on miu200521358-ror-sample... connecting, run.2971 (Free)
Running rails db:migrate on miu200521358-ror-sample... up, run.2971 (Free)
D, [2020-02-01T04:16:25.695959 #4] DEBUG -- :    (19.0ms)  CREATE TABLE "schema_migrations" ("version" character varying NOT NULL PRIMARY KEY)
D, [2020-02-01T04:16:25.711056 #4] DEBUG -- :    (12.0ms)  CREATE TABLE "ar_internal_metadata" ("key" character varying NOT NULL PRIMARY KEY, "value" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
D, [2020-02-01T04:16:25.713087 #4] DEBUG -- :    (0.9ms)  SELECT pg_try_advisory_lock(217714722442632450)
D, [2020-02-01T04:16:25.730358 #4] DEBUG -- :    (1.3ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
D, [2020-02-01T04:16:25.739049 #4] DEBUG -- :   ActiveRecord::InternalMetadata Load (1.0ms)  SELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]]
D, [2020-02-01T04:16:25.746421 #4] DEBUG -- :    (0.9ms)  BEGIN
D, [2020-02-01T04:16:25.748508 #4] DEBUG -- :   ActiveRecord::InternalMetadata Create (1.1ms)  INSERT INTO "ar_internal_metadata" ("key", "value", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "key"  [["key", "environment"], ["value", "production"], ["created_at", "2020-02-01 04:16:25.746822"], ["updated_at", "2020-02-01 04:16:25.746822"]]
D, [2020-02-01T04:16:25.750384 #4] DEBUG -- :    (1.6ms)  COMMIT
D, [2020-02-01T04:16:25.751404 #4] DEBUG -- :    (0.8ms)  SELECT pg_advisory_unlock(217714722442632450)

ひとまず500エラーページを表示してみます。

image.png

これで、デプロイまで出来るようになりました。
次は、htmlページを実際に作って、デプロイしてみようと思います。

Windows10 + heroku + github + Ruby on Rails 事始め②(2020/02版)

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6