LoginSignup
8
4

More than 1 year has passed since last update.

VPSにLaravelが動く環境を作る

Last updated at Posted at 2021-03-15

VPSにLaravel環境を作る デプロイはgithubから行う

より本運用に近い形をイメージして github にリポジトリを作成、productionブランチからサーバーにデプロイするイメージで作成する。

プロジェクトを用意

GitHubにプロジェクトを作る

create_git_repository.png

開発用Macにclone

git clone git@github.com:sugie/my_laravel.git org

orgディレクトリにリポジトリがクローンされる。

Laravelプロジェクトを新規作成

> composer create-project laravel/laravel=6.* my_project

Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Nothing to install, update or remove
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
67 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

composer installを実行

> composer install
Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Nothing to install, update or remove
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
67 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

artisan serveを実行

> php artisan serve
Laravel development server started: http://127.0.0.1:8000
[Mon Mar 15 17:19:41 2021] PHP 7.4.12 Development Server (http://127.0.0.1:8000) started
[Mon Mar 15 17:19:46 2021] 127.0.0.1:57585 Accepted
[Mon Mar 15 17:19:46 2021] 127.0.0.1:57586 Accepted
[Mon Mar 15 17:19:46 2021] 127.0.0.1:57585 Closing
[Mon Mar 15 17:19:47 2021] 127.0.0.1:57586 [200]: GET /favicon.ico
[Mon Mar 15 17:19:47 2021] 127.0.0.1:57586 Closing

ブラウザで
http://127.0.0.1:8000
を開くいて、LaravelのWelcomeページが表示されることを確認。

first.png

githubにpush

> cp -pR ../org/.git .

ステータスを確認

> git status

On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	.editorconfig
	.env.example
	.gitattributes
	.styleci.yml
	README.md
	app/
	artisan
	bootstrap/
	composer.json
	composer.lock
	config/
	database/
	package.json
	phpunit.xml
	public/
	resources/
	routes/
	server.php
	storage/
	tests/
	webpack.mix.js

nothing added to commit but untracked files present (use "git add" to track)

AddしてCommitしてPush

>git add .

>git commit -m 'First commit'

[master (root-commit) 5b38273] First commit
 84 files changed, 9914 insertions(+)
 create mode 100644 .editorconfig
 create mode 100644 .env.example
 create mode 100644 .gitattributes
 create mode 100644 .styleci.yml
 create mode 100644 README.md
 create mode 100644 app/Console/Kernel.php
 create mode 100644 app/Exceptions/Handler.php
 create mode 100644 app/Http/Controllers/Auth/ConfirmPasswordController.php
 create mode 100644 app/Http/Controllers/Auth/ForgotPasswordController.php
 create mode 100644 app/Http/Controllers/Auth/LoginController.php
 create mode 100644 app/Http/Controllers/Auth/RegisterController.php
 create mode 100644 app/Http/Controllers/Auth/ResetPasswordController.php
 create mode 100644 app/Http/Controllers/Auth/VerificationController.php
 create mode 100644 app/Http/Controllers/Controller.php
 create mode 100644 app/Http/Kernel.php
 create mode 100644 app/Http/Middleware/Authenticate.php
 create mode 100644 app/Http/Middleware/CheckForMaintenanceMode.php
 create mode 100644 app/Http/Middleware/EncryptCookies.php
 create mode 100644 app/Http/Middleware/RedirectIfAuthenticated.php
 create mode 100644 app/Http/Middleware/TrimStrings.php
 create mode 100644 app/Http/Middleware/TrustProxies.php
 create mode 100644 app/Http/Middleware/VerifyCsrfToken.php
 create mode 100644 app/Providers/AppServiceProvider.php
 create mode 100644 app/Providers/AuthServiceProvider.php
 create mode 100644 app/Providers/BroadcastServiceProvider.php
 create mode 100644 app/Providers/EventServiceProvider.php
 create mode 100644 app/Providers/RouteServiceProvider.php
 create mode 100644 app/User.php
 create mode 100755 artisan
 create mode 100644 bootstrap/app.php
 create mode 100644 bootstrap/cache/.gitignore
 create mode 100644 composer.json
 create mode 100644 composer.lock
 create mode 100644 config/app.php
 create mode 100644 config/auth.php
 create mode 100644 config/broadcasting.php
 create mode 100644 config/cache.php
 create mode 100644 config/database.php
 create mode 100644 config/filesystems.php
 create mode 100644 config/hashing.php
 create mode 100644 config/logging.php
 create mode 100644 config/mail.php
 create mode 100644 config/queue.php
 create mode 100644 config/services.php
 create mode 100644 config/session.php
 create mode 100644 config/view.php
 create mode 100644 database/factories/UserFactory.php
 create mode 100644 database/migrations/2014_10_12_000000_create_users_table.php
 create mode 100644 database/migrations/2014_10_12_100000_create_password_resets_table.php
 create mode 100644 database/migrations/2019_08_19_000000_create_failed_jobs_table.php
 create mode 100644 database/seeds/DatabaseSeeder.php
 create mode 100644 package.json
 create mode 100644 phpunit.xml
 create mode 100644 public/.htaccess
 create mode 100644 public/favicon.ico
 create mode 100644 public/index.php
 create mode 100644 public/robots.txt
 create mode 100644 public/web.config
 create mode 100644 resources/js/app.js
 create mode 100644 resources/js/bootstrap.js
 create mode 100644 resources/lang/en/auth.php
 create mode 100644 resources/lang/en/pagination.php
 create mode 100644 resources/lang/en/passwords.php
 create mode 100644 resources/lang/en/validation.php
 create mode 100644 resources/sass/app.scss
 create mode 100644 resources/views/welcome.blade.php
 create mode 100644 routes/api.php
 create mode 100644 routes/channels.php
 create mode 100644 routes/console.php
 create mode 100644 routes/web.php
 create mode 100644 server.php
 create mode 100644 storage/app/.gitignore
 create mode 100644 storage/app/public/.gitignore
 create mode 100644 storage/framework/cache/.gitignore
 create mode 100644 storage/framework/cache/data/.gitignore
 create mode 100644 storage/framework/sessions/.gitignore
 create mode 100644 storage/framework/testing/.gitignore
 create mode 100644 storage/framework/views/.gitignore
 create mode 100644 storage/logs/.gitignore
 create mode 100644 tests/CreatesApplication.php
 create mode 100644 tests/Feature/ExampleTest.php
 create mode 100644 tests/TestCase.php
 create mode 100644 tests/Unit/ExampleTest.php
 create mode 100644 webpack.mix.js
git push origin master
Authenticated to github.com ([52.69.186.44]:22).
Counting objects: 110, done.
Delta compression using up to 12 threads.
Compressing objects: 100% (93/93), done.
Writing objects: 100% (110/110), 62.85 KiB | 0 bytes/s, done.
Total 110 (delta 11), reused 0 (delta 0)
remote: Resolving deltas: 100% (11/11), done.
Transferred: sent 67160, received 3404 bytes, in 2.1 seconds
Bytes per second: sent 32330.1, received 1638.7
To git@github.com:sugie/my_laravel.git
 * [new branch]      master -> master

プロダクションブランチを作成してpush


> git checkout production
error: pathspec 'production' did not match any file(s) known to git.

> git branch
* master

> git checkout production
error: pathspec 'production' did not match any file(s) known to git.

> git branch production

> git checkout production
Switched to branch 'production'

> git merge master -m 'merge from master'
Already up-to-date.

> git push origin production
Authenticated to github.com ([52.192.72.89]:22).
Total 0 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'production' on GitHub by visiting:
remote:      https://github.com/sugie/my_laravel/pull/new/production
Transferred: sent 2740, received 2764 bytes, in 1.8 seconds
remote:
Bytes per second: sent 1531.3, received 1544.7
To git@github.com:sugie/my_laravel.git
 * [new branch]      production -> production

> 

git flowの手順にしたがって
productionブランチにはデプロイする内容を入れる。

VPSにサーバーを作る

今回はvultr.comを使う。さくらのVPSでもConoHaのVPSでも基本は同じだと思う。

vultr.png

vultrでfirewallを設定する方法は
https://qiita.com/Shiro-neko-kamen/items/0b4a8504eb87a459c7d8
こちらを参照。

サーバーインスタンスができたら詳細画面に遷移

server_detail.png

ターミナルでログインする

Macでターミナルアプリを起動。

detail2.png

コピーアイコンをクリックしてIPアドレスをコピー。

ssh root@コピーしたIPアドレスをペースト

パスワードを聞かれるので、サーバー詳細のrootパスワードをコピーしてペースト。

ss.png

52 updates can be installed immediately.
とか出てくるのでアップデートを最初に行う。

apt-get update
apt-get upgrade

作業用アカウントを用意する

visudo のエディタをvimに変更。nanoエディタを使いたい人は以下のコマンドを実行しない。

update-alternatives --set editor /usr/bin/vim.basic

ユーザー名を決める。taroでも、hanakoでも、itadoriでもtanjiroでもなんでも良い。今回はblueを使う。

adduser blue

パスワードを設定。uShieh#oo8agを設定。

blueをsudoできるようにする。

visudo

blue ALL=(ALL) NOPASSWD:ALL
を27行目くらいに挿入して保存。

ss 1.png

blueの公開鍵を設定

作業ユーザーは鍵認証でsshログインするようにする。鍵認証の詳細は割愛。説明希望の人はコメント欄に説明希望と書いてください。追記します。

su blue
cd
mkdir .ssh
vi .ssh/authorized_keys

公開鍵をペーストして保存

パーミッションを設定
chmod 0700 .ssh
chmod 0400 .ssh/authorized_keys

この設定をすると作業ユーザーでsshログインできるようになる。

Macのターミナルから以下のコマンドを実行

ssh blue@139.180.207.51

sudo できることを確認

sudo pwd

成功したらrootでのリモートログインを禁止して、パスワードログインを禁止してセキュリティ向上をしたいところ。

使いそうなモジュールをインストール

サーバーに作業ユーザーでログインしてapt-get installを実行。

ssh blue@139.180.207.51

sudo apt-get install curl wget net-tools vim vim-gtk3 vim-tiny neovim vim-athena vim-gtk vim-nox python vim-gui-common vim-runtime mycli tree nkf 

ズラーっといろいろ表示される。

###Apacheをインストール

ppa:ondrej/apache2 リポジトリを追加

sudo add-apt-repository ppa:ondrej/apache2

sudo apt-get update

sudo apt-get update

Apacheをインストール

sudo apt-get install apache2 w3m

インストールされていることを確認

> systemctl  | grep apache
  apache2.service                                                                     loaded    active running   The Apache HTTP Server                                                       

ブラウザで確認

を開く。こんなのが表示される。
ss 2.png

せっかくだからドメインの設定をする

お名前.comのDOMナビの例。DNSの説明は割愛します。
作ったサーバーのIPアドレスを指定して反映。
ss 3.png

登録したURLをブラウザで開いてみる。

ss 4.png
すぐには表示されない。

ある程度時間が経ってDNSが浸透したら開けるようになる。

10分くらいで表示されるようになった。
ss 5.png

MySQLデータベースをインストール

https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-20-04-ja
このサイトを参考にしました。

sudo apt install mysql-server
sudo mysql_secure_installation

Press y|Y for Yes, any other key for No: NO

New password: ohcue3Olu

Remove anonymous users? (Press y|Y for Yes, any other key for No) : yes

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y


MYSQLユーザーの作成

sudo mysql

CREATE USER 'myproject'@'%';
CREATE DATABASE IF NOT EXISTS myproject;
GRANT ALL PRIVILEGES ON myproject.* TO 'myproject'@'%';
CREATE USER 'myproject'@'localhost';
GRANT ALL PRIVILEGES ON myproject.* TO 'myproject'@'localhost';
use mysql
ALTER USER 'myproject'@'localhost' identified BY 'ooH8Tho8umo';
flush privileges;

別のターミナルからログインできることを確認

blue@mylaravel:~$ mysql -umyproject -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.23-0ubuntu0.20.10.1 (Ubuntu)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

mycliでもログインしてみる。コマンドラインからmysqlに繋ぐならmysqlコマンドよりmycliコマンドのほうが便利だ。

blue@mylaravel:~$ mycli -umyproject
Password: 
mysql 8.0.23-0ubuntu0.20.10.1
mycli 1.22.2
Chat: https://gitter.im/dbcli/mycli
Mail: https://groups.google.com/forum/#!forum/mycli-users
Home: http://mycli.net
Thanks to the contributor - Zane C. Bowers-Hadley
mysql myproject@localhost:(none)>
mysql myproject@localhost:(none)> quit
Goodbye!
blue@mylaravel:~$ 

PHPのインストール

sudo apt-get install php7.4-cli  php7.4-common php7.4 php7.4-mbstring php7.4-xml php7.4-dom php7.4-gd php7.4-mysqlnd php7.4-pdo php7.4-zip php7.4-redis php7.4-curl

バージョンを確認

php --version
>php -version
PHP 7.4.9 (cli) (built: Oct 26 2020 15:17:14) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies

compoesrをインストール

sudo apt-get install composer

githubから持ってくる

cd ~
vi mygithub.secret
# GitHubに登録した秘密鍵を配置
# 保存したら以下のコマンドでパーミッションを設定

chmod 0400 ~/.ssh/mygithub.secret

vi ~/.ssh/config
Host github.com
    User #GitHubAccount#
    Port 22
    HostName github.com
    IdentityFile ~/.ssh/mygithub.secret
    TCPKeepAlive yes
    IdentitiesOnly yes

クローン
productionブランチを指定

git clone git@github.com:sugie/my_laravel.git --branch production

my_laravelディレクトリを移動

sudo mkdir /var/sites/
sudo mv /home/blue/my_laravel /var/sites/my_laravel
sudo chown www-data:www-data -R /var/sites/my_laravel

composer を実行

cd /var/sites/my_laravel
sudo -u www-data composer install

composer_installing.png

www-dataユーザーでgit pullできるように設定

sudo mkdir /var/www/.ssh -p
sudo cp -p /home/blue/.ssh/#MY_GITHUB_SECRET#.secret /var/www/.ssh/.

所有者をwww-dataにする

sudo vi /var/www/.ssh/config
Host github.com
    User #MY_GITHUB_ACCOUNT#
    Port 22
    HostName github.com
    IdentityFile ~/.ssh/#MY_GITHUB_SECRET#.secret
    TCPKeepAlive yes
    IdentitiesOnly yes
sudo chown www-data:www-data -R /var/www

pullしてみる

cd /var/sites/my_laravel
sudo -u www-data git pull

将来本番サーバーに反映させるときは
productionブランチを用意して、pullを行って反映させる。

環境ファイルの用意

cd /var/sites/my_laravel
sudo cp -p .env.example .env
sudo -u www-data vi .env

データベースの設定を.envに反映。さっき作ったMySQLユーザーとパスワードを記述。

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=myproject
DB_USERNAME=myproject
DB_PASSWORD=ooH8Tho8umo

Key generate

sudo -u www-data php artisan key:generate

.envに
APP_KEY=base64:3epehyg5v9XIHz2ZxTquvcpVdnbKGxlDmHPCaLTdU9w=
が設定される。

migrateを実行

sudo -u www-data php artisan migrate

mig.png

storage以下にフォルダを作る

sudo -u www-data mkdir -p storage/framework/cache/data
sudo -u www-data mkdir -p storage/framework/app/cache
sudo -u www-data mkdir -p storage/framework/sessions
sudo -u www-data mkdir -p storage/framework/views

Apacheの設定

既存の設定ファイルを削除。

cd /etc/apache2/sites-enabled
sudo rm 000-default.conf

新しい仮想ホストの設定ファイルを作る

cd ../sites-available/

#設定ファイルはドメイン名+.confを勧めます

sudo vi myproject.ice2nd.mobi.conf

<VirtualHost *:80>
        ServerName myproject.ice2nd.mobi

        ServerAdmin admin@email.address
        DocumentRoot /var/sites/my_laravel/public
        <Directory /var/sites/my_laravel/public>
                AllowOverride All
                Options All
                Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
cd /etc/apache2/sites-enabled
sudo ln -s ../sites-available/myproject.ice2nd.mobi.conf .


sudo apache2ctl configtest
Syntax OK

sudo apache2ctl start

apa.png

ブラウザで確認

br.png

https化する

https化するにはSSL証明書が必要。このサイトは正しいサイトですよ。と認証局に認定してもらう。証明書は購入することもできるが、無料でも入手できる。
無料で使えるSSL証明書はLets encryptと呼ばれている。
今回はlets encryptを使って証明書をインストールし、1ヶ月で自動更新するようにする。

cetbotをインストールするためにリポジトリを追加する。

sudo apt-get install certbot python3-certbot-apache

証明書のインストール

sudo certbot --apache

nc.png

ブラウザでhttpsになっていることを確認。

https.png

vultr.com でサーバーを作りなら

https://www.vultr.com/?ref=8408139-6G
このリンクから申し込むと100$分の利用料がもらえるので、よかったら使ってください。

8
4
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
8
4