自分だけのクイズ作成 - Quipha公開中
スポンサーリンク
スポンサーリンク

【Heroku】Laravel+MySQLで作成したアプリを公開【完全版】

Laravel
スポンサーリンク

はじめに

Herokuを使って、Laravelプロジェクトを公開する手順をまとめました。
個人で開発したアプリケーションを手軽に公開することができます。

Herokuの新規登録方法は、以下の記事にまとめました。

Djangoで作成したアプリもHerokuで公開できます。
詳しくは以下の記事をご覧ください。

使用するバージョンなど
  • Windows 11 / 10 or macOS Monterey (M1)
  • Git
  • Heroku
  • Laravel
  • MySQL

クライアントの作業は、WindowsでもMacでも同様にできます。

他にも私のブログで、Laravelについて解説している記事がありますのでご覧ください。

【紹介】個人開発

私の個人開発ですがQuiphaというサービスを開発しました。(Laravel, Vue3など)
良かったら、会員登録して動作を試してみて下さい。

また、Laravel 9 実践入門という書籍を出版しました。
Kindle Unlimitedを契約している方であれば、読み放題で無料でご覧いただくことができます

是非多くの方に読んでいただき、Laravelの開発に少しでもお役に立てたら幸いです。

2022/08/27 追記:無料プラン廃止について

Herokuは、以下の無料プランを廃止すると発表しました。

  • Heroku Dynos
  • Heroku Postgres
  • Heroku Data for Redis
PaaS「Heroku」が無料プラン廃止、11月から 非アクティブなアカウントとストレージも削除
米Salesforceの子会社である米Herokuは、同社が提供するPaaS「Heroku」の無料プランを廃止すると発表した。今後はサービスの運営上不可欠なミッションクリティカルな機能の提供にリソースを集中させると説明している。

プランにつきましては公式サイトをご確認ください。

Pricing | Heroku
Heroku offers simple, flexible pricing to meet the needs of every app and every organization. Add data stores, cloud services, support, and more.

Heroku CLIのインストール

WindowsとMacのそれぞれで、インストール方法を解説します。

Windows

Windowsで作業を行う場合ですが、今回はWSL2のUbuntuを使用しました。
導入は簡単にできますので、以下の記事を参考にしてください。

HerokuのCLIツールとして、Windowsのインストーラもあります。
インストール後、コマンドプロンプトやPowerShellで「heroku」コマンドが使用できるようになりますが、別途Gitのインストールも必要になります。

以下のページにアクセスします。

The Heroku CLI | Heroku Dev Center
How to download, install, and start using, the Heroku CLI. The Heroku CLI used to be part of the Heroku Toolbelt.

それぞれのOSごとにインストール方法が記載されています。
今回はWSL2のUbuntuにインストールしますが、以下のコマンドでした。

上記のページにあるUbuntuで「snap」コマンドを使用したインストールはうまくいきませんでした。

以降はWSL2のUbuntuからコマンドを実行していきます。

以下のコマンドを実行します。

$ curl https://cli-assets.heroku.com/install-ubuntu.sh | sh

インストールが完了しました。バージョンを確認しましょう。

$ heroku --version

heroku/7.59.2 linux-x64 node-v12.21.0

ついでにGitのバージョンも確認しましょう。
Ubuntuには最初からインストールされていました。

$ git --version

git version 2.25.1

Git は、ほとんどの Linux 用 Windows サブシステムのディストリビューションと一緒に既にインストールされていますが、最新バージョンに更新したほうがよい場合があります。 また、git 構成ファイルを設定する必要もあります。

https://docs.microsoft.com/ja-jp/windows/wsl/tutorials/wsl-git

最新のGitのバージョンは、現時点で2.34.1でした。
UbuntuにインストールされていたGitのバージョンがやや古いですが、必要に応じてアップデートすると良いでしょう。

これでHeroku CLIを使う準備ができました。

Mac

Macで作業を行うために、Heroku CLIをインストールします。

以下のページにアクセスします。

The Heroku CLI | Heroku Dev Center
How to download, install, and start using, the Heroku CLI. The Heroku CLI used to be part of the Heroku Toolbelt.

それぞれのOSごとにインストール方法が記載されています。

Homebrewをインストールしていない場合は、以下の記事を参考にしてください。

ターミナルを起動し、以下のコマンドを実行します。

% brew tap heroku/brew && brew install heroku

インストールが完了しました。バージョンを確認しましょう。

% heroku --version

heroku/7.60.1 darwin-x64 node-v14.19.0

Gitのインストールも行いましょう。
インストールされているかどうか、以下のコマンドを実行します。

% git --version

Gitがインストールされていない場合は、以下のダイアログが表示されますのでインストールを選択します。

“git”コマンドを実行するには、コマンドライン・デベロッパツールが必要です。ツールを今すぐインストールしますか?
コマンドライン・デベロッパツールを今すぐダウンロードしてインストールするには、”インストール”を選択してください。

規約を確認します。

完了しました。

インストール完了後、以下のコマンドでGitのバージョンが確認できます。

% git --version

git version 2.30.1 (Apple Git-130)

Git用のメールアドレスと名前を設定しておきましょう。

% git config --global user.email "you@example.com"
% git config --global user.name "Your Name"

Heroku CLIを使う準備ができました。

Laravelプロジェクトの用意

HerokuにデプロイするためのLaravelプロジェクトを作成します。
Laravel Sailを使って構築しますが、詳細は以下の記事をご覧ください。

Windows
Mac

任意のディレクトリを作成しましょう。
ホームディレクトリにプロジェクトフォルダを作成しました。

$ cd ~
$ mkdir Laravel-Project
$ cd Laravel-Project

任意のプロジェクト名でLaravelプロジェクトを作成します。

$ curl -s https://laravel.build/example-app-heroku | bash

Gitリポジトリを作成しコミットしましょう。

$ cd example-app-heroku
$ git init
$ git add .
$ git commit -m "new laravel project"

Herokuにデプロイ

Procfileファイルを作成

Procfileファイルを作成し、Laravelの公開ディレクトリの設定を行います。
Procfileもコミットします。

$ echo "web: vendor/bin/heroku-php-apache2 public/" > Procfile
$ git add .
$ git commit -m "Procfile for Heroku"

ログイン

Herokuへログインします。
q以外のキーを押すとブラウザが開きます。

$ heroku login

heroku: Press any key to open up the browser to login or q to exit:

ブラウザでログインページが開き、ログインを行うことができます。

「Log in」ボタンクリックでCLIの方でログインが完了します。

Logging in... done
Logged in as xxx@xxxx

アプリケーション作成

Herokuアプリケーションを作成します。

$ heroku create

Creating app... done, ⬢ xxx-xxx-xxxx
 https://xxx-xxx-xxxx.herokuapp.com/ | https://git.heroku.com/xxx-xxx-xxxx.git

「xxx-xxx-xxxx」の部分は、アプリケーション名でありランダムな名前が自動的に選択されました。

この時点でWebのダッシュボードを確認すると、作成されたアプリケーションが確認できます。

LaravelプロジェクトのAPP_KEYを設定します。
まずはキーを生成します。今回はSailを使用しますので起動します。

$ sail up -d
$ sail artisan key:generate --show

base64:xxxxx

生成されたキーを指定し、Herokuのconfigに設定します。

$ heroku config:set APP_KEY=base64:xxxxx

Laravelの設定ファイルは.envですが、Gitリポジトリの管理対象外となっています。(機密情報が含まれますので)
そのためHerokuのリポジトリへ.envをプッシュするのではなく、「heroku config」コマンドで各種Laravelの設定を行っていきます。

Webのダッシュボード上からConfigの値を確認することができます。

もちろんコマンドで確認することもできます。

$ heroku config

=== xxx-xxx-xxxx Config Vars
APP_KEY: base64:xxxxx

HerokuのGitリモートリポジトリにプッシュします。
リモート先を確認してみましょう。
heroku」というリモート先が追加されているのが分かります。

$ git remote -v

heroku  https://git.heroku.com/xxx-xxx-xxxx.git (fetch)
heroku  https://git.heroku.com/xxx-xxx-xxxx.git (push)

originと間違えないようにしましょう。

プッシュを行いデプロイします。

$ git push heroku master

プッシュ時に自動でPHPを認識してビルドされるようです。
composer installなどのコマンドを実行せずとも構築されるようです。

remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote: -----> Determining which buildpack to use for this app
remote:  !     Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used.
remote:                         Detected buildpacks: PHP,Node.js
remote:                         See https://devcenter.heroku.com/articles/buildpacks#buildpack-detect-order
remote: -----> PHP app detected
remote: -----> Bootstrapping...
remote: -----> Installing platform packages...
remote:        - php (8.1.1)
remote:        - ext-mbstring (bundled with php)
remote:        - composer (2.2.3)
remote:        - apache (2.4.51)
remote:        - nginx (1.20.2)
remote: -----> Installing dependencies...
remote:        Composer version 2.2.3 2021-12-31 12:18:53
remote:        Installing dependencies from lock file
remote:        Verifying lock file contents can be installed on current platform.
remote:        Package operations: 70 installs, 0 updates, 0 removals
remote:          - Downloading doctrine/inflector (2.0.4)
remote:          - Downloading doctrine/lexer (1.2.2)
...

それではデプロイされたサイトにアクセスしてみましょう。

$ heroku open

データベースの設定はしていませんが、とりあえずいつものLaravelの画面が表示されました。

ちなみにdynoコンテナ上のコマンドを実行する場合は、heroku runを使用します。

$ heroku run php -v

PHP 8.1.1 (cli) (built: Dec 17 2021 15:27:15) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies

他にも本番用のLaravelの設定をしておきましょう。

$ heroku config:set APP_ENV=production
$ heroku config:set APP_DEBUG=false
$ heroku config:set APP_URL=https://xxx-xxx-xxxx.herokuapp.com/

MySQLの設定

ClearDBアドオンを追加します。

ClearDB MySQL - Add-ons - Heroku Elements
The high speed database for your MySQL powered applications.

MySQLであり、5MBまでのストレージサイズや、接続数10までと制限はありますが、無料で使用することができます。

以下のコマンドで追加します。

$ heroku addons:add cleardb:ignite

Creating cleardb:ignite on ⬢ xxx-xxx-xxx... free
Created cleardb-concave-xxxx as CLEARDB_DATABASE_URL
Use heroku addons:docs cleardb to view documentation

アカウントにクレジットカードを登録し、アカウント認証を済ませる必要があります。

アカウント認証が済んでいない状態で、ClearDBを追加しようとすると以下のエラーが表示されます。

Creating cleardb:ignite on ⬢ xxx-xxx-xxx... !
 ▸    Please verify your account to install this add-on plan (please enter a
 ▸    credit card) For more information, see
 ▸    https://devcenter.heroku.com/categories/billing Verify now at
 ▸    https://heroku.com/verify

正常に追加されると、ダッシュボードからも確認できます。

MySQLの接続情報を確認しましょう。

$ heroku config

=== xxx-xxx-xxx Config Vars
APP_KEY:              base64:xxx
CLEARDB_DATABASE_URL: mysql://xxx:xxx@xxx/heroku_xxx?reconnect=true

CLEARDB_DATABASE_URLのフォーマットは以下のようになっています。

mysql://(DB_USERNAME):(DB_PASSWORD)@(DB_HOST)/(DB_DATABASE)?reconnect=true

herokuにデータベースの設定を追加します。(CLEARDB_DATABASE_URLの内容を設定)

$ heroku config:set DB_CONNECTION=mysql
$ heroku config:set DB_HOST=(DB_HOST)
$ heroku config:set DB_PORT=3306
$ heroku config:set DB_DATABASE=(DB_DATABASE)
$ heroku config:set DB_USERNAME=(DB_USERNAME)
$ heroku config:set DB_PASSWORD=(DB_PASSWORD)

Laravelのテーブルを作成しましょう。
APP_ENVをproductionに変更していたため確認メッセージが表示されますがyesで進めます。

$ heroku run php artisan migrate

Running php artisan migrate on ⬢ xxx-xxx-xxx... up, run.3610 (Free)
**************************************
*     Application In Production!     *
**************************************

 Do you really wish to run this command? (yes/no) [no]:
 >

以下のエラーが表示されました。

In Connection.php line 712:

  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))


In Connection.php line 501:

  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

これはLaravelとMySQLの問題ですので、以下のように修正します。

app\Providers\AppServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

修正したファイルをHerokuにプッシュしてデプロイしましょう。

$ git add .
$ git commit -m "Fix for MySQL"
$ git push heroku master

先程中途半端にテーブルが作られたため、再構築を行います。

$ heroku run php artisan migrate:fresh

今度は正常にテーブルが作成されました。

Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (59.87ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (63.82ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (68.19ms)
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated:  2019_12_14_000001_create_personal_access_tokens_table (88.77ms)

MySQLのデータベース確認

MySQLのデータの確認方法につきましては、以下の記事にまとめましたので参考にしてください。

スポンサーリンク

ログの出力

Laravelのログの内容を、Herokuに出力できるように修正してみます。
適当にログを出力するように修正してみました。

routes\web.php
Route::get('/', function () {

    // ログを出力する
    \Log::info("Laravel Log TEST!");

    return view('welcome');
});

ロガーの設定を変更します。

config\logging.php
        // 'single' => [
        //     'driver' => 'single',
        //     'path' => storage_path('logs/laravel.log'),
        //     'level' => env('LOG_LEVEL', 'debug'),
        // ],
        'single' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],

Herokuにデプロイします。

$ git add .
$ git commit -m "Log Test"
$ git push heroku master

デプロイされたサイトにアクセスしてみましょう。

$ heroku open

Herokuのログを確認するには、以下のコマンドでできます。

$ heroku logs

ログの中に、Laravelのログの内容も出力されていることが確認できます。

...
 [22-Jan-2022 14:53:15 UTC] [2022-01-22 14:53:15] production.INFO: Laravel Log TEST!
...

NPMの実行

Herokuへデプロイ時にNPMコマンドの実行を行うこともできます。
Laravelプロジェクトでは以下のように、js/cssなどをビルドするでしょう。

$ npm run prod

Herokuでも設定は可能ですが、今回はローカルの開発環境でビルドを行い、トランスパイルされたファイルをプッシュする運用にしようと思いますので、この手順は割愛します。

さいごに

Herokuを使って、Laravelプロジェクトを公開する手順をまとめました。

個人開発でとりあえず公開して使ってもらいたい、と言う場合に手軽に公開できます。
是非活用してみましょう。

他にも私のブログで、Laravelについて解説している記事がありますのでご覧ください。

\オススメ/

コメント