Installing mariadb with yum/dnf

MySQL vs MariaDB comparison

MySQL MariaDB
Database Structure MySQL is an open-source relational database management system (RDBMS). As with every other relational database, MySQL users work with staple constituents such as tables, constraints, triggers, roles, stored procedures, and views. Each row, or record is identified with a primary key, and foreign keys are used to make sure that related tables can refer to each other accurately. MariaDB is a fork of MySQL, so the database structure and indexes of MariaDB are the same as they are with MySQL. The upshot of this is that your applications will still work if you switch, because the way that the data is organised doesn’t need to change.
Indexes MySQL also allows hash indexes and InnoDB engine utilises inverted lists for FULLTEXT indexes. Most MySQL and MariaDB indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT) are held in B-trees. The indexes on spatial data types use R-trees so they are an exception.
Databases Deployment MySQL is written in C and C++ and binaries are available for these systems: Microsoft Windows, OS X, Linux, AIX, BSDi, FreeBSD, HP-UX, IRIX, NetBSD, Novell Netware, and lots more. MariaDB is written in C, C++, Bash, and Perl and has binaries for these systems: Microsoft Windows, Linux, OS X, FreeBSD, OpenBSD, Solaris, and others.

Since MariaDB works as a straight swap for MySQL, you should have no trouble uninstalling MySQL, installing MariaDB in its place, then connecting (so long as the file versions are the same). Please be aware that you should run mysql_upgrade to conclude the upgrade process.

Replication / Clustering Replication with MySQL is asynchronous. One server acts as a master to the others’ slaves. You can replicate all databases, selected databases or even selected tables within a database.

MySQL Cluster is a technology providing shared-nothing (there isn’t one point of failure) clustering and auto-sharding (partitioning) for the MySQL database management system.

Internally, MySQL Cluster uses synchronous replication through a two-phase commit mechanism to ensure that data is written to many nodes. This contrasts with what is normally termed “MySQL Replication”, which is asynchronous.

MariaDB offers master-master and master-slave replication as well. MariaDB uses the Galera Cluster for multi-master. From MariaDB 10.1 onwards, Galera is included with MariaDB. To enable clustering you only need to activate the configuration parameters.
Support MySQL developers and support engineers give round-the-clock coverage for patches, updates and fixing bugs. This is part of Oracle’s lifetime support arrangement.

Oracle offers MySQL Premier Support, Extended Support, and Sustaining Support depending upon your needs.

MariaDB ‘s engineers give round the clock support under the enterprise subscription for mission-critical production systems. Support staff are well versed in both MariaDB and MySQL.
Connectors MySQL provides a variety of database connectors which include C, C++, Delphi, Perl, Java, Lua, .NET, Node.js, Python, PHP, Lisp, Go, R, D, and Erlang. MariaDB provides various database connectors which include ADO.NET, C, C++, D, Java, JavaScript, ODBC, Perl, PHP, Python, Ruby, and Visual Studio plug-in.

Шаг 2 — Настройка MariaDB

Для новых установок MariaDB следующим шагом является запуск встроенного скрипта безопасности. Этот скрипт меняет ряд наименее защищенных опций, используемых по умолчанию, для таких функций, как, например, удаленный вход для пользователя root и тестовые пользователи.

Запустите скрипт безопасности:

При этом откроется серия диалогов, где вы можете внести некоторые изменения в параметры безопасности установки MariaDB. В первом диалоге вам нужно будет ввести пароль пользователя root для текущей базы данных. Поскольку мы еще не настроили его, нажмите , чтобы указать «отсутствует».

В следующем диалоге вам будет предложено задать пароль для пользователя root базы данных. В Ubuntu учетная запись root для MariaDB тесно связана с автоматизированным обслуживанием системы, так что мы не должны изменять настроенные методы аутентификации для этой учетной записи. Это позволит нам обновить пакет для уничтожения системы базы данных посредством удаления доступа к административной учетной записи. Введите и нажмите .

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

Далее вы можете использовать клавиши и , чтобы принять ответы по умолчанию для всех последующих вопросов. Выбрав эти ответы, вы удалите ряд анонимных пользователей и тестовую базу данных, отключите возможность удаленного входа пользователя root и загрузите новые правила, чтобы внесенные изменения немедленно имплементировались в MariaDB.

Мы завершили первоначальную настройку конфигурации безопасности MariaDB. Следующий шаг необязателен, но его следует выполнить, если вы предпочитаете использовать пароль для аутентификации на сервере MariaDB.

Step 4 — Testing MariaDB

When installed from the default repositories, MariaDB should start running automatically. To test this, check its status.

You’ll receive output that is similar to the following:

If MariaDB isn’t running, you can start it with the command .

For an additional check, you can try connecting to the database using the tool, which is a client that lets you run administrative commands. For example, this command says to connect to MariaDB as root and return the version using the Unix socket:

You should receive output similar to this:

If you configured a separate administrative user with password authentication, you could perform the same operation by typing:

This means that MariaDB is up and running and that your user is able to authenticate successfully.

Шаг 2. Настройка кластера MariaDB в режиме Master — Master

Если одностороннего режима копирования данных нам недостаточно, продолжаем настройку.

Настройка на сервере Slave

На втором сервере откроем конфигурационный файл MariaDB:

# vi /etc/my.cnf.d/server.cnf

и допишем в него следующее:

log_bin=mysql-bin
log_error=mysql-bin.err
binlog-ignore-db=information_schema,mysql,test

Перезагрузим демон для применения настроек:

# systemctl restart mariadb

Теперь подключимся к MariaDB:

# mysql -uroot -p

и создадим учетную запись для репликации с первого сервера:

MariaDB > GRANT replication slave ON *.* TO «replmy»@»192.168.166.155» IDENTIFIED BY «password»;

* replmy: имя учетной записи (можно использовать любое). 192.168.166.155: IP-адрес первого сервера, с которым будем реплицировать данные. password: пароль для учетной записи (желательно, сложный).

Выведем состояние работы мастера:

MariaDB > show master status\G

Как и при настройке первого сервера, запомните или запишите значения для File и Position.

Настройка на сервере Master

Теперь подключитесь к первому серверу.

И зайдем в командную оболочку MariaDB:

# mysql -uroot -p

введем такую команду:

MariaDB > change master to master_host = «192.168.166.156», master_user = «replmy», master_password = «password», master_log_file = «mysql-bin.000003», master_log_pos = 245;

* 192.168.166.156: IP-адрес моего второго сервера. replmy: учетная запись для репликации, которая была создана на втором сервере. password: пароль для учетной записи, также был сделан на втором сервере. mysql-bin.000003: имя файла, которое мы должны были записать или запомнить (у вас может быть другим). 245: номер позиции, с которой необходимо начать репликацию (также должны были записать или запомнить ранее).

Теперь запустим вторичный сервер для репликации:

MariaDB > start slave;

И проверим состояние репликации:

MariaDB > SHOW SLAVE STATUS\G

Отключитесь от СУРБД:

MariaDB > \q

Настройка кластера в режиме Master — Master закончена.

Теперь остается окончательно убедиться, что репликация работает. Внесите изменения на первом сервере — они должны попасть на второй. И наоборот, при внесении изменений на втором сервере, они должны попадать на первый.

Step 2 — Configuring MariaDB

For new MariaDB installations, the next step is to run the included security script. This script changes some of the less secure default options. We will use it to block remote root logins and to remove unused database users.

Run the security script:

This will take you through a series of prompts where you can make some changes to your MariaDB installation’s security options. The first prompt will ask you to enter the current database root password. Since we have not set one up yet, press to indicate “none”.

The next prompt asks you whether you’d like to set up a database root password. Type and then press . On Ubuntu, the root account for MariaDB is tied closely to automated system maintenance, so we should not change the configured authentication methods for that account. Doing so would make it possible for a package update to break the database system by removing access to the administrative account. Later, we will cover how to optionally set up an additional administrative account for password access if socket authentication is not appropriate for your use case.

From there, you can press and then to accept the defaults for all the subsequent questions. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MariaDB immediately implements the changes you have made.

Шаг 3 — Настройка аутентификации и прав пользователя (опционально)

При установке MariaDB 10.1 в системах Ubuntu для пользователя root user MariaDB настраивается аутентификация с помощью плагина , а не с помощью пароля. Во многих случаях это обеспечивает более высокую безопасность и удобство, однако это также может осложнить ситуацию, если вам нужно предоставить права администратора внешней программе (например, phpMyAdmin).

Поскольку для ротации журналов, запуска и остановки сервера используется учетная запись root, лучше всего не менять учетные данные root. Изменение учетных данных в файле конфигурации может работать на начальном этапе, но при обновлении пакета изменения могут быть перезаписаны. Вместо изменения учетной записи root, мантейнеры пакетов рекомендуют создать отдельную административную учетную запись для доступа по паролю.

Для этого мы создадим новую учетную запись с именем и теми же возможностями, которые есть у учетной записи root, но настроим для нее аутентификацию по паролю. Для этого откройте командную строку MariaDB через терминал:

Теперь мы можем создать нового пользователя с привилегиями root и доступом с использованием пароля. Измените имя пользователя и пароль на желаемые:

Очистите привилегии, чтобы они были сохранены и доступны в текущем сеансе:

После этого закройте оболочку MariaDB:

Теперь давайте проверим установку MariaDB.

Запускаем кластер

На основной ноде запускаем сервис с ключом –wsrep-new-cluster (/etc/init.d/mysql start –wsrep-new-cluster), на остальных нодах запускаем как обычно /etc/init.d/mysql start

Проверяем статус кластера

1
2
3
4
5
6
7
8
9
10
11
12

mysql-uroot-p—execute=»SHOW GLOBAL STATUS WHERE Variable_name IN (‘wsrep_ready’, ‘wsrep_cluster_size’, ‘wsrep_cluster_status’, ‘wsrep_connected’);»

+———————-+———+

|Variable_name|Value|

+———————-+———+

|wsrep_cluster_size|2|

|wsrep_cluster_status|Primary|

|wsrep_connected|ON|

|wsrep_ready|ON|

+———————-+———+

1
2
3
4
5
6
7
8
9
10
11

mysql-uroot-p—execute=»SHOW GLOBAL STATUS WHERE Variable_name IN(‘wsrep_cluster_size’, ‘wsrep_cluster_status’, ‘wsrep_incoming_addresses’);»

+—————————+—————————————+

|Variable_name|Value|

+—————————+—————————————+

|wsrep_cluster_size|2|

|wsrep_cluster_status|Primary|

|wsrep_incoming_addresses|00.201.203.553306,100.201.203.543306|

+—————————+—————————————+

1
2
3

mysql-uroot-p-e»show status like ‘wsrep%'»

wsrep_local_state_comment wsrep_cluster_sizewsrep_ready

Шаг 3 — (необязательно) Создание административного пользователя с аутентификацией по паролю

При установке MariaDB 10.3 в системах Ubuntu для пользователя root в MariaDB настраивается аутентификация с помощью плагина , а не с помощью пароля. Во многих случаях это обеспечивает более высокую безопасность и удобство, однако это также может осложнить ситуацию, если вам нужно предоставить права администратора внешней программе (например, phpMyAdmin).

Поскольку для ротации журналов, запуска и остановки сервера используется учетная запись root, лучше всего не менять учетные данные root. Изменение учетных данных в файле конфигурации может работать на начальном этапе, но при обновлении пакета изменения могут быть перезаписаны. Вместо изменения учетной записи root, мантейнеры пакетов рекомендуют создать отдельную административную учетную запись для доступа по паролю.

Для этого мы создадим новую учетную запись admin с теми же привилегиями, что и у учетной записи root, но настроенную для аутентификации с использованием пароля. Откройте в терминале командную строку MariaDB:

Затем создайте нового пользователя с правами root и с аутентификацией на основе пароля. Измените имя пользователя и пароль на предпочитаемые:

Очистите привилегии, чтобы они были сохранены и доступны в текущем сеансе:

После этого закройте оболочку MariaDB:

Теперь давайте проверим установку MariaDB.

Conclusion

Percona sees healthy competition in the MySQL ecosystem. We support all databases in the ecosystem: MySQL, MariaDB Server and Percona Server for MySQL. Our focus is to provide alternatives to proprietary parts of open source software. Percona has a strong operations focus on compatibility, application scalability, high availability security, and observability. We also support many additional tools within the ecosystem and love integrating and contributing to open source code.

For example, Percona Monitoring and Management (PMM) includes many open source tools like Prometheus, Consul, Grafana, Orchestrator and more. We have made the de facto open source hot backup solution for MySQL, MariaDB Server and Percona Server for MySQL (called Percona XtraBackup). We continue to maintain and extend useful tools for database engineers and administrators in Percona Toolkit. We make Percona XtraDB Cluster safe for deployment out of the box. We have invested in a write-optimized storage engine, TokuDB, and now continue to work with making MyRocks better.

We look forward to supporting your deployments of MySQL or MariaDB Server, whichever option is right for you! If you need assistance on migrations between servers, or further information, don’t hesitate to contact your friendly Percona sales associate.

Step 4 — Testing MariaDB

When installed from the default repositories, MariaDB should start running automatically. To test this, check its status.

You’ll receive output that is similar to the following:

Output

If MariaDB isn’t running, you can start it with the command .

For an additional check, you can try connecting to the database using the tool, which is a client that lets you run administrative commands. For example, this command says to connect to MariaDB as root and return the version using the Unix socket:

You should receive output similar to this:

If you configured a separate administrative user with password authentication, you could perform the same operation by typing:

This means that MariaDB is up and running and that your user is able to authenticate successfully.

MariaDB vs. MySQL

Here are a major difference between MariaDB and MySQL.

Parameter MariaDB MySQL
Storage Engines MariaDB has 12 new storage engines that you won’t find in MySQL. It has fewer options for storage compared to MariaDB.
Speed Improvements MariaDB shows an improved speed when compared to MySQL. MySQL exhibits a slower speed when compared to MariaDB.
Initial release 2009 1995
Server operating systems FreeBSD Linux
Solaris Windows
FreeBSD Linux
OS X Solaris
Windows
Faster cache/indexes With the Memory storage engine of MariaDB, an INSERT statement can be completed 24% faster than in the standard MySQL. The memory storage engine of MySQL is slower compared to that MariaDB.
Larger and Faster Connection Pool MariaDB comes with an advanced thread pool capable of running faster and supporting up to 200,000+ connections. The thread pool provided by MySQL cannot support up to 200,000 connections per time.
Improved Replication In MariaDB, replication can be done safer and faster. Updates can also be done 2x faster compared to the traditional MySQL. MySQL’s community edition allows a static number of threads to be connected. MySQL’s enterprise plan comes with thread capabilities.
New Features/Extensions MariaDB comes with new features and extensions including the JSON, WITH and KILL statements. The new MariaDB features are not provided in MySQL.
Missing Features MariaDB lacks some of the features provided by the MySQL enterprise edition. To address this, it offers alternative open-source plugins. The Enterprise Edition of MySQL uses a proprietary code. Only users of MySQL Enterprise Edition have access to this.
Priority code MariaDB doesn’t allow access to this propriety content and is a closed source. MySQL uses some proprietary code in its Enterprise Edition.
Data Masking No Yes
Dynamic columns No Yes
Monitoring SQLyog MySQL workbench
Routing MariaDB MaxScale Mysql Router
Analytics MaraiDB ColumnStore No
Secondary database model Document store and Graph DBMS Document store
Git hub stars 2.8 k 4k
Forks 868 1.6 K
Famous companies using Nrise, Accenture, Docplanner, Grooveshark. Airbnb, Uber Technogloeis, Netflix, Dropbox.

Возможные ошибки

1. ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

Причина: в новых версиях по умолчанию активированы политики на проверку сложности пароля. Их список можно посмотреть командой:

> SHOW VARIABLES LIKE ‘validate_password%’;

Вывод команды будет, примерно, следующим:

+—————————————+———+
| Variable_name | Value |
+—————————————+———+
| validate_password_check_user_name | OFF |
| validate_password_dictionary_file | |
| validate_password_length | 8 |
| validate_password_mixed_case_count | 1 |
| validate_password_number_count | 1 |
| validate_password_policy | MEDIUM |
| validate_password_special_char_count | 1 |
+—————————————+———+

* где:

  • validate_password_check_user_name — пароль не должен совпадать с именем пользователя.
  • validate_password_dictionary_file — использовать специальный файл со словарем запрещенных паролей.
  • validate_password_length — минимальная длина пароля.
  • validate_password_mixed_case_count — сколько, как минимум, должно быть символов в малой и большой раскладках.
  • validate_password_number_count — какое минимальное количество цифр использовать в пароле.
  • validate_password_policy — позволяет задать определенный набор правил. Доступны значения LOW (или 0), MEDIUM (1), STRONG (2).
  • validate_password_special_char_count — минимальное количество специальных символов (например, # или !).

Решение:

  1. Привести пароль в соответствие требованиям политик.
  2. Отключить политику, которая не позволяет использовать желаемый пароль. Например, чтобы отключить требование использовать цифры вводим:

> SET GLOBAL validate_password_number_count = 0;

2. ERROR 1728 (HY000): Cannot load from mysql.tables_priv. The table is probably corrupted

Причина: система считает, что таблица tables_priv в базе mysql неисправна.

Решение: чаще всего, ошибка возникает при переносе баз с одного сервера в другой. Если версии СУБД разные, таблица tables_priv может работать со сбоями. Для исправления необходимо выполнить команду mysql_upgrade — она проверяет все таблицы на совместимость с текущей версией MySQL/MariaDB и вносит исправления. Применение команды:

mysql_upgrade -u root -p

Supporting Ecosystem and Tools

Upgrading from MySQL to MariaDB Server should be a relatively simple process (as stated above). If you want to upgrade away from MariaDB Server to MySQL, you may face hassles. For tools, see the following table:

Purpose MySQL Percona Server for MySQL MariaDB Server
Monitoring MySQL Enterprise Monitor Percona Monitoring & Management (PMM) (100% open source) Webyog Monyog
Backup MySQL Enterprise Backup Percona XtraBackup MariaDB Backup (fork of Percona XtraBackup)
SQL Management MySQL Workbench MySQL Workbench Webyog SQLyog
Load Balancing & Routing MySQL Router ProxySQL MariaDB MaxScale
Database Firewall MySQL Enterprise Firewall ProxySQL MariaDB MaxScale

2: Настройка MariaDB

После завершения установки нужно запустить сценарий безопасности, который удалит ненадёжные параметры  и защитит БД от несанкционированного доступа.

Сценарий задаст ряд вопросов. Сначала нужно указать root-пароль MariaDB. Это административная учетная запись MariaDB, которая имеет повышенные привилегии. Вы установили MariaDB только что и еще не внесли никаких изменений в конфигурацию, этого пароля пока у вас нет, поэтому просто нажмите Enter.

В следующем запросе скрипт предложит настроить пароль root для базы данных. Введите N и нажмите клавишу Enter. В Debian учетная запись root MariaDB тесно связана с автоматизированным обслуживанием системы, поэтому изменять стандартные методы аутентификации этой учетной записи нельзя. Иначе при обновлении пакета БД может повредиться, а доступ к учетной записи root может быть утрачен. Позже мы рассмотрим, как настроить дополнительную учетную запись администратора, если аутентификация сокетов вам не подходит.

На остальные вопросы можно нажать Y и Enter. Это удалит анонимных пользователей и тестовые базы данных, отключит удалённый root логин и обновит текущие настройки MariaDB.

Строковые типы данных

Ниже приведены строковые типы данных в MariaDB:

Синтаксис типа данных Максимальный размер Пояснение
CHAR(размер) Максимальный размер 255 символов. Где размер — это количество символов для хранения. Строки фиксированной длины. Пробел дополняется справа до размер символов.
VARCHAR(размер) Максимальный размер 255 символов. Где размер — это количество символов для хранения. Строка переменной длины.
TINYTEXT(размер) Максимальный размер 255 символов. Где размер — это количество символов для хранения.
TEXT(размер) Максимальный размер 65,535 символов. Где размер — это количество символов для хранения.
MEDIUMТЕКСТ (размер) Максимальный размер 16,777,215 символов. Где размер — это количество символов для хранения.
LONGТЕКСТ (размер) Максимальный размер 4GB or 4,294,967,295 символов. Где размер — это количество символов для хранения.
BINARY (размер) Максимальный размер 255 символов. Где размер — это количество двоичных символов для хранения. Строки фиксированной длины. Пробел дополняется справа до размер символов.
VARBINARY (размер) Максимальный размер 255 символов. Где размер — это количество символов для хранения. Строка переменной длины.

Step 3 — (Optional) Adjusting User Authentication and Privileges

In Debian systems running MariaDB 10.3, the root MariaDB user is set to authenticate using the plugin by default rather than with a password. This allows for some greater security and usability in many cases, but it can also complicate things when you need to allow an external program (e.g., phpMyAdmin) administrative rights.

Because the server uses the root account for tasks like log rotation and starting and stopping the server, it is best not to change the root account’s authentication details. Changing credentials in the configuration file may work initially, but package updates could potentially overwrite those changes. Instead of modifying the root account, the package maintainers recommend creating a separate administrative account for password-based access.

To do so, we will create a new account called with the same capabilities as the root account, but configured for password authentication. To do this, open up the MariaDB prompt from your terminal:

Now, we will create a new user with root privileges and password-based access. Change the username and password to match your preferences:

Flush the privileges to ensure that they are saved and available in the current session:

Following this, exit the MariaDB shell:

Finally, let’s test the MariaDB installation.

Step 3 — (Optional) Adjusting User Authentication and Privileges

On Ubuntu systems running MariaDB 10.1, the root MariaDB user is set to authenticate using the plugin by default rather than with a password. This allows for some greater security and usability in many cases, but it can also complicate things when you need to allow an external program (e.g., phpMyAdmin) administrative rights.

Because the server uses the root account for tasks like log rotation and starting and stopping the server, it is best not to change the root account’s authentication details. Changing credentials in the configuration file may work initially, but package updates could potentially overwrite those changes. Instead of modifying the root account, the package maintainers recommend creating a separate administrative account for password-based access.

To do so, we will create a new account called with the same capabilities as the root account, but configured for password authentication. To do this, open up the MariaDB prompt from your terminal:

Now, we will create a new user with root privileges and password-based access. Change the username and password to match your preferences:

Flush the privileges to ensure that they are saved and available in the current session:

Following this, exit the MariaDB shell:

Finally, let’s test the MariaDB installation.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector