お金をかけずにサーバーの勉強をしよう

MySQLインストール

2024年5月7日

メニューへ戻る

MySQLでデータベースサーバーを作り、リレーショナルデータベースを味わいます。

このデータベースは OSS出身で、サンマイクロシステムズに買われてから、Oracleがサンマイクロシステムズを買ったので、現在は 世界有数のデータベース商品を抱える Oracle社のプロダクトということになります。

サンマイクロシステムズが Oracleに買われたことで MySQLの存続も危ぶまれましたが、現在では MySQL独自の進化を続けながら 1つの会社の中で Oracle Databaseとの共存しています。

OSSの DBとしては、PostgreSQLと人気を二分していますが、AWSでも Azureでも MySQLの DaaSがあることもあり、しばらく無くなることはないと思います。
依然として人気の高いデータベースです。

本家サイトはこちらです。
MySQL

2024年4月末に久しぶりに LTS(Long Term Support)版の最新版である 8.4 が出ました。
今後しばらくはこのバージョンが MySQLの基幹バージョンになるのでしょう。

では早速インストールしてみましょう。


1.環境

以下の構成でいきます。


2.Ubuntuの MySQLパッケージ調査

Ubuntu 24.04の snapと aptのリポジトリには MySQLがあるのか、まず確認してみます。

snapのほう。

subro@UbuntuServer2404-2:~$ snap info mysql
name:      mysql
summary:   Experimental MySQL Community snap
publisher: Canonical Data Platform (dataplatformbot)
store-url: https://snapcraft.io/mysql
contact:   lars.tangvald@oracle.com
license:   GPL-2.0
description: |
  MySQL Snap Contains the minimal set of binaries needed for the MySQL server and client. This is
  meant as a way to try out MySQL with Snappy, and is not to be considered ready for production
  environments. Before running, the process control interface must be connected with the command
  «snap connect mysql:process-control»
snap-id: YNxM22tkUrmu4YHhBt9PShBj7DwKojxp
channels:
  latest/stable:    –
  latest/candidate: –
  latest/beta:      5.7.17    2017-05-17 (3) 17MB -
  latest/edge:      8.0.0-dmr 2017-05-17 (4) 18MB -
  8.0/stable:       –
  8.0/candidate:    –
  8.0/beta:         8.0.0-dmr 2017-05-17 (4) 18MB -
  8.0/edge:         ↑
  5.7/stable:       –
  5.7/candidate:    –
  5.7/beta:         5.7.17    2017-05-17 (3) 17MB -
  5.7/edge:         ↑

MySQLはありますけど、まだ前の LTSの 8.0 ですね。

aptのほう。

subro@UbuntuServer2404-2:~$ apt search mysql
〜〜〜 省略 〜〜〜
mysql-server-8.0/noble 8.0.36-2ubuntu3 amd64
  MySQL database server binaries and system database setup
〜〜〜 省略 〜〜〜

こちらも 8.0 でした。

流石にまだ早過ぎて Canonicalもパッケージ化してないんでしょう。
しかし私は 8.4 を味わいたいのです。


3.MySQLのリポジトリを登録する

Ubuntuのリポジトリにいずれはパッケージが入ってくるんでしょうからそれまでのしのぎではありますが、MySQLのリポジトリから取得する方針にします。

ダウンロードはこちらから。
MySQL Community Server 8.4.0 LTS

上のリンク先に行くと deb形式のパッケージファイルを含むインストール用のバイナリファイルを何種類かダウンロードできるんですが、[Select Operating System:] に [Ubuntu Linux] を選んでやりますと、ペンギンの絵が出てきます。

この絵が MySQLリポジトリ登録用 deb形式バイナリパッケージファイルダウンロードへのリンクになっていますのでこれをクリックします。
MySQLダウンロードサイト 1

Downloadを押します。
MySQLダウンロードサイト 2

このダウンロードには Oracleのアカウントが必要で、アカウント/パスワードの入力画面になります。

Oracleのアカウントを持っていない人は無料で作れます。
もし Oracle Databaseや MySQLをこれからやっていこうと思う人は作っておいたほうが良いと思います。
(私は Javaの資格を取るときも使いましたので)

ダウンロードが完了すると [mysql-apt-config_0.8.30-1_all.deb]ファイルができました。

私は Lubuntuの Firefoxでダウンロードしたので、scpコマンドで Ubuntu Serverに持っていきました。

Ubuntu Serverでパッケージを実行して MySQLのリポジトリを OSに登録します。

subro@UbuntuServer2404-2:~$ sudo apt install -y ./mysql-apt-config_0.8.30-1_all.deb
〜〜〜 省略 〜〜〜

バージョンによっていリポジトリの URLが違うんでしょうね。
この画面になって選択するリポジトリのカスタマイズができるようになっていますが、8.4 を入れるには何も変えずに キーで [OK] を選択し、Enterキーを押します。
MySQLリポジトリインストール

何故かわかりませんが、同じ事をもう 1回やって、特に問題なくインストールできました。

OSへの登録は [/etc/apt/sources.list.d/mysql.list]ファイルが実体です。
内容はこうなっていました。

### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out entries below, but any other modifications may be lost.
# Use command 'dpkg-reconfigure mysql-apt-config' as root for modifications.
deb [signed-by=/usr/share/keyrings/mysql-apt-config.gpg] http://repo.mysql.com/apt/ubuntu/ noble mysql-apt-config
deb [signed-by=/usr/share/keyrings/mysql-apt-config.gpg] http://repo.mysql.com/apt/ubuntu/ noble mysql-8.4-lts
deb [signed-by=/usr/share/keyrings/mysql-apt-config.gpg] http://repo.mysql.com/apt/ubuntu/ noble mysql-tools
#deb [signed-by=/usr/share/keyrings/mysql-apt-config.gpg] http://repo.mysql.com/apt/ubuntu/ noble mysql-tools-preview
deb-src [signed-by=/usr/share/keyrings/mysql-apt-config.gpg] http://repo.mysql.com/apt/ubuntu/ noble mysql-8.4-lts

新規リポジトリが追加されましたので、パッケージ情報を取得します。

subro@UbuntuServer2404-2:~$ sudo apt update
取得:1 http://repo.mysql.com/apt/ubuntu noble InRelease [22.6 kB]
取得:2 http://repo.mysql.com/apt/ubuntu noble/mysql-8.4-lts amd64 Packages [16.8 kB]
取得:3 http://repo.mysql.com/apt/ubuntu noble/mysql-tools amd64 Packages [4,125 B]
ヒット:4 http://security.ubuntu.com/ubuntu noble-security InRelease
ヒット:5 http://jp.archive.ubuntu.com/ubuntu noble InRelease
ヒット:6 http://jp.archive.ubuntu.com/ubuntu noble-updates InRelease
ヒット:7 http://jp.archive.ubuntu.com/ubuntu noble-backports InRelease
43.6 kB を 1秒 で取得しました (39.4 kB/s)
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています... 完了
状態情報を読み取っています... 完了
アップグレードできるパッケージが 1 個あります。表示するには 'apt list --upgradable' を実行してください。

これで MySQLリポジトリの登録は OKです。


4.インストール

改めて MySQLのパッケージを調べます。

subro@UbuntuServer2404-2:~$ sudo apt search mysql
mysql-community-client/不明,now 8.4.0-1ubuntu24.04 amd64
  MySQL Client

mysql-community-server/不明,now 8.4.0-1ubuntu24.04 amd64
  MySQL Server

mysql-shell/不明 8.4.0-1ubuntu24.04 amd64
  MySQL Shell (part of MySQL Server) 8.0

一杯出てきますが「これがインストール対象だろう」ってものだけ書いて他は省略しています。

MySQL Shellは馴染みのない方もいらっしゃると思いますが、Oracle社は従来の mysqlコマンドよりこちらに移行したそうなので、これも入れておいた方が良いでしょう。

上の 3つのパッケージをインストールします。

subro@UbuntuServer2404-2:~$ sudo apt -y install mysql-community-server mysql-community-client mysql-shell
〜〜〜 いっぱい出るので省略 〜〜〜

途中でこのように MySQLの [root]ユーザーの初期パスワード設定を促されます。
8.0の頃はこれは無かった気がします。
結構強いパスワードを設定し、TABキーを押して [<了解>] を選択し、Enterキーを押します。
MySQLインストール 1
もう一回確認のためにパスワード入力を促されますので、同様に処理してください。

パスワードの強度をどう設定するかの選択です。
f古い MySQLとの互換性が必要なら [Use Legacy 〜] ですが、
デフォルトの [Use Strong 〜]にします。
このまま Enterキーを押します。
MySQLインストール 2

しばらくしてインストールを完了できました。


5.初期化

MySQLの初期化という作業をします。

主にセキュリティ関連の初期セッティングになります。
ここからは OSのユーザーと MySQLのユーザーを混同しないように気をつけて下さい。

subro@UbuntuServer2404-2:~$ sudo mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root:**********  ← インストール時に設定した MySQLの[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?

十分にセキュアなパスワードになっているかをチェックする VALIDATE PASSWORD を設定するか聞いています。
Press y|Y for Yes, any other key for No: y

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

3段階種類あるパスワード強度から選ぶように聞いています。
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0  ← 検証ではタルいので[LOW]にしました。
Using existing password for root.

Estimated strength of the password: 100   ← MySQLの[root]ユーザーのパスワード強度が100のようです。(多分100が最高)
MySQLの[root]ユーザーのパスワードを変えるか聞いています。
Change the password for root ? ((Press y|Y for Yes, any other key for No) : n

 ... skipping.
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.

リモートノードから MySQLの[roo]tユーザーでアクセスを拒否するか聞いています。
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.

インストール時のデフォルトで作られる[test]データベースを消すか聞いています。
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!

初期化が完了しました。
これで環境構築が完了しました。


6.データベース作成

[subrotest]データベースを作ります。

MySQLの [root]ユーザーでログインします。

subro@UbuntuServer2404-2:~$ mysql -u root -p
Enter password: MySQLの[root]ユーザーのパスワードを入れる
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 8.4.0 MySQL Community Server - GPL

Copyright (c) 2000, 2024, 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>

ログインできました。
「mysql> 」が MySQLのコマンドプロンプトで、SQL文を入れたりする所になります。

既に存在しているデータベースを一覧してみます。

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

システム用のデータベースしかありません。
ではデータベースを作成します。

mysql> create database subrotest;
Query OK, 1 row affected (0.00 sec)

データベースができました。

データベース一覧を表示します。

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| subrotest          | ← できました。
| sys                |
+--------------------+
5 rows in set (0.00 sec)

[subrotest]データベースができましたので、この中に [subrotesttable]テーブルを作ります。

まず使用するデータベースを選択します。

mysql> use subrotest;
Database changed

[subrotest]データベースを選択できました。

[subrotesttable]テーブルを作ります。

mysql> create table subrotesttable ( name char(50) );
Query OK, 0 rows affected (0.01 sec)

固定長 50文字の [name]カラムを持たせました。

データを挿入してみましょう。

mysql> insert into subrotesttable values('Tanaka');
Query OK, 1 row affected (0.01 sec)

mysql> select * from subrotesttable;
+--------+
| name   |
+--------+
| Tanaka |
+--------+
1 row in set (0.00 sec)

うん、まぁリレーショナルデータベースですね。

この素の状態(MySQLの [root]ユーザーしかいない)だと他の PCなどからログインできませんし、最高権限ユーザーで全てを行わせるのはセキュリティ上はよくありませんので、MySQLの [subromysql]一般ユーザーを作成します。

mysql> create user 'subromysql'@'%' identified by 'mkd92t-jk';
Query OK, 0 rows affected (0.01 sec)

ユーザーが作成されました。
「mkd92t-jk」がパスワードです。(パスワードの複雑性をクリアしています)

[subromysql]ユーザーを作るのに「'subromysql'@'%'」と記述しています。

これは何かというと、書式的には 'ユーザー名'@'ホスト名(またはIPアドレス)' となっていて、どのホスト(IPアドレス)からのログインを許可するかをユーザー名で設定できるのです。
「%」はワイルドカードで、「どのホストからも OK」という意味になります。

最後に [subromysql@%]ユーザーに、[subrotest]データベースに対する操作の全権限を付与します。
[subromysql@%]ユーザーが、[subrotest]データベースの管理者のイメージですね。

mysql> grant all on subrotest.* to 'subromysql'@'%' with grant option;
Query OK, 0 rows affected (0.00 sec)
all全権
subrotest.*[subrotest]データベースの何もかも
with grant option他のユーザーにも権限委譲できる権限を持たせる

一般ユーザーの設定はこれで OKです。

試しに外部ノード(別な Ubuntu Server 24.04)で MySQL 8.0の mysqlコマンドを使い、 [subromysql]ユーザーでログインしてみました。

subro@UbuntuServer2404-1:~$ mysql -u subromysql -h UbuntuServer2404-2 -p
Enter password: MySQLの[subromysql]ユーザーのパスワード(mkd92t-jk)を入れる
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 8.4.0 MySQL Community Server - GPL

Copyright (c) 2000, 2024, 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> use subrotest;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select * from subrotesttable;
+--------+
| name   |
+--------+
| Tanaka |
+--------+
1 row in set (0.00 sec)

ログインして SELECT文も実行できています。
どうやら良さげです。\(^o^)/


==========
ここから先はリレーショナルデータベース(RDB)の果てしない世界が広がっています。

RDBの使い方や SQLの書き方はのお勉強につき、書籍を 1冊は欲しいところです。

まずは RDBを使えるようになるところから始め、その後にバックアップ/リカバリなど、個々の製品特有のスキルを身に着けましょう。

とりあえずここで書いた通りの事ができれば、他のミドルウェアで RDBをデータストレージとして活用するものの構築のお勉強に進むことができるでしょう。

その意味ではデータベースってインフラなんですよね。


当然ながらいずれの本も 8.4には対応していませんけど、基礎は同じですので十分に活用できると思います。