備忘録

CentOS7にMySQL公式リポジトリを使って最新のMySQL8.0をインストール

CentOS7ではMariaDBが標準になっているので、MySQLを利用する場合はMySQL公式リポジトリを使ってMySQL8.0をインストールします

MariaDBはMySQLと互換性がありますが、どちらもインストールすると競合を起こすため、MySQLを使用する場合はMariaDBをアンインストールする必要があります。

MariaDBがすでにインストールされていたら削除

MariaDBインストール確認

# yum list installed | grep mariadb

MariaDBの停止

# systemctl stop mariadb.service

MariaDBの削除

# yum remove mariadb-*
# rm -rf /var/lib/mysql/

MySQL公式リポジトリの追加

最新のMySQLは下記サイトで確認

Download MySQL Yum Repository(https://dev.mysql.com/downloads/repo/yum/)

Red Hat Enterprise Linux 7 / Oracle Linux 7
(Architecture Independent), RPM Package
(mysql80-community-release-el7-3.noarch.rpm)
# yum install https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm

MySQL公式リポジトリの無効化

MySQL公式リポジトリは、インストールすると有効化の状態になっています。必要な時だけMySQL公式リポジトリを使いたいので無効化にします。

/etc/yum.repos.d/mysql-community.repo

enabled=1
↓
enabled=0

MySQL公式リポジトリを無効化にしたので、使用する時は「--enablerepo=ius」といったように明示的に実行します。

最新のMySQLをインストール

# yum --enablerepo=mysql80-community install mysql-community-server

インストールが完了したらバージョンを確認

# mysqld --version

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

MySQLを起動

# systemctl start mysqld.service

MySQLの自動起動の設定

# systemctl enable mysqld.service

初期パスワードの確認

mysql_secure_installation実行時に使うのでメモしておきます

# grep password /var/log/mysqld.log
9999-99-99T09:09:09.999999Z 9 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: 〇〇〇〇〇〇

※〇〇〇〇〇〇の部分がパスワードです。

新しいパスワードの準備

パスワード長 8文字以上
大文字小文字 1文字以上
数字 1文字以上
記号 1文字以上

例)mySql-888

MySQL初期設定(mysql_secure_installation)

  • rootパスワードの変更
  • validate_passwordコンポーネントのインストール
  • validate_passwordコンポーネントインストール後のrootパスワードの設定
  • anonymousユーザの削除
  • rootでのログインをlocalhostに制限
  • test用のデータベースの削除
# mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root: [初期パスワードを入力][Enter]

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

New password: [新しいパスワードを入力][Enter]

Re-enter new password: [再度、新しいパスワードを入力][Enter]
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を入力][Enter]

New password: [新しいパスワードを入力][Enter]

Re-enter new password: [再度、新しいパスワードを入力][Enter]

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を入力][Enter]
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を入力][Enter]
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を入力][Enter]
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を入力][Enter]
 - 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を入力][Enter]
Success.

All done!

my.cnfの設定

/etc/my.cnf

変更前にバックアップ

# cp -p /etc/my.cnf /etc/my.cnf_`date "+%Y%m%d%H%M%S"`
[mysqld]
user = mysql
port = 3306

socket = /var/lib/mysql/mysql.sock
pid-file = /var/run/mysqld/mysqld.pid
default_authentication_plugin = mysql_native_password
default_password_lifetime = 0
datadir = /var/lib/mysql
log-error = /var/log/mysql/mysql.log
binlog_expire_logs_seconds=864000 #10days

### utf8
#character_set_server = utf8
#collation_server = utf8_bin
#init_connect = 'SET NAMES utf8'
#skip-character-set-client-handshake

### utf8mb4
character_set_server = utf8mb4
collation_server = utf8mb4_bin
init_connect = 'SET NAMES utf8mb4'
skip-character-set-client-handshake

skip-name-resolve
#symbolic-links = 0
default-storage-engine = innodb
#sql_mode = ''
explicit_defaults_for_timestamp = true

wait_timeout = 300
max_connections = 100
table_open_cache = 1000
table_definition_cache = 500
open_files_limit = 1400

max_allowed_packet = 16M

### InnoDB
#innodb_file_per_table
#innodb_file_format = Barracuda
#innodb_file_format_max = Barracuda
#innodb_large_prefix = 1

slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2.0
min_examined_row_limit = 1000
log-queries-not-using-indexes

[mysql.server]
#default-character-set = utf8
default-character-set = utf8mb4

[mysqld_safe]
#default-character-set = utf8
default-character-set = utf8mb4

[mysql]
#default-character-set = utf8
default-character-set = utf8mb4

[client]
#default-character-set = utf8
default-character-set = utf8mb4

[mysqldump]
#default-character-set = utf8
default-character-set = utf8mb4

ログの出力先

ログの出力先を変更したのでディレクトリを作成

# mkdir /var/log/mysql
# chown -R mysql:mysql /var/log/mysql

MySQLを再起動

# systemctl restart mysqld.service

データベース・ユーザ・テーブルの作成(削除)

MySQLにrootでログイン

# mysql -u root -p

Enter password: [パスワード入力][Enter]

データベースの作成

CREATE DATABASE IF NOT EXISTS [データベース名];
 又は
CREATE DATABASE IF NOT EXISTS [データベース名] CHARACTER SET [文字コード] COLLATE [照合順序];

mysql> CREATE DATABASE IF NOT EXISTS test_db CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

データベースの一覧

mysql> SHOW DATABASES;

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test_db            |
+--------------------+

データベースの削除

DROP DATABASE [データベース名];

mysql> DROP DATABASE test_db;

ユーザの作成

常にrootユーザ使うのは、権限が強すぎてセキュリティ上よくないので、作業ユーザを作成します。

CREATE USER IF NOT EXISTS [ユーザ名]@[ホスト名] IDENTIFIED BY [パスワード];

mysql> CREATE USER IF NOT EXISTS 'test_user'@'localhost' IDENTIFIED BY 'testPassword-888';

ユーザの一覧

mysql> SELECT user, host FROM mysql.user;

+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
| test_user        | localhost |
+------------------+-----------+

ユーザに権限を設定

GRANT [権限] ON [データベース名].[対象のテーブル名] TO [ユーザ名]@[ホスト名];

mysql> GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES ON test_db.* TO 'test_user'@'localhost';

権限の確認

SHOW GRANTS FOR [ユーザ名]@[ホスト名];

mysql> SHOW GRANTS FOR 'test_user'@'localhost';

+-----------------------------------------------------------------------------------------------------+
| Grants for test_user@localhost                                                                      |
+-----------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `test_user`@`localhost`                                                       |
| GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES ON `test_db`.* TO `test_user`@`localhost` |
+-----------------------------------------------------------------------------------------------------+

権限の削除

REVOKE [権限] ON [データベース名].[対象のテーブル名] FROM [ユーザ名]@[ホスト名];
mysql> REVOKE DROP ON test_db.* FROM 'test_user'@'localhost';

パスワードの変更

ALTER USER [ユーザ名]@[ホスト名] IDENTIFIED BY [パスワード];

mysql> ALTER USER 'test_user'@'localhost' IDENTIFIED BY 'testPassword-999';

ユーザの削除

DROP USER [ユーザ名]@[ホスト名];

mysql> DROP USER 'test_user'@'localhost';

認証プラグインの確認

mysql> SELECT user, host, plugin FROM mysql.user;
+------------------+-----------+-----------------------+
| user             | host      | plugin                |
+------------------+-----------+-----------------------+
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session    | localhost | caching_sha2_password |
| mysql.sys        | localhost | caching_sha2_password |
| root             | localhost | caching_sha2_password |
| test_user        | localhost | mysql_native_password |
+------------------+-----------+-----------------------+

※認証プラグインが「caching_sha2_password」の場合は「phpMyAdmin」等から接続できない場合があります。

テーブルの作成

mysql> USE test_db;

mysql> CREATE TABLE test_table ( id INT, name VARCHAR(255) );

テーブルの一覧

mysql> SHOW TABLES;

+-------------------+
| Tables_in_test_db |
+-------------------+
| test_table        |
+-------------------+

テーブルの削除

mysql> DROP TABLE test_table;

MySQlの主なコマンド

状態確認
# systemctl status mysqld.service

起動
# systemctl start mysqld.service

停止
# systemctl stop mysqld.service

再起動
# systemctl restart mysqld.service

自動起動設定状態の確認
# systemctl is-enabled mysqld.service

自動起動設定
# systemctl enable mysqld.service

自動起動解除
# systemctl disable mysqld.service