Unable to load authentication plugin ‘caching_sha2_password’

Unable to load authentication plugin ‘caching_sha2_password’

 

Получили ли вы сообщение об ошибке unable to load authentication plugin ‘caching_sha2_password’ при попытке подключиться к экземпляру базы данных MySQL в контейнере Docker ?. Начиная с MySQL 8.0 плагин аутентификации по умолчанию был изменен на caching_sha2_password с mysql_native_password. Если вы используете более старый клиент MySQL, он может не подключиться к серверу базы данных с сообщением об ошибке “unable to load authentication plugin ‘caching_sha2_password’”.

Чтобы продемонстрировать это, мы создадим контейнер Docker с экземпляром сервера базы данных MySQL 8. Я выполняю эту операцию на сервере Linux Ubuntu 20.04, но можно использовать любую другую ОС. Я начну с установки Docker CE, а затем с создания контейнеров докеров MySQL 8.

Установите Docker CE на Ubuntu

Начну с установки Docker CE на Ubuntu. Используйте последний индекс пакета приложений:

sudo apt -y update
sudo apt -y install apt-transport-https ca-certificates curl gnupg-agent software-properties-common

Импортировать ключ GPG из репозитория Docker:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Добавьте репозиторий Docker CE в Ubuntu:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

Наконец, установите Docker CE на Ubuntu:

sudo apt update
sudo apt -y install docker-ce docker-ce-cli containerd.io

Добавьте свою учетную запись пользователя в группу докеров.

sudo usermod -aG docker $USER
newgrp docker

Проверьте установку, проверив версию Docker:

$ docker version
Client: Docker Engine - Community
 Version:           19.03.14
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        5eb3275d40
 Built:             Tue Dec  1 19:20:26 2020
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.14
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       5eb3275d40
  Built:            Tue Dec  1 19:18:53 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.3.9
  GitCommit:        ea765aba0d05254012b0b9e595e995c09186427f
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

Запустить экземпляр базы данных MySQL в Docker

Теперь мы можем создать контейнер Docker на основе базового образа MySQL 8. Создадим каталог данных:

mkdir ~/mysql_data

Запуск экземпляра базы данных:

docker run -d \
--name mysql8 \
-p 3306:3306 \
-v ~/mysql_data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD='RootUserPssw0rd' \
-e MYSQL_USER=app1 \
-e MYSQL_PASSWORD='app1Password' \
-e MYSQL_DATABASE=app1db \
mysql:8

Подтверждаем, что контейнер запущен:

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
368b02d943ad        mysql:8             "docker-entrypoint.s…"   51 seconds ago      Up 50 seconds       3306/tcp, 33060/tcp   mysql8

Установите клиентские инструменты MariaDB.

sudo apt install mariadb-client

Попробуйте подключиться к экземпляру сервера базы данных как пользователь root.

$ mysql -uroot -p'RootUserPssw0rd' -h 127.0.0.1
ERROR 1045 (28000): Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory

Мы можем подтвердить ошибку “Plugin caching_sha2_password could not be loaded“.

С более новой версией клиента MySQL, например 8, у вас не должно возникнуть такой проблемы.

$ mysql --version
mysql  Ver 8.0.22-0ubuntu0.20.04.3 for Linux on x86_64 ((Ubuntu))

# mysql -uroot -p'RootUserPssw0rd' -h 127.0.0.1
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.22 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>

Исправление невозможности загрузить плагин аутентификации  ‘caching_sha2_password’

Проверьте работающие контейнеры, чтобы выбрать контейнер MySQL.

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
72d48298731e        mysql:8             "docker-entrypoint.s…"   10 minutes ago      Up 10 minutes       0.0.0.0:3306->3306/tcp, 33060/tcp   mysql8

Подключиться к оболочке контейнера.

$ docker exec -ti mysql8 bash
root@72d48298731e:/#

Подключитесь к оболочке MySQL с паролем, переданным в переменной среды во время выполнения.

root@72d48298731e:/# mysql -uroot -p'RootUserPssw0rd'
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 8.0.22 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>

Обновите плагин аутентификации.

Для пользователя корневой базы данных

mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'RootUserPssw0rd';
Query OK, 0 rows affected (0.01 sec)

mysql> \q
Bye

root@72d48298731e:/# exit
exit

Подтвердите подключение:

$ mysql -uroot -p'RootUserPssw0rd' -h 127.0.0.1
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]>

Для любых других пользователей базы данных

Для любого другого пользователя базы данных используйте синтаксис команды:

ALTER USER 'dbusername' IDENTIFIED WITH mysql_native_password BY 'DBUserPassword';
# OR
ALTER USER 'dbusername'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'DBUserPassword';

См. Пример ниже, где мы обновляем плагин аутентификации для пользователя базы данных, который мы создали ранее.

mysql> ALTER USER 'app1'@'%' IDENTIFIED WITH mysql_native_password BY 'app1Password';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)

mysql> \q
Bye

root@07164b718a3f:/# exit
exit

Повторите команду для подключения к экземпляру MySQL.

$ mysql -u app1 -papp1Password -h 127.0.0.1
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| app1db             |
| information_schema |
+--------------------+
2 rows in set (0.008 sec)

MySQL [(none)]> \q
Bye