macでHerokuにデプロイしてみた

今回はLaravelで構築したWebアプリケーションをmacを使ってHerokuにデプロイしてみます。

デプロイとは?

デプロイとはローカルPCで開発したWebアプリケーションをサーバーにアップロードしてサーバーで実行可能にすることをいいます。

Herokuとは?

Herokuとは、PaaS(Platform as a Service)と呼ばれるプラットフォームです。 PaaSとは、作成したプログラムを動かすためのサーバーやその言語環境(PHPやRuby、Python)などを、インターネット経由のサービスとして利用できるというものです。

前提環境

・Heroku無料アカウント
・PHPのインストール
・gitのインストール

⚠️作業はソースコードの場所へ移動(cd)して行う。

Herokuアカウントの登録はこちら
https://signup.heroku.com/dc

PHP環境の確認

$ php -v
PHP 7.2.13 (cli) (built: Dec  9 2018 16:43:07) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
   with Xdebug v2.8.0, Copyright (c) 2002-2019, by Derick Rethans

gitの確認

$ git --version
git version 2.22.0

Herokuコマンドラインインターフェイス(CLI)をインストールする。

$ brew install heroku/brew/heroku

以下のようにheroku --versionでHeroku CLIのバージョンが確認できればインストールは完了です。

$ heroku --version
heroku/7.41.1 darwin-x64 node-v12.16.2

heroku loginコマンドを使用して、Heroku CLIにログインします。

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

ターミナル上で何かキーを叩くとブラウザが立ち上がるので「LOGIN」ボタンをクリックします。

スクリーンショット 2020-05-24 16.30.08

この状態になればCLIにログインできています。

スクリーンショット 2020-05-24 16.31.23

Herokuへアプリを作成する場合は、以下のコマンドを実行します。

heroku apps:create

名前を指定する場合は以下のように実行しましょう。

heroku apps:create -a <アプリ名>

PCのソースコードとリモートリポジトリを紐づけるために、以下のコマンドを実行します。 「heroku git:remote」の後ろに作成したアプリ名を-aオプションで指定します。

heroku git:remote -a arakakisample
set git remote heroku to https://git.heroku.com/arakakisample.git

Herokuのビルドパック設定

ビルドパックとは環境で必要なプログラミング言語のインストールやフレームワークを簡単に環境構築するものです。

今回はLaravelで作成したWebアプリケーションをリリースしますので、PHPとNode.jsのビルドパックを設定します。以下の2つのコマンドを実行。

heroku buildpacks:set heroku/nodejs
heroku buildpacks:set heroku/php

ビルドパックの確認

$ heroku buildpacks
=== arakakisample Buildpack URLs
1. heroku/php
2. heroku/nodejs

Herokuにデータベースの作成

ローカルにあるデータベース環境はMySQLだがHerokuでMySQLを使用するにはクレジットカードの登録が必要みたいなので今回は、PostgreSQLを利用します。

以下のコマンドをターミナルで実行することでデータベースを設定できます。

heroku addons:create heroku-postgresql:hobby-dev

データベース設定後、以下のコマンドでデータベースの設定情報を取得できます。

heroku config:get DATABASE_URL

実行すると、以下のようにターミナルに表示されます。

postgres://<ユーザー>:<パスワード>@<ホスト>:<ポート>/<データベース名>

取得したデータベースの設定情報を、以下のようにターミナルでコマンドとして実行し、それぞれ環境変数として設定していきます。

heroku config:set DB_CONNECTION=pgsql
heroku config:set DB_DATABASE=<データベース名>
heroku config:set DB_HOST=<ホスト>
heroku config:set DB_PASSWORD=<パスワード>
heroku config:set DB_PORT=<ポート>
heroku config:set DB_USERNAME=<ユーザー>

APP_KEYの作成

LaravelをHerokuへリリースするためには、APP_KEYという環境変数を設定する必要があります。

以下のコマンドでAPP_KEYを表示できます。

php artisan key:generate --show

base64から文字列の最後までをコピーしたものをheroku config:setを使い、環境変数APP_KEYにセットします。

heroku config:set APP_KEY=base64:1HxfJpS0p8TEUWrLSwDR2soV5uq6W4+AKa0vL4O7MKM=

Procfileの追加

Laravelで作成したWebアプリケーションをHerokuで動かすためには、Procfileと呼ばれるファイルを用意する必要があります。

プロジェクトディレクトリの直下に、Procfileという名前でファイルを作成し、以下の内容を追加します。

僕の環境ではXAMMPで開発したため。
/Applications/XAMPP/xamppfiles/htdocs/laravel
の直下にProcfileファイルを作成しました。

Procfileを開いて以下の内容に追記します。

web: vendor/bin/heroku-php-apache2 public/

Herokuへのデプロイ

いよいよHerokuへデプロイします。
Herokuへのデプロイはgit push heroku masterコマンドを実行して、手元にあるローカルPCのソースコードをHerokuのアプリ内にあるリモートリポジトリにプッシュします。

git push heroku master

以下のように実行されました。

$ git push heroku master
Enumerating objects: 538, done.
Counting objects: 100% (538/538), done.
Delta compression using up to 4 threads
Compressing objects: 100% (508/508), done.
Writing objects: 100% (538/538), 1.05 MiB | 3.73 MiB/s, done.
Total 538 (delta 282), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> PHP app detected
remote: -----> Bootstrapping...
remote: -----> Installing platform packages...
remote:        - php (7.4.5)
remote:        - ext-mbstring (bundled with php)
remote:        - apache (2.4.43)
remote:        - nginx (1.18.0)
remote: -----> Installing dependencies...
remote:        Composer version 1.10.5 2020-04-10 11:44:22
remote:        Loading composer repositories with package information
remote:        Installing dependencies from lock file
remote:        Package operations: 54 installs, 0 updates, 0 removals
remote:          - Installing symfony/finder (v4.4.2): Downloading (100%)
remote:          - Installing psr/log (1.1.2): Downloading (100%)
remote:          - Installing symfony/debug (v4.4.2): Downloading (100%)
remote:          - Installing symfony/polyfill-php72 (v1.13.1): Downloading (100%)
remote:          - Installing symfony/polyfill-mbstring (v1.13.1): Downloading (100%)
remote:          - Installing symfony/var-dumper (v4.4.2): Downloading (100%)
remote:          - Installing maximebf/debugbar (v1.15.1): Downloading (100%)
remote:          - Installing symfony/polyfill-ctype (v1.13.1): Downloading (100%)
remote:          - Installing phpoption/phpoption (1.7.2): Downloading (100%)
remote:          - Installing vlucas/phpdotenv (v3.6.0): Downloading (100%)
remote:          - Installing symfony/css-selector (v5.0.2): Downloading (100%)
remote:          - Installing tijsverkoyen/css-to-inline-styles (2.2.2): Downloading (100%)
remote:          - Installing symfony/routing (v4.4.2): Downloading (100%)
remote:          - Installing symfony/process (v4.4.2): Downloading (100%)
remote:          - Installing symfony/polyfill-php73 (v1.13.1): Downloading (100%)
remote:          - Installing symfony/polyfill-intl-idn (v1.13.1): Downloading (100%)
remote:          - Installing symfony/mime (v5.0.2): Downloading (100%)
remote:          - Installing symfony/http-foundation (v4.4.2): Downloading (100%)
remote:          - Installing symfony/event-dispatcher-contracts (v1.1.7): Downloading (100%)
remote:          - Installing symfony/event-dispatcher (v4.4.2): Downloading (100%)
remote:          - Installing symfony/error-handler (v4.4.2): Downloading (100%)
remote:          - Installing symfony/http-kernel (v4.4.2): Downloading (100%)
remote:          - Installing psr/container (1.0.0): Downloading (100%)
remote:          - Installing symfony/service-contracts (v2.0.1): Downloading (100%)
remote:          - Installing symfony/console (v4.4.2): Downloading (100%)
remote:          - Installing symfony/polyfill-iconv (v1.13.1): Downloading (100%)
remote:          - Installing doctrine/lexer (1.2.0): Downloading (100%)
remote:          - Installing egulias/email-validator (2.1.14): Downloading (100%)
remote:          - Installing swiftmailer/swiftmailer (v6.2.3): Downloading (100%)
remote:          - Installing paragonie/random_compat (v9.99.99): Downloading (100%)
remote:          - Installing ramsey/uuid (3.9.2): Downloading (100%)
remote:          - Installing psr/simple-cache (1.0.1): Downloading (100%)
remote:          - Installing opis/closure (3.5.1): Downloading (100%)
remote:          - Installing symfony/translation-contracts (v2.0.1): Downloading (100%)
remote:          - Installing symfony/translation (v4.4.2): Downloading (100%)
remote:          - Installing nesbot/carbon (2.28.0): Downloading (100%)
remote:          - Installing monolog/monolog (2.0.2): Downloading (100%)
remote:          - Installing league/flysystem (1.0.63): Downloading (100%)
remote:          - Installing league/commonmark (1.1.2): Downloading (100%)
remote:          - Installing league/commonmark-ext-table (v2.1.0): Downloading (100%)
remote:          - Installing dragonmantank/cron-expression (v2.3.0): Downloading (100%)
remote:          - Installing doctrine/inflector (1.3.1): Downloading (100%)
remote:          - Installing laravel/framework (v6.10.1): Downloading (100%)
remote:          - Installing barryvdh/laravel-debugbar (v3.2.8): Downloading (100%)
remote:          - Installing fideloper/proxy (4.2.2): Downloading (100%)
remote:          - Installing jakub-onderka/php-console-color (v0.2): Downloading (100%)
remote:          - Installing nikic/php-parser (v4.3.0): Downloading (100%)
remote:          - Installing jakub-onderka/php-console-highlighter (v0.4): Downloading (100%)
remote:          - Installing dnoegel/php-xdg-base-dir (v0.1.1): Downloading (100%)
remote:          - Installing psy/psysh (v0.9.12): Downloading (100%)
remote:          - Installing laravel/tinker (v1.0.10): Downloading (100%)
remote:          - Installing laravel/ui (v1.1.2): Downloading (100%)
remote:          - Installing laravelcollective/html (v6.0.3): Downloading (100%)
remote:          - Installing rutorika/sortable (6.0.0): Downloading (100%)
remote:        Generating optimized autoload files
remote:        Deprecation Notice: Class App\Http\Controllers\Admin\Auth\LoginController located in ./app/Http/Controllers/Admin/LoginController.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///tmp/build_388d2c5dc55b18582e66fe8ffe2c8ce9/.heroku/php/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201
remote:        Deprecation Notice: Class App\Http\Controllers\Auth\Auth\ConfirmPasswordController located in ./app/Http/Controllers/Admin/Auth/ConfirmPasswordController.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///tmp/build_388d2c5dc55b18582e66fe8ffe2c8ce9/.heroku/php/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201
remote:        Deprecation Notice: Class App\Http\Controllers\Auth\Auth\ResetPasswordController located in ./app/Http/Controllers/Admin/Auth/ResetPasswordController.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///tmp/build_388d2c5dc55b18582e66fe8ffe2c8ce9/.heroku/php/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201
remote:        Deprecation Notice: Class App\Http\Controllers\Auth\Auth\ForgotPasswordController located in ./app/Http/Controllers/Admin/Auth/ForgotPasswordController.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///tmp/build_388d2c5dc55b18582e66fe8ffe2c8ce9/.heroku/php/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201
remote:        Deprecation Notice: Class App\Http\Controllers\Auth\Auth\VerificationController located in ./app/Http/Controllers/Admin/Auth/VerificationController.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///tmp/build_388d2c5dc55b18582e66fe8ffe2c8ce9/.heroku/php/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201
remote:        Warning: Ambiguous class resolution, "App\Http\Controllers\Admin\Auth\LoginController" was found in both "/tmp/build_388d2c5dc55b18582e66fe8ffe2c8ce9/app/Http/Controllers/Admin/LoginController.php" and "/tmp/build_388d2c5dc55b18582e66fe8ffe2c8ce9/app/Http/Controllers/Admin/Auth/LoginController.php", the first will be used.
remote:        > Illuminate\Foundation\ComposerScripts::postAutoloadDump
remote:        > @php artisan package:discover --ansi
remote:        Discovered Package: barryvdh/laravel-debugbar
remote:        Discovered Package: fideloper/proxy
remote:        Discovered Package: laravel/tinker
remote:        Discovered Package: laravel/ui
remote:        Discovered Package: laravelcollective/html
remote:        Discovered Package: nesbot/carbon
remote:        Package manifest generated successfully.
remote: -----> Preparing runtime environment...
remote: -----> Checking for additional extensions to install...
remote: -----> Node.js app detected
remote:        
remote: -----> Creating runtime environment
remote:        
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NODE_ENV=production
remote:        NODE_MODULES_CACHE=true
remote:        NODE_VERBOSE=false
remote:        
remote: -----> Installing binaries
remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:        
remote:        Resolving node version 12.x...
remote:        Downloading and installing node 12.16.3...
remote:        Using default npm version: 6.14.4
remote:        
remote: -----> Installing dependencies
remote:        Installing node modules (package.json + package-lock)
remote:        added 1012 packages from 493 contributors and audited 1081 packages in 24.598s
remote:        
remote:        11 packages are looking for funding
remote:          run `npm fund` for details
remote:        
remote:        found 615 vulnerabilities (610 low, 4 moderate, 1 high)
remote:          run `npm audit fix` to fix them, or `npm audit` for details
remote:        
remote: -----> Build
remote:        
remote: -----> Caching build
remote:        - node_modules
remote:        
remote: -----> Pruning devDependencies
remote:        removed 1011 packages and audited 1 package in 11.26s
remote:        found 0 vulnerabilities
remote:        
remote:        
remote: -----> Build succeeded!
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote: 
remote: -----> Compressing...
remote:        Done: 41.9M
remote: -----> Launching...
remote:        Released v12
remote:        https://arakakisample.herokuapp.com/ deployed to Heroku
remote: 
remote: Verifying deploy... done.
To https://git.heroku.com/arakakisample.git
* [new branch]      master -> master

コードは無事Herokuにデプロイされました!

最後にLaravelでデータベースを作成するためのマイグレーションを実行していません。 そこで「php artisan migrate」をを実行します。

heroku run php artisan migrate -a <アプリ名>

上手く行きましたね!

heroku run php artisan migrate -a arakakisample
Running php artisan migrate on ⬢ arakakisample... up, run.8098 (Free)
**************************************
*     Application In Production!     *
**************************************

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

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.02 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (0.01 seconds)
Migrating: 2019_11_14_045749_create_posts_table
Migrated:  2019_11_14_045749_create_posts_table (0.01 seconds)
Migrating: 2019_11_27_064202_create_goals_table
Migrated:  2019_11_27_064202_create_goals_table (0.01 seconds)
Migrating: 2019_11_27_064219_create_todos_table
Migrated:  2019_11_27_064219_create_todos_table (0.01 seconds)
Migrating: 2019_12_07_075648_create_tags_table
Migrated:  2019_12_07_075648_create_tags_table (0.01 seconds)
Migrating: 2019_12_07_075826_create_todo_tags_table
Migrated:  2019_12_07_075826_create_todo_tags_table (0.01 seconds)
Migrating: 2020_01_04_012146_create_products_table
Migrated:  2020_01_04_012146_create_products_table (0.01 seconds)
Migrating: 2020_01_09_082756_create_categories_table
Migrated:  2020_01_09_082756_create_categories_table (0.01 seconds)
Migrating: 2020_01_16_081432_create_admins_table
Migrated:  2020_01_16_081432_create_admins_table (0.02 seconds)

最後に、デプロイしたアプリにアクセスしてみましょう。

 https://<アプリ名>.herokuapp.com

上記のURLでアクセスすると画面が表示されます。

スクリーンショット 2020-05-24 17.37.11

お疲れ様でした!

良ければYouTubeのチャンネル登録、Twitterのフォローをお願いします!


YouTubeチャンネル 「爆速プログラミングチャンネル」
https://www.youtube.com/channel/UCnGHmf-kbUALwO8kNoMWsSQ/

Twitter
https://twitter.com/a_makoto33

この記事が気に入ったらサポートをしてみませんか?