Поиск по сайту:

Как установить и использовать MariaDB в Ubuntu 22.04


На этой странице

  1. Предпосылки
  2. Установка и настройка MariaDB
  3. Проверьте версию MariaDB
  4. Заключение

MariaDB — это бесплатная и мощная система управления базами данных с открытым исходным кодом, используемая для хранения данных приложений. Это стабильная и реляционная система управления базами данных, форк популярной системы баз данных MySQL. Он специально разработан для масштабируемости и критически важных развертываний. На момент написания этого руководства последняя версия MariaDB — 10.6.7. Каждый крупный релиз будет поддерживаться не менее 5 лет. Таким образом, MariaDB 10.6.7 будет поддерживаться до 2026 года.

В этом руководстве мы покажем вам, как установить MariaDB 10.6 на сервер Ubuntu 22.04.

Предпосылки

  • Сервер под управлением Ubuntu 22.04.
  • На сервере настроен пароль root.

Установить и настроить MariaDB

Сначала обновите все системные пакеты с помощью следующей команды:

apt update -y

После обновления всех пакетов установите последнюю версию сервера и клиента MariaDB с помощью следующей команды:

apt-get install mariadb-server mariadb-client -y

После успешной установки запустите службу MariaDB и включите ее запуск при перезагрузке системы:

systemctl start mariadb
systemctl enable mariadb
systemctl status mariadb

Вы должны увидеть следующий вывод:

? mariadb.service - MariaDB 10.6.7 database server
     Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2022-06-25 14:34:47 UTC; 39s ago
       Docs: man:mariadbd(8)
             https://mariadb.com/kb/en/library/systemd/
    Process: 3174 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
    Process: 3175 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
    Process: 3177 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $?>
    Process: 3218 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
    Process: 3220 ExecStartPost=/etc/mysql/debian-start (code=exited, status=0/SUCCESS)
   Main PID: 3206 (mariadbd)
     Status: "Taking your SQL requests now..."
      Tasks: 13 (limit: 4579)
     Memory: 57.2M
        CPU: 582ms
     CGroup: /system.slice/mariadb.service
             ??3206 /usr/sbin/mariadbd

Jun 25 14:34:47 ubuntu2204 mariadbd[3206]: 2022-06-25 14:34:47 0 [Note] /usr/sbin/mariadbd: ready for connections.
Jun 25 14:34:47 ubuntu2204 mariadbd[3206]: Version: '10.6.7-MariaDB-2ubuntu1'  socket: '/run/mysqld/mysqld.sock'  port: 3306  Ubuntu 22.04
Jun 25 14:34:47 ubuntu2204 systemd[1]: Started MariaDB 10.6.7 database server.
Jun 25 14:34:47 ubuntu2204 /etc/mysql/debian-start[3222]: Upgrading MySQL tables if necessary.

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

mysql_secure_installation

Вам будет предложено ввести текущий пароль root, как показано ниже:

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 

Просто нажмите Enter. Вам будет предложено переключиться на аутентификацию unix_socket, как показано ниже:

OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorization.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] Y

Введите Y и нажмите Enter. Вам будет предложено изменить пароль root, как показано ниже:

Enabled successfully!
Reloading privilege tables..
 ... Success!


You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] Y

Введите Y и нажмите Enter, чтобы изменить пароль root.

New password: 
Re-enter new password: 

Введите безопасный пароль и нажмите Enter. Вы должны увидеть следующий вывод:

Password updated successfully!
Reloading privilege tables..
 ... Success!


Next, you will be asked to remove anonymous users as shown below:

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB 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? [Y/n] Y

Введите Y и нажмите Enter, чтобы удалить анонимных пользователей. Вам будет предложено запретить удаленный вход в систему root, как показано ниже:

 ... Success!

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? [Y/n] Y

Введите Y и нажмите Enter. Вам будет предложено удалить тестовую базу данных, как показано ниже:

 ... Success!

By default, MariaDB 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.

Remove test database and access to it? [Y/n] Y

Введите Y и нажмите Enter, чтобы удалить тестовую базу данных. Вам будет предложено перезагрузить таблицы привилегий, как показано ниже:

 - 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? [Y/n] Y

Введите Y и нажмите Enter, вы должны увидеть следующий вывод:

 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

Проверить версию MariaDB

На данный момент MariaDB установлена и защищена. Далее вам нужно будет проверить установленную версию MariaDB.

Сначала войдите в оболочку MariaDB с помощью следующей команды:

mysql -u root -p

Укажите свой корневой пароль MariaDB и нажмите Enter. После входа в систему вы должны увидеть следующий вывод:

Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 41
Server version: 10.6.7-MariaDB-2ubuntu1 Ubuntu 22.04

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

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

MariaDB [(none)]> 

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

MariaDB [(none)]> SELECT VERSION();

Вы должны получить следующий результат:

+-------------------------+
| VERSION()               |
+-------------------------+
| 10.6.7-MariaDB-2ubuntu1 |
+-------------------------+
1 row in set (0.000 sec)

Заключение

Поздравляем! вы успешно установили и защитили MariaDB 10.6 на сервере Ubuntu 22.04. Теперь вы можете создать новую базу данных и пользователя и подключить их к своему приложению.