Установка MySQL 8 в Ubuntu 22.04
Введение
MySQL – сервер баз данных, разработанный шведами, распростараняется бесплатно. Позже стала частью компании Oracle. Сейчас мы рассмотрим процесс установки сервера MySQL 8 на Ubuntu Server 22.04 и настройки внешнего доступа к базам данных.
Устанавливаем MySQL сервер на Ubuntu
По традиции все подобные статьи всегда начинаются с обновления операционной системы. Вуаля:
sudo apt update
sudo apt install mysql-server mysql-client
sudo systemctl start mysql.service
Настраиваем MySQL сервер
sudo mysql
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
mysql> exit
sudo mysql_secure_installation
Вывод команды sudo mysql_secure_installation:
~$ sudo mysql_secure_installation Securing the MySQL server deployment. Enter password for user 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? 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 Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2 Using existing password for root. Estimated strength of the password: 100 Change the password for root ? ((Press y|Y for Yes, any other key for No) : ... 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. 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. 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!
- Remove anonymous users – удалить аноноимных пользователей
- Disallow root login remotely – отключить удалённые подключения для root пользователя, это касается только удалённых подключений, подключения с localhost удалёнными не считаются.
- Remove test database and access to it – удалить тестовую базу данных.
- Reload privilege tables now – перезагрузить таблицу привилегий.
Заходим в MySQL под пользователем root, вас попросят ввести пароль:
mysql -u root -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH auth_socket;
mysql> exit
Теперь мы можем логиниться в MySQL через sudo.
Создаём нового пользователя в MySQL и выдаём ему разрешения
Заходим в базу под рутом для того, чтобы создать нового пользователя:
sudo mysql
Создаем пользователя username:
mysql> CREATE USER 'username'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
Выдаём новому пользователю привилегии:
mysql> GRANT CREATE, ALTER, DROP, INSERT, UPDATE, INDEX, DELETE, SELECT, REFERENCES, RELOAD on *.* TO 'username'@'localhost' WITH GRANT OPTION;
Или
mysql> GRANT ALL PRIVILEGES ON *.* TO 'username'@'%';
Далее приминяем внесённые изменения:
mysql> FLUSH PRIVILEGES;
mysql> exit
И пробуем авторизоваться под только что созданным пользователем:
mysql -u username -p
Теперь давайте протестируем MySQL
systemctl status mysql.service
На выводе мы видим, что сервис запушен и работает:
● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2023-04-03 06:12:56 UTC; 52min ago
Main PID: 35355 (mysqld)
Status: "Server is operational"
Tasks: 39 (limit: 1025)
Memory: 361.4M
CPU: 20.924s
CGroup: /system.slice/mysql.service
└─35355 /usr/sbin/mysqld
Apr 03 06:12:55 system systemd[1]: Starting MySQL Community Server...
Apr 03 06:12:56 system systemd[1]: Started MySQL Community Server.
sudo mysqladmin -p -u username version
Вывод:
~$ sudo mysqladmin -p -u username version
Enter password:
mysqladmin Ver 8.0.32-0ubuntu0.22.04.2 for Linux on x86_64 ((Ubuntu))
Copyright (c) 2000, 2023, 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.
Server version 8.0.32-0ubuntu0.22.04.2
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/run/mysqld/mysqld.sock
Uptime: 57 min 22 sec
Threads: 2 Questions: 25 Slow queries: 0 Opens: 182 Flush tables: 3 Open tables: 101
Queries per second avg: 0.007
Готово.
Удаленный доступ к MySQL
Открываем на редактирование файл mysqld.cnf:
Редактирование конфигурационного файла
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Переходим к конфигурированию параметра bind-address:
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 127.0.0.1
Чтобы разрешить доступ с любых IP-адресов, укажите здесь 0.0.0.0.
Обратите внимание, что такая настройка может быть небезопасной. Рекомендуется использовать ваш IP адрес, с которого вы собираетесь работать с базой данных.
Для применения параметров перезапускаем сервер MySQL командой:
sudo systemctl restart mysql
Даём привилегии пользователю на доступ из вне
Теперь нам нужно выдать права пользователю MySQL на доступ к серверу из вне.
CREATE USER 'username'@'%' IDENTIFIED BY 'password';
Если мы хотим создать пользователя, который сможет подключаться только с определенного IP адреса:
CREATE USER 'username'@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'username'@'%';
FLUSH PRIVILEGES;
Ограничения файрвола
В iptables нужно открыть порт 3306 (по умолчанию для MySQL сервера). Если мы хотим открыть на доступ только для конкретного ip адреса:
sudo iptables -A INPUT -s xxx.xxx.xxx.xxx -p tcp --destination-port 3306 -j ACCEPT
Если мы хотим открыть для всех входящих соединений:
sudo iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
После можно проверить список правил в iptables командой:
sudo iptables -nvLТакже мы можем настроить iptables для входящих только с определенных ip адресов, а для остальных запретить:
/sbin/iptables -A INPUT -s 127.0.0.1 -p tcp --destination-port 3306 -j ACCEPT /sbin/iptables -A INPUT -s 192.168.1.5 -p tcp --destination-port 3306 -j ACCEPT /sbin/iptables -A INPUT -p tcp --dport 3306 -j DROP
Также в Ubuntu по дефолту идёт оболочка UFW, можно через неё открыть доступ к порту сервера MySQl:
sudo ufw allow 3306
А также, если нам нужно открыть только для определенного ip адреса:
sudo ufw allow from xxx.xxx.xxx.xxx to any port 3306
После завершения настройки проверьте, что пользователь может подключиться к MySQL удаленно.
mysql -u username -h ip_server_mysql -p
Комментари 8: