3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vagrant(CentOS7) × PostgreSQL × CakePHP × Apacheで環境構築

Last updated at Posted at 2019-06-06

はじめに

環境構築に慣れていない初学者がメモとしてかいたエントリーです。
正しい情報を書いているつもりですが万が一間違った情報などがありましたら、
ご指摘してくださるとありがたいです。

今回やること

Vagrant(CentOS7)で以下を導入してみる。

  • PHP7.3
  • Apache 2.4
  • PostgreSQL
  • CakePHP 3.x系

Vagrant

※VirtualboxおよびVagrantのインストールは終わっていること、boxもすでに追加済みのことが前提

ホストOSのターミナル
# 好きなディレクトリにVagrant用のフォルダを作成
$mkdir CentOS
$cd CentOS

$vagrant init

# Vagrantfileを以下に書き換え
Vagrant.configure("2") do |config|
  config.vm.box = "centos/7"
end

# 仮想マシンを立ち上げてssh接続する
$vagrant up
$vagrant ssh
ゲストOSのターミナル
# 管理者権限でログイン
$sudo su -

Apacheのインストール

ゲストOSのターミナル
# インストール
$yum install httpd

# バージョン確認
$httpd -v
server version: Apache/2.4.6 (CentOS)
Server built:   Apr 24 2019 13:45:48

「$yum install httpd php」でphpも同時にインストールが可能だが、composerでCakePHP導入時にPHPのバージョンが5.6以上の必要があるため、ここではインストールしない。

PHP(7.3)のインストール

レポジトリ の導入

PHP7.3をインストールするためには、EPEL、Remiレポジトリが必要となる。

## EPELをインストール
$yum install epel-release

# [epel]のbaseurlをコメントイン、metalinkをコメントアウト
vi /etc/yum.repos.d/epel.repo

[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7


## Remiをインストール
$yum -y install http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

# libargon2がPHP7.3を入れる際に依存性パッケージとして必要となる
$yum install --disablerepo=* --enablerepo=epel libargon2

# 一旦インストールし終わったら以下を実行
$yum update

リポジトリがインストールされているか確認

epelとremiリポジトリがインストールされているか確認。

$yum repolist

# 結果
読み込んだプラグイン:fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.riken.jp
 * epel: ftp.riken.jp
 * extras: ftp.riken.jp
 * remi-safe: ftp.riken.jp
 * updates: ftp.riken.jp
リポジトリー ID  リポジトリー名                                           状態
base/7/x86_64    CentOS-7 - Base                                          10,019
epel/x86_64      Extra Packages for Enterprise Linux 7 - x86_64           13,215
extras/7/x86_64  CentOS-7 - Extras                                           409
remi-safe        Safe Remi's RPM repository for Enterprise Linux 7 - x86_  3,267
updates/7/x86_64 CentOS-7 - Updates                                        1,945
repolist: 28,855

インストールがうまくいかないとき

epelレポを1回消してインストールしてみる。

# 一度アンインストール
$yum remove epel-release

# もう一度インストール
$yum install epel-release

remiレポジトリにPHPをインストール

# CakePHPの導入に必要な依存性パッケージとPHPをインストール
$yum -y install --enablerepo=remi,remi-php73 php php-devel php-mbstring php-pdo php-gd php-xml php-mcrypt php-intl

最後に確認

$php -v
# 結果
PHP 7.3.6 (cli) (built: May 28 2019 09:32:59) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.6, Copyright (c) 1998-2018 Zend Technologies

無事インストール完了!

PostgreSQLのインストール

$yum install postgresql-server
$postgresql-setup initdb

# 拡張モジュールのインストールが必要
$yum --enablerepo=remi-php73 install php-pgsql

# 確認
psql --version
psql (PostgreSQL) 9.2.24

# 起動コマンド
$systemctl start postgresql.service

Composerのインストール

どこの階層でもいいので、以下コマンドを実行。

# 一旦管理者権限から抜ける
$exit

# インストーラーのインストール
$php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
$php composer-setup.php
$php -r "unlink('composer-setup.php');"
$mv composer.phar /usr/local/bin/composer

# 導入の確認
$composer

# 結果
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.8.5 2019-04-09 17:46:47

CakePHPのインストール

$cd /vagrant

# Cake導入時に必要な依存性パッケージとgit
$sudo yum install git
$sudo yum install zip unzip


# プロジェクトの作成
$composer create-project --prefer-dist cakephp/app [プロジェクト名]

# インストール開始
Installing cakephp/app (3.7.1)
  - Installing cakephp/app (3.7.1): Loading from cache
Created project in cake
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 78 installs, 0 updates, 0 removals
  - Installing cakephp/plugin-installer (1.1.0): Loading from cache
  - Installing aura/intl (3.0.0): Loading from cache
  - Installing psr/http-message (1.0.1): Loading from cache
  - Installing zendframework/zend-diactoros (1.8.6): Loading from cache
  - Installing psr/simple-cache (1.0.1): Loading from cache
  - Installing psr/log (1.1.0): Loading from cache
  - Installing cakephp/chronos (1.2.6): Loading from cache
  - Installing cakephp/cakephp (3.7.8): Loading from cache
  - Installing symfony/polyfill-ctype (v1.11.0): Downloading (100%)
  - Installing symfony/yaml (v4.3.0): Downloading (100%)
  - Installing symfony/filesystem (v4.3.0): Downloading (100%)
  - Installing symfony/config (v4.3.0): Downloading (100%)
  - Installing symfony/service-contracts (v1.1.2): Downloading (100%)
  - Installing symfony/polyfill-php73 (v1.11.0): Downloading (100%)
  - Installing symfony/polyfill-mbstring (v1.11.0): Downloading (100%)
  - Installing symfony/console (v4.3.0): Downloading (100%)
  - Installing robmorgan/phinx (0.10.7): Downloading (100%)
  - Installing cakephp/migrations (2.1.1): Downloading (100%)
  - Installing mobiledetect/mobiledetectlib (2.8.33): Downloading (100%)
  - Installing twig/twig (v1.42.1): Downloading (100%)
  - Installing umpirsky/twig-php-function (v0.1): Downloading (100%)
  - Installing jasny/twig-extensions (v1.2.0): Downloading (100%)
  - Installing asm89/twig-cache-extension (1.3.2): Downloading (100%)
  - Installing aptoma/twig-markdown (2.0.0): Downloading (100%)
  - Installing ajgl/breakpoint-twig-extension (0.3.4): Downloading (100%)
  - Installing wyrihaximus/twig-view (4.3.8): Downloading (100%)
  - Installing cakephp/bake (1.9.6): Downloading (100%)
  - Installing squizlabs/php_codesniffer (3.4.2): Downloading (100%)
  - Installing cakephp/cakephp-codesniffer (3.1.1): Downloading (100%)
  - Installing jdorn/sql-formatter (v1.2.17): Downloading (100%)
  - Installing symfony/process (v4.3.0): Downloading (100%)
  - Installing symfony/finder (v4.3.0): Downloading (100%)
  - Installing seld/phar-utils (1.0.1): Downloading (100%)
  - Installing seld/jsonlint (1.7.1): Downloading (100%)
  - Installing justinrainbow/json-schema (5.2.8): Downloading (100%)
  - Installing composer/xdebug-handler (1.3.3): Downloading (100%)
  - Installing composer/spdx-licenses (1.5.1): Downloading (100%)
  - Installing composer/semver (1.5.0): Downloading (100%)
  - Installing composer/ca-bundle (1.1.4): Downloading (100%)
  - Installing composer/composer (1.8.5): Downloading (100%)
  - Installing cakephp/debug_kit (3.19.0): Downloading (100%)
  - Installing m1/env (2.1.2): Downloading (100%)
  - Installing josegonzalez/dotenv (3.2.0): Downloading (100%)
  - Installing sebastian/version (2.0.1): Downloading (100%)
  - Installing sebastian/resource-operations (1.0.0): Downloading (100%)
  - Installing sebastian/recursion-context (3.0.0): Downloading (100%)
  - Installing sebastian/object-reflector (1.1.1): Downloading (100%)
  - Installing sebastian/object-enumerator (3.0.3): Downloading (100%)
  - Installing sebastian/global-state (2.0.0): Downloading (100%)
  - Installing sebastian/exporter (3.1.0): Downloading (100%)
  - Installing sebastian/environment (3.1.0): Downloading (100%)
  - Installing sebastian/diff (2.0.1): Downloading (100%)
  - Installing sebastian/comparator (2.1.3): Downloading (100%)
  - Installing doctrine/instantiator (1.2.0): Downloading (100%)
  - Installing phpunit/php-text-template (1.2.1): Downloading (100%)
  - Installing phpunit/phpunit-mock-objects (5.0.10): Downloading (100%)
  - Installing phpunit/php-timer (1.0.9): Downloading (100%)
  - Installing phpunit/php-file-iterator (1.4.5): Downloading (100%)
  - Installing theseer/tokenizer (1.1.2): Downloading (100%)
  - Installing sebastian/code-unit-reverse-lookup (1.0.1): Downloading (100%)
  - Installing phpunit/php-token-stream (2.0.2): Downloading (100%)
  - Installing phpunit/php-code-coverage (5.3.2): Downloading (100%)
  - Installing webmozart/assert (1.4.0): Downloading (100%)
  - Installing phpdocumentor/reflection-common (1.0.1): Downloading (100%)
  - Installing phpdocumentor/type-resolver (0.4.0): Downloading (100%)
  - Installing phpdocumentor/reflection-docblock (4.3.1): Downloading (100%)
  - Installing phpspec/prophecy (1.8.0): Downloading (100%)
  - Installing phar-io/version (1.0.1): Downloading (100%)
  - Installing phar-io/manifest (1.0.1): Downloading (100%)
  - Installing myclabs/deep-copy (1.9.1): Downloading (100%)
  - Installing phpunit/phpunit (6.5.14): Downloading (100%)
  - Installing jakub-onderka/php-console-color (v0.2): Downloading (100%)
  - Installing jakub-onderka/php-console-highlighter (v0.4): Downloading (100%)
  - Installing dnoegel/php-xdg-base-dir (0.1): Downloading (100%)
  - Installing nikic/php-parser (v4.2.2): Downloading (100%)
  - Installing symfony/polyfill-php72 (v1.11.0): Downloading (100%)
  - Installing symfony/var-dumper (v4.3.0): Downloading (100%)
  - Installing psy/psysh (v0.9.9): Downloading (100%)
cakephp/app suggests installing markstory/asset_compress (An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.)
cakephp/app suggests installing dereuromark/cakephp-ide-helper (After baking your code, this keeps your annotations in sync with the code evolving from there on for maximum IDE and PHPStan compatibility.)
cakephp/cakephp suggests installing lib-ICU (The intl PHP library, to use Text::transliterate() or Text::slug())
symfony/service-contracts suggests installing psr/container
symfony/service-contracts suggests installing symfony/service-implementation
symfony/console suggests installing symfony/event-dispatcher
symfony/console suggests installing symfony/lock
asm89/twig-cache-extension suggests installing psr/cache-implementation (To make use of PSR-6 cache implementation via PsrCacheAdapter.)
aptoma/twig-markdown suggests installing michelf/php-markdown (Original Markdown engine with MarkdownExtra.)
aptoma/twig-markdown suggests installing knplabs/github-api (Needed for using GitHub's Markdown engine provided through their API.)
ajgl/breakpoint-twig-extension suggests installing ext-xdebug (The Xdebug extension is required for the breakpoint to work)
ajgl/breakpoint-twig-extension suggests installing symfony/framework-bundle (The framework bundle to integrate the extension into Symfony)
ajgl/breakpoint-twig-extension suggests installing symfony/twig-bundle (The twig bundle to integrate the extension into Symfony)
composer/composer suggests installing ext-zip (Enabling the zip extension allows you to unzip archives)
m1/env suggests installing m1/vars (For loading of configs)
sebastian/global-state suggests installing ext-uopz (*)
phpunit/phpunit-mock-objects suggests installing ext-soap (*)
phpunit/php-code-coverage suggests installing ext-xdebug (^2.5.5)
phpunit/phpunit suggests installing phpunit/php-invoker (^1.1)
phpunit/phpunit suggests installing ext-xdebug (*)
psy/psysh suggests installing ext-posix (If you have PCNTL, you'll want the POSIX extension as well.)
psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)
psy/psysh suggests installing hoa/console (A pure PHP readline implementation. You'll want this if your PHP install doesn't already support readline or libedit.)
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files
> Cake\Composer\Installer\PluginInstaller::postAutoloadDump
> App\Console\Installer::postInstall
Created `config/app.php` file
Created `/vagrant/cake/tmp/cache/views` directory

# yを入力
Set Folder Permissions ? (Default to Y) [Y,n]? y
Permissions set on /vagrant/cake/tmp/cache
Permissions set on /vagrant/cake/tmp/cache/models
Permissions set on /vagrant/cake/tmp/cache/persistent
Permissions set on /vagrant/cake/tmp/cache/views
Permissions set on /vagrant/cake/tmp/sessions
Permissions set on /vagrant/cake/tmp/tests
Permissions set on /vagrant/cake/tmp
Permissions set on /vagrant/cake/logs
Updated Security.salt value in config/app.php

完了。

Vagrantfileの修正

ホストOS
$vi Vagrantfile

# Vagrantfileに以下追記
config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
config.vm.network "private_network", ip: "192.168.33.10"
config.vm.synced_folder "[ホストOSのVagrantfileが置いてあるパス]", "/vagrant(マウント先)",owner: 'vagrant', group: 'apache', mount_options: ['dmode=777', 'fmode=777']  

# リロードして再度ssh接続
$vagrant reload
$vagrant ssh

httpd.confファイルの修正

ゲストOS
$sudo -s
$vi /etc/httpd/conf/httpd.conf

# Documentrootの変更

# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
- DocumentRoot "/var/www/html"
+ DocumentRoot "/vagrant/[プロジェクト名]/webroot"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>


# アクセスを許可する

# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
+   AllowOverride All
-   AllowOverride None  
+   Require all granted
-   Require all denied
</Directory>

DBのDriverを編集(CakePHP内)

CakePHPでは初期のDBのドライバーがmysqlとなっているため、
Postgresqlに書き換える。

[プロジェクト]/config/app.php

   'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
-           'driver' => 'Cake\Database\Driver\Mysql',   
+           'driver' => 'Cake\Database\Driver\Postgres',        
            'persistent' => false,
            'host' => 'localhost',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',
            'username' => 'my_app',
            'password' => 'secret',
            'database' => 'my_app',
            /*
             * You do not need to set this flag to use full utf-8 encoding (internal default since CakePHP 3.6).
             */
            //'encoding' => 'utf8mb4',
            'timezone' => 'UTC',
            'flags' => [],
            'cacheMetadata' => true,
            'log' => false,


       'test' => [
            'className' => 'Cake\Database\Connection',
-           'driver' => 'Cake\Database\Driver\Mysql',   
+           'driver' => 'Cake\Database\Driver\Postgres',
            'persistent' => false,
            'host' => 'localhost',
            //'port' => 'non_standard_port_number',
            'username' => 'my_app',
            'password' => 'secret',
            'database' => 'test_myapp',
            //'encoding' => 'utf8mb4',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
            'log' => false,
            //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
            'url' => env('DATABASE_TEST_URL', null),
        ],
    ],

/vagrant に管理者権限をつける (曖昧です、要らないかも)

$chmod 777 -R /vagrant

Apacheサーバーへアクセス

# firewallを停止
$sudo systemctl disable firewalld

http://192.168.33.10/ へアクセスし、Cakeの画面が出たら完了!
スクリーンショット 2019-06-06 17.40.11.png

まだDBの設定をしていないため、Databaseが×になっていますが、後ほど追記 or 別の記事で書きます。

参考

homesteadやphp-brewを使うことによって、環境構築が楽になるそうです。
homestead:https://readouble.com/laravel/5.1/ja/homestead.html
php-brew:https://github.com/phpbrew/phpbrew/blob/develop/README.md

3
3
1

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?