2
5

More than 1 year has passed since last update.

CentOS7でLAMP環境構築 Linux, Apache, MariaDB(MySQL), PHP(Laravel / Composer)

Last updated at Posted at 2022-05-15

CentOS7上での基本的なLAMP環境の構築方法の備忘録。

開発環境

Windows11
VirtualBox 6.1.14
CentOS 7.9.2009
Apache 2.4.6
MySQL 8.0.29
PHP 8.0.19
Laravel 9.12.2
Composer 2.3.5
Git 2.9.5

新規ユーザーの設定

ユーザー追加
useradd [ユーザー名]

# useradd sakamoto

実行後に何も表示されませんが追加されています。

パスワード設定
passwd [ユーザー名]

# passwd sakamoto

Changing password for user sakamoto.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

ユーザー設定
sudo をパスワードなしで使用できるようにする。
/etc/sudoers のコメントを外す。

# vi /etc/sudoers

#Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

ユーザーをwheelグループに追加

# usermod -aG wheel sakamoto

ユーザーをrootからsakamotoへ変更

# su - sakamoto

rootへ変更したい時は

$ su

rootでの操作はなるべく行わず、一般ユーザーに権限を付与して開発していくのが基本。
管理者権限が必要なコマンドは$ sudo [コマンド]で実行する。

Apache導入

ひとまずyumを最新状態にアップデート

$ sudo yum update -y

Apache(httpd)のインストール

$ sudo yum install -y httpd

CentOS起動時にApacheが自動的に起動するように設定

$ sudo systemctl enable httpd
Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.

Apacheの起動(start)、停止(stop)、状態確認(status)
statusでActive: inactiveになっている場合はstartでactiveに

$ sudo systemctl start httpd
$

$ sudo systemctl stop httpd
$

$ sudo systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since 日 2022-05-15 22:13:47 JST; 1s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 24611 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
 Main PID: 24626 (httpd)
   Status: "Processing requests..."
   CGroup: /system.slice/httpd.service
           ├─24626 /usr/sbin/httpd -DFOREGROUND
           ├─24627 /usr/sbin/httpd -DFOREGROUND
           ├─24628 /usr/sbin/httpd -DFOREGROUND
           ├─24629 /usr/sbin/httpd -DFOREGROUND
           ├─24630 /usr/sbin/httpd -DFOREGROUND
           └─24631 /usr/sbin/httpd -DFOREGROUND

firewall-cmdで状態を確認

$ sudo firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: enp0s3
  sources:
  services: dhcpv6-client ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

servicesにhttpを追加

$ sudo firewall-cmd --add-service=http --permanent
success

再起動しないと設定が反映されないので--reloadで再起動

$ sudo firewall-cmd --reload
success

$ sudo firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: enp0s3
  sources:
  services: dhcpv6-client http ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

ここまでくればブラウザからApacheに接続できるはずなので
http://IPアドレス
に接続

IPアドレスはip aで確認できる

$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    (省略)
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    (省略)
    inet 192.168.11.33/24 brd 192.168.11.255 scope global noprefixroute dynamic enp0s3
    (省略)

私の場合は 192.168.11.33

これで接続するとApacheが用意しているテストページが表示される

MySQL導入

↓MySQL公式サイト参照
https://dev.mysql.com/doc/refman/5.6/ja/linux-installation-yum-repo.html

↓からOSに合ったリポジトリを選択する
https://dev.mysql.com/downloads/repo/yum/

http://dev.mysql.com/get/[リポジトリのファイル名(.rpm)]

MySQLのYumリポジトリを追加

$ sudo yum localinstall http://dev.mysql.com/get/mysql80-community-release-el7-6.noarch.rpm

リポジトリの確認
/etc/yum.repos.dmysql-community-source.repomysql-community.repoが追加されているか確認

$ cd /etc/yum.repos.d
$ ls
CentOS-Base.repo       CentOS-Media.repo    CentOS-fasttrack.repo           mysql-community-source.repo
CentOS-CR.repo         CentOS-Sources.repo  CentOS-x86_64-kernel.repo       mysql-community.repo
CentOS-Debuginfo.repo  CentOS-Vault.repo    mysql-community-debuginfo.repo

MySQLのインストールを実行

$ sudo yum install -y mysql-community-server

GPG 鍵の取得に失敗しました: [Errno 14] curl#37 - "Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql-2022"

新しいGPGキーをインストールすればよさそうなので下記コマンドでインポートして再度MySQLのインストールを実行

$ sudo rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022

$ sudo yum install -y mysql-community-server

MySQLがインストールできているか確認

$ mysqld --version
/usr/sbin/mysqld  Ver 8.0.29 for Linux on x86_64 (MySQL Community Server - GPL)

MySQLの起動と確認
start stop status enableなどで

$ systemctl start mysqld
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to manage system services or units.
Authenticating as: sakamoto
Password:
==== AUTHENTICATION COMPLETE ===
$ systemctl status mysqld
$ systemctl enable mysqld

MySQLの設定

MySQLのrootユーザーの初期パスワードを調べる

[sakamoto@localhost ~]$ sudo cat /var/log/mysqld.log | grep password
2022-05-15T13:54:35.158716Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: ,8-0yIg/w#ilG

↑の最後にある8-0yIg/w#ilGが初期パスワードです

MySQLの初期設定のために↓のコマンドを入力
root用の初期パスワードを入力して新しいパスワードの設定
※新パスワード設定時に
... Failed! Error: Your password does not satisfy the current policy requirements
とエラーが出た場合は、パスワードの要求事項を満たしていないので、英大文字、記号、数字を最低1つずつパスワードに入れましょう
他の質問にはyesでOKです

[sakamoto@localhost ~]$ sudo mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root:

The existing password for the user account root has expired. Please set a new password.

New password:

Re-enter new password:
 ... Failed! Error: Your password does not satisfy the current policy requirements

New password:

Re-enter new password:
The 'validate_password' component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.

Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

New password:

Re-enter new password:

Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

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


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

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

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


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

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

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

All done!

これでMySQLの初期設定はひとまず完了ですので試しにテーブルを見てみましょう

[sakamoto@localhost ~]$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 8.0.29 MySQL Community Server - GPL

Copyright (c) 2000, 2022, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

操作できるので特に問題なさそうです

PHP導入

今回はPHP8.0をインストールしていきます
参考サイト↓
https://php-junkie.net/env/php8/

デフォルトではyumにはPHP5.4しか入っていないのでRemiリポジトリを追加

[sakamoto@localhost ~]$ sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm

yumでインストールできるphp80系のパッケージを確認し、必要なものをインストール

[sakamoto@localhost ~]$ sudo yum -y install php80 php80-php php80-php-bcmath php80-php-json php80-php-mbstring php80-php-pdo php80-php-xml php80-php-mysqlnd --enablerepo=remi-php80

php80がインストールできたかを確認

[sakamoto@localhost ~]$ php80 -v
PHP 8.0.19 (cli) (built: May 10 2022 08:07:35) ( NTS gcc x86_64 )
Copyright (c) The PHP Group
Zend Engine v4.0.19, Copyright (c) Zend Technologies

※ちなみにphp -vではエラーになる

[sakamoto@localhost ~]$ php -v
-bash: php: コマンドが見つかりません

ので、phpコマンドでphp80を使えるようにする

[sakamoto@localhost ~]$ which php80
/usr/bin/php80

[sakamoto@localhost ~]$ sudo ln -sf /usr/bin/php80 /usr/bin/php

するとphp -vで認識

[sakamoto@localhost ~]$ php -v
PHP 8.0.19 (cli) (built: May 10 2022 08:07:35) ( NTS gcc x86_64 )
Copyright (c) The PHP Group
Zend Engine v4.0.19, Copyright (c) Zend Technologies

これでPHPのインストールは終了です
次にLaravelを使うためにComposerをインストールしましょう

Composer導入

基本的に公式ドキュメントどおりに進めていけば問題ありません

[sakamoto@localhost ~]$ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
[sakamoto@localhost ~]$ php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
Installer verified
[sakamoto@localhost ~]$ php composer-setup.php
All settings correct for using Composer
Downloading...

Composer (version 2.3.5) successfully installed to: /home/sakamoto/composer.phar
Use it: php composer.phar

[sakamoto@localhost ~]$ php -r "unlink('composer-setup.php');"
[sakamoto@localhost ~]$ sudo mv composer.phar /usr/local/bin/composer

インストールできているか確認

[sakamoto@localhost ~]$ composer
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 2.3.5 2022-04-13 16:43:00

Git導入

Laravelを使用する時のために最新のGitをインストールしておきましょう
yum install gitでもインストールできますが、最新版ではなくv1.8なので気をつけましょう

参考サイト↓
https://qiita.com/tomy0610/items/66e292f80aa1adc1161d

後々必要になるのでwgetをインストールしておきます

[sakamoto@localhost src]$ sudo yum install wget

依存関係のあるライブラリをインストール

[sakamoto@localhost ~]$ sudo yum -y install gcc curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-ExtUtils-MakeMaker autoconf

インストール場所に移動

[sakamoto@localhost ~]$ cd /usr/local/src/

下記リンクから目的のバージョンのGitファイルをダウンロード(今回は'git-htmldocs-2.36.1.tar.gz `)
https://mirrors.edge.kernel.org/pub/software/scm/git/

[sakamoto@localhost src]$ sudo wget https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.36.1.tar.gz

ダウンロードしたファイルを解凍

[sakamoto@localhost src]$ sudo tar xzvf git-2.36.1.tar.gz 

圧縮ファイルを削除

[sakamoto@localhost src]$ sudo rm -rf git-2.36.1.tar.gz 

解答したGitのディレクトリに移動してインストール

[sakamoto@localhost src]$ cd git-2.36.1
[sakamoto@localhost git-2.36.1]$ sudo make prefix=/usr/local all
[sakamoto@localhost git-2.36.1]$ sudo make prefix=/usr/local install

インストールできているか確認

[sakamoto@localhost git-2.36.1]$ git --version
git version 2.36.1

Laravel導入

必要になるのでzip unzipをyumインストール

[sakamoto@localhost ~]$ sudo yum install -y zip unzip

ComposerでLaravelライブラリを読み込む

[sakamoto@localhost ~]$ composer global require laravel/installer

Laravelプロジェクトの作成をしようとするとディレクトリの操作権限がないのでエラーが出る

[sakamoto@localhost html]$ composer create-project --prefer-dist laravel/laravel sample-laravel

In ProjectInstaller.php line 75:

  mkdir(): Permission denied

ディレクトリの権限をすべてのユーザーに与える

[sakamoto@localhost html]$ sudo chmod 777 /var/www/html

再度Laravelプロジェクトを作成

[sakamoto@localhost html]$ composer create-project --prefer-dist laravel/laravel sample-laravel
(省略)
Application key set successfully.

作成したプロジェクトのディレクトリへ移動して開発を続けていきましょう!

[sakamoto@localhost html]$ ls
sample-laravel

[sakamoto@localhost html]$ cd sample-laravel

MySQLとLaravelの連携

最後にvi .envでファイルを編集してDBとの連携を忘れずに!

※仮想サーバー内でCentOSを開発している場合:
php artisan serveでサーバーを立てて、ホストOSのブラウザでは確認できない?
ホストOSのVSCodeでSSH接続してサーバーを立てるとLaravelの初期画面が表示される?

2
5
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
2
5