MySQLのこと。

MySQLのことについてまとめているブログ。他人に見せる用でもなく、自分の勉強備忘録。検索インデックスも外してるので、辿りついた方・・・ようこそ。そんな大した情報ないですよ?!たまにアルゴリズムの練習も

CentOSにMySQLとPostgres環境の構築

はじめに

ここではMacOSの環境からVPS内のCentOSに、MySQLとPostgres環境の構築をする手順をまとめておく。

SSH接続

まずはサーバーに下記の通りSSHでログインを行う。

ssh root@***.***.**.***
password: **********
SAKURA Internet [Virtual Private Server SERVICE]

CentOSの初期設定

ソフトウェアをアップデート

yum updateでアップデートを行う。

# yum update

【略】

completed!

言語の変更

最終行に下記を追加すればOK。

# vim ~/.bash_profile

LANG=ja_JP.UTF-8
export LANG

日付の表記を確認する。

# date
2020年  5月 16日 土曜日 14:18:17 JST

ユーザー作成

SSHでログインするためのユーザー作成を行う。

# adduser user01
# passwd user01 
新しいパスワード:
新しいパスワードを再入力してください:
passwd: すべての認証トークンが正しく更新できました。

user01sudoを使えるように権限を付与する。下記のブロッグがコメントアウトされていたら修正する。/wheelで検索すると移動できる。

# visudo

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

user01wheelに入れる。これでsudoが使える。

# usermod -aG wheel user01
# groups user01
user01 : user01 wheel

SSH公開鍵認証

SSH公開鍵認証の設定

SSH公開鍵認証の設定を行う。まずはローカル環境のMacOSで鍵を生成する。

ssh-keygen -t rsa -v
パスワードをつける

The key's randomart image is:
+---[RSA 3072]----+
【略】
+----[SHA256]-----+

id_rsa秘密鍵でローカルに置いておき、認証情報として利用する。id_rsa.pubは公開鍵で、サーバーに配置する。

$ ls ~/.ssh
id_rsa      id_rsa.pub

公開鍵をサーバーに送信するために、サーバーにディレクトリを作る。

$ ssh user01@<ip>
$ pwd
/home/user01

$ mkdir .ssh
$ chmod 700 .ssh
$ ls -la | grep .ssh
drwx------  2 user01 user01 4096  5月 16 14:32 .ssh
$exit

ローカル環境からscpコマンドで公開鍵を送信する。

scp ~/.ssh/id_rsa.pub user01@<server ip>:~/.ssh/authorized_keys
user01@153.127.44.173's password: 
id_rsa.pub                                             100%  580    13.0KB/s   00:00   

ではSSH公開鍵を使ってローカルからログインする。ログインができている。

# id_rsaという名前であれば下記でよい
# ssh  user01@<server ip>
$ ssh -i ~/.ssh/id_rsa user01@<server ip>
Enter passphrase for key '/Users/***/.ssh/id_rsa': 

$ cat /etc/redhat-release 
CentOS Linux release 7.8.2003 (Core) 

セキュリティの設定

Portブロックのコメントアウトを解除し、ポート番号をかえる。SSHサーバーのデフォルトは22番。/Portなどで検索。

$ sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.org
$ sudo vim /etc/ssh/sshd_config

# デフォルトのポート番号設定は変更する。
Port <port no>

# パスワード認証を禁止
PasswordAuthentication no

# 空白パスの禁止
PermitEmptyPasswords no

# rootログインの禁止
PermitRootLogin no

確認を行う。エラーが出ないのでOK。再起動しておく。再起動を忘れるとfirewallいじってログアウトして入れなくなる。

$ sudo sshd -t

$ sudo systemctl restart sshd

firewallの設定

ポートの番号を変更したので、その番号でアクセスできるように変更する。デフォルトでは22番は有効の状態。

$ sudo cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/ssh-<port no>.xml
$ sudo vim /etc/firewalld/services/ssh-<port no>.xml

ポートの番号を22から変更する。

<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>SSH</short>
  <description>【略</description>
  <port protocol="tcp" port="<port no>"/>
</service>

firewallがそもそも起動していないので、起動させる。設定をリロードしておく。

$ systemctl start firewalld

==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to manage system services or units.
Authenticating as: user01
Password: *****

$ systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: active (running) since 土 2020-05-16 15:01:48 JST; 4s ago
     Docs: man:firewalld(1)

$ sudo firewall-cmd --reload
success

$ sudo firewall-cmd --permanent --add-service=ssh-<port no>
success

$ sudo firewall-cmd --reload
success

サーバ起動時に自動でfirewallが起動するよう設定。

$ systemctl enable firewalld
パスワード:****

firewallの設定を確認しておく。servicesに指定したポートのxmlがある。

$ sudo firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources: 
  services: dhcpv6-client ssh ssh-<port no> #ここに指定したポートがある。
  ports: 
  protocols: 
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 

この状態でローカルからsshでポートを指定してログインできる。

# ssh -p<port no > user01@<ip>でもよい
$ ssh -p<port no > -i ~/.ssh/id_rsa user01@<ip>

不要になった22番ポートのfirewall設定を削除する。servicessshが22番の設定。

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

削除する。

$ sudo firewall-cmd --permanent --remove-service=ssh
success
    
$ sudo firewall-cmd --reload
success

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

MySQLの環境構築

インストール

MariaDBを削除しておく。

$ sudo yum remove mariadb-libs
$ sudo rm -rf /var/lib/mysql

MySQLも消しておく。

$ sudo yum remove mysql-server mysql-devel
$ sudo rm -rf /var/lib/mysql

MySQLのバージョンを確認。ここではMySQL8.0.2をインストールする。

$ sudo rpm -ivh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
$ sudo yum info mysql-community-server
【略】
バージョン          : 8.0.20

$ sudo yum install mysql-community-server
【略】
完了しました!

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

MySQLを起動する。初期パスワードを使って、初期設定を行う。

$ systemctl start mysqld.service
$ sudo cat /var/log/mysqld.log | grep 'temporary password'
2020-05-16T07:05:35.094594Z 6 [Note] [MY-010454] [Server] 
A temporary password is generated for root@localhost: s%FfdhlFu3nS

$ mysql_secure_installation
Securing the MySQL server deployment.
Enter password for user root: s%FfdhlFu3nS # 初期パスワード
The existing password for the user account root has expired. Please set a new password.

Change the password for root ? ((Press y|Y for Yes, any other key for No) : y
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y

All done! 

MySQLにログインする。

$ mysql -u root -p

Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.20 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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)

MySQLの環境設定

デフォルト文字コードをUTF8にする。my.cnfの最下部に書きを追加。

$ sudo vim /etc/my.cnf

character-set-server=utf8
default_authentication_plugin=mysql_native_password 

設定をリロードするためにMysqlを再起動し、Mysqlを自動で起動するようにする。

$ systemctl restart mysqld.service
$ sudo systemctl enable mysqld
$ systemctl list-unit-files -t service | grep mysql
mysqld.service                                enabled # 自動起動
mysqld@.service                               disabled

確認。

$ ps aux | grep mysql
user01    3478  0.0  0.0 112824   968 pts/2    S+   16:19   0:00 grep --color=auto mysql
mysql    19618  0.5 32.3 1772856 328364 ?      Ssl  16:15   0:01 /usr/sbin/mysqld

テストデータベースを作成

ここでは、テスト用のデータベースを作成する。毎日60秒間隔で自動インサートされるテーブルを作る。まずはイベントスケジュールをONにする。

mysql> SET GLOBAL event_scheduler = ON;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW variables like 'event%';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| event_scheduler | ON    |
+-----------------+-------+
1 row in set (0.00 sec)

event_auto_insertというデータベースを作成する。

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

mysql> use event_auto_insert;
Database changed

テーブル名はlogsにする。適当に60秒ごとにタイムスタンプと値、フラグを生成するようなテーブルを設定。

mysql> 
CREATE TABLE event_auto_insert.logs (
   id INT AUTO_INCREMENT,
    datetime DATETIME NOT NULL,
    value1 INT NOT NULL,
    value2 INT NOT NULL,
    category varchar(1) NOT NULL,
    flg INT NOT NULL,
    PRIMARY KEY (id)
);

ではイベントlogsを作成する。イベントを削除する時は、DROP EVENT logs;で削除。

create event logs
    on schedule every 60 SECOND
    starts now()
    do INSERT INTO event_auto_insert.logs(datetime, value1, value2, category, flg) VALUES (
     NOW(),
     CASE WHEN MONTH(NOW()) IN (1,2,3) THEN FLOOR(RAND() * (100 * -1))
     WHEN MONTH(NOW()) IN (4,5,6) THEN FLOOR(RAND() * (10 * -2))
     WHEN MONTH(NOW()) IN (7,8,9) THEN FLOOR(RAND() * (100 * 1))
     ELSE FLOOR(RAND() * (10 * 2)) END,
     FLOOR(RAND() * 100),
     SUBSTRING(MD5(RAND()), 1, 1),
     floor(rand() * 2)
     );
Query OK, 0 rows affected (0.00 sec)

こんなかんじ。データの自動連携とかで検証用に使いたいのでこんな感じで履歴を残すようなテーブル。

select * from event_auto_insert.logs;
+----+---------------------+--------+--------+----------+-----+
| id | datetime            | value1 | value2 | category | flg |
+----+---------------------+--------+--------+----------+-----+
|  1 | 2020-05-17 04:36:33 |     -8 |      8 | 0        |   0 |
+----+---------------------+--------+--------+----------+-----+
1 row in set (0.00 sec)

MySQL WorkBenchで外部サーバへSSHを通して接続する方法しかうまくいかなかった。さくらのVPSが関係しているのか・・・外部接続がうまくいかないので、この方法。

f:id:AZUMINO:20200517043558p:plain

f:id:AZUMINO:20200517043849p:plain

Postgres

工事中