概要

Webアプリのお供であるDBを入れます。

環境

  • Ubuntu 26.04

※ローカル運用で実施。いわゆるLAMP環境のため、他のサーバがDBを見に行くことはないという想定です。

さっくりとした手順

  1. パッケージのアップデートを行います。
  2. MySQLをインストールします。
  3. MySQLのrootパスワードを設定します。
  4. mysql_secure_installationにより安全性を高めます。

パッケージのアップデート

sudo aptitude update

筆者の好みでaptitudeを用いています。必要に応じてaptを使ってください。

MySQLインストール

  • パッケージでインストール
sudo aptitude install mysql-server
  • インストール確認
systemctl status mysql

active(running)を確認します。

MySQL設定変更について

MySQL 8.4以降では、長年使われてきた古い認証方式(mysql_native_password)がデフォルトで無効化され、よりセキュアな caching_sha2_password が標準となっています。そのため、設定ファイル(mysqld.cnf)を書き換えて旧プラグインを強制する手順は不要となり、標準の認証方式のまま初期設定を進めます。

また、近年のバージョンではインストール直後の初期セキュリティが強化されていますが、mysql_secure_installation は以下の重要な役割を持つため実行します。

  • パスワード検証コンポーネント(VALIDATE PASSWORD)の導入
  • 匿名ユーザーアカウントを削除
  • リモートからのrootユーザーのログインを無効化
  • testデータベースを削除し、testデータベースへのアクセス権限を持つユーザーを削除

mysql rootパスワード設定

sudo mysql

初期状態ではローカルソケット認証(auth_socket)のため、sudo経由でパスワードなしでログインできます。

ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'password';

''のpasswordは任意の、強固なものを入力ください。

標準推奨の caching_sha2_password を用いて強固なパスワードを設定します。

flush privileges;
exit

mysql_secure_installation

sudo mysql_secure_installation

質問事項

Enter password for user root: 
# 上記で設定したパスワードを入力します
​
VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?
​
Press y|Y for Yes, any other key for No:
# パスワード強度チェックを有効にするためYを入力してEnter
​
There are three levels of password validation policy:
​
LOW   Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
​
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:
# ポリシーに合わせて0/1/2を入力(ローカル開発環境なら0または1を推奨)
​
Estimated strength of the password: 50
Change the password for root ? ((Press y|Y for Yes, any other key for No) :
# 既に直前の手順でパスワードを設定済みのため、ここではnを選択します。
​
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) :
# anonymousユーザーを削除するためY
​
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) :
# rootユーザのリモートログインを禁止するためY
​
Remove test database and access to it? (Press y|Y for Yes, any other key for No) :
# テストDBを削除するためY
​
Reload privilege tables now? (Press y|Y for Yes, any other key for No) :
# 設定を反映するためY

以上でMySQLの初期設定は完了です。