Главная страница » Как установить mysql на ubuntu

Как установить mysql на ubuntu

  • автор:

Установка MySQL на Linux #

Будем устанавливать MySQL как сервис в систему, нам будет необходима любая версия 8.0.x, которая есть в репозитория дистрибутива.

Откройте терминал и выполните команды в зависимости от вашего пакетного менеджера:

Обновите список пакетов

sudo apt update

Запускаем обновление пакетов репозитория:

sudo apt install mysql-server

Обновите список пакетов

sudo pacman -Syu

Установите пакет mysql :

sudo pacman -S mysql

Обновите Yum репозиторий, скачайте

и установите согласно настройкам

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

Также может потребоваться установка если вы выбрали mariadb:

При успехе будет создан пользователь root без пароля и пользователь mysql без пароля. Чтобы использовать эти учетные записи, необходимо быть пользователем root или mysql при использовании клиентов, что неудобно и небезопасно. Желательно выполнить конфигурацию и создать пользователя.

  • �� вы всегда можете проверить работает ли сервер Mysql командой

systemctl status mysql

Для перезапуска команда

systemctl restart mysql

Для остановки mysql

systemctl stop mysql

Конфигурация MySQL #

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

В терминале наберите команду

Будет запущено поэтапный конфигуратор, который будет вам задавать вопросы.

Первый вопрос: Необходимо ли делать валидацию новых паролей пользователей базы данных. Отвечайте на этот вопрос Y.

Далее вас спросят насколько сложными должны быть новые пароли. Если вы настраиваете сервер для тестов, локально. Можете выбрать 0, пароль должен быть 8 и более символов. В остальных случаях используйте 1 или 2.

Далее введите пароль от root пользователя:

После ввода пароля, вам предложат повторить пароль для подтверждения. Далее вас могут спросить, готовы продолжить с установленным паролем, вводите Y и нажмите Enter.

Следующим шагом, предложат удалить анонимный аккаунт test, вы можете использовать его при использовании бд как тестовую. А так принято удалять, чтобы не было возможности получить доступ к бд без логина и пароля. Выбирайте Y для удаления.

После будет предложено запретить доступ пользователю root если попытка получить доступ к бд будет не с локального компьютера на котором установлен сервис mysql.

Если вы используете учебную базу на одном компьютере, то закрывайте доступ.

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

В нашем случае выбирайте Y:

Далее предлагают удалить тестовые базы, соглашайтесь если вам они не нужны, выбирайте Y:

И последний вопрос будет — перезагрузить ли привилегии пользователей, чтобы изменения вступили в силу:

Создание нового пользователя #

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

username — логин нового пользователя

password — пароль, на скриншоте используется slsds23#.jd

Поменяйте значения по вашему усмотрению и запомните.

Для учебных целей выдайте права на все базы этому пользователю:

Давать все права (привилегии) на реальных базах опасно, это допустимо делать только на учебных базах данных.

Остается выйти quit и зайти уже под новым пользователем

Проверка подключения #

Для подключения вводим команду

, где мы указываем два параметра:

-u и после него указывается пользователь под которым мы хотим зайти в консоль mysql

-p после него не указываем ничего, а значит нас спросят ввести пароль отдельно. Можно пароль вводить после, например так mysql -u username -p 12345 , но это менее безопасно. Так как пароль остается в открытом виде.

MySQL

MySQL — свободная СУБД для малых и средних приложений. Входит в состав LAMP и XAMPP.

Версии MySQL в Ubuntu

Ubuntu MySQL
12.04 LTS (Precise) 5.5
14.04 LTS (Trusty) 5.5, 5.6
15.10 (Wily) 5.6
16.04 LTS (Xenial) 5.7

Установка

MySQL есть в репозиториях Ubuntu. Он разбит на несколько пакетов.

Для того чтобы установить MySQL сервер выполните команду:

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

Для того чтобы установить консольный клиент MySQL выполните команду:

Для того чтобы установить модуль для работы с MySQL в PHP выполните команду:

Настройка

Конфигурация сервера MySQL содержится в файле /etc/mysql/my.cnf.

Доступ к серверу из сети

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

Кодировки

По-умолчанию в Ubuntu MySQL устанавливается с кодировкой latin1 . В этом можно убедиться посмотрев вывод запроса:

В связи с этим, даже используя при работе с сервером команду

и используя при создании таблиц

невозможно добиться полной поддержки кодировки utf8:

Кодировка по-умолчанию все равно останется latin1, что неудобно и может привести к ошибкам.

Чтобы сервер сразу загружался с нужной кодировкой, необходимо отредактировать файл /etc/mysql/my.cnf:

В секцию [mysqld] добавьте следующие строки:

Так же желательно установить кодировку для клиента и mysqldump. Для этого в секциях [client] и [mysqldump] необходимо добавить строчку:

Перезагрузите сервер MySQL:

После этого список переменных будет выглядеть так:

Администрирование

Установка root пароля

Восстановление забытого пароля для root'a

Схожая проблема возникает если не задать пароль при установке MySQL, в этом случае mysql использует плагин unix-socket.

Запустите mysqld с параметрами —skip-grant-tables —user=root :

Если команда не сработает, добавьте строку « skip-grant-tables » в секцию « [mysqld] » файла /etc/mysql/mysql.conf.d/mysqld.cnf . Затем выполните sudo service mysql restart . После выполнения операций удалите эту строку.

Подключитесь к MySQL-серверу командой:

Обновите пароль для root'a:

Для MySQL версий < 5.7:

Теперь можете проверить вход под root с новым паролем:

Резервное копирование

Для создания резервных копий существует специальная утилита mysqldump . Основные ее параметры приведены в таблице:

Параметр Описание Пример
-u<user> Пользователь, от лица которого будет производится дамп баз данных. -uroot
-p<password> Пароль пользователя. Пароль необязательно указывать, достаточно упомянуть этот параметр для того, чтобы утилита знала что подключение требует пароля. -ppassword
-p
-h<host> Хост, на котором расположена база данных. -h127.0.0.1
-A Создать бекап всех баз данных. -A
-B <databases> Базы данных, которые нужно забэкапить. -B db1 db2 db3
—tables <tables> Таблицы, которые нужно забэкапить. Перекрывает действие ключа -B —tables db1.table1 db1.table2 db2.table3
-d Создать бекап структуры таблиц. Содержимое таблиц скопировано не будет. -d
—skip-extended-insert Не использовать многострочные INSERT-записи при создании дампа. —skip-extended-insert
-w'where_clause ' Создавать дамп только тех строк, которые попадают под условие. -w'Id > 10 AND Id < 100 '

Отключение и включение автозагрузки сервиса

Начиная с версии Ubuntu 15.04 отключение и включение сервисов возможно одной командой, без редактирования конфигов. В примерах команд ниже слово «SERVICE» следует заменить на «mysql».

Узнать стоит ли сервис в автозагрузке:

Убрать сервис из автозагрузки в Ubuntu-16.04:

Добавить сервис в автозагрузку в Ubuntu-16.04:

MySQL Workbench

MySQL Workbench – инструмент для визуального проектирования баз данных. MySQL Workbench существует в двух вариантах:

Install and configure a MySQL server

MySQL is a fast, multi-threaded, multi-user, and robust SQL database server. It is intended for mission-critical, heavy-load production systems and mass-deployed software.

Installation

To install MySQL, run the following command from a terminal prompt:

Once the installation is complete, the MySQL server should be started automatically. You can quickly check its current status via systemd:

Which should provide an output like the following:

The network status of the MySQL service can also be checked by running the ss command at the terminal prompt:

When you run this command, you should see something similar to the following:

If the server is not running correctly, you can type the following command to start it:

A good starting point for troubleshooting problems is the systemd journal, which can be accessed from the terminal prompt with this command:

Configuration

You can edit the files in /etc/mysql/ to configure the basic settings – log file, port number, etc. For example, to configure MySQL to listen for connections from network hosts, in the file /etc/mysql/mysql.conf.d/mysqld.cnf , change the bind-address directive to the server’s IP address:

Note:
Replace 192.168.0.5 with the appropriate address, which can be determined via the ip address show command.

After making a configuration change, the MySQL daemon will need to be restarted with the following command:

Database engines

Whilst the default configuration of MySQL provided by the Ubuntu packages is perfectly functional and performs well there are things you may wish to consider before you proceed.

MySQL is designed to allow data to be stored in different ways. These methods are referred to as either database or storage engines. There are two main storage engines that you’ll be interested in: InnoDB and MyISAM. Storage engines are transparent to the end user. MySQL will handle things differently under the surface, but regardless of which storage engine is in use, you will interact with the database in the same way.

Each engine has its own advantages and disadvantages.

While it is possible (and may be advantageous) to mix and match database engines on a table level, doing so reduces the effectiveness of the performance tuning you can do as you’ll be splitting the resources between two engines instead of dedicating them to one.

MyISAM is the older of the two. It can be faster than InnoDB under certain circumstances and favours a read-only workload. Some web applications have been tuned around MyISAM (though that’s not to imply that they will be slower under InnoDB). MyISAM also supports the FULLTEXT data type, which allows very fast searches of large quantities of text data. However MyISAM is only capable of locking an entire table for writing. This means only one process can update a table at a time. As any application that uses the table scales this may prove to be a hindrance. It also lacks journaling, which makes it harder for data to be recovered after a crash. The following link provides some points for consideration about using MyISAM on a production database.

InnoDB is a more modern database engine, designed to be ACID compliant which guarantees database transactions are processed reliably. Write locking can occur on a row level basis within a table. That means multiple updates can occur on a single table simultaneously. Data caching is also handled in memory within the database engine, allowing caching on a more efficient row level basis rather than file block. To meet ACID compliance all transactions are journaled independently of the main tables. This allows for much more reliable data recovery as data consistency can be checked.

As of MySQL 5.5 InnoDB is the default engine, and is highly recommended over MyISAM unless you have specific needs for features unique to that engine.

Advanced configuration

Creating a tuned configuration

There are a number of parameters that can be adjusted within MySQL’s configuration files. This will allow you to improve the server’s performance over time.

Many parameters can be adjusted with the existing database, however some may affect the data layout and thus need more care to apply.

First, if you have existing data, you will first need to carry out a mysqldump and reload:

This will then prompt you for the root password before creating a copy of the data. It is advisable to make sure there are no other users or processes using the database whilst this takes place. Depending on how much data you’ve got in your database, this may take a while. You won’t see anything on the screen during this process.

Once the dump has been completed, shut down MySQL:

It’s also a good idea to backup the original configuration:

Next, make any desired configuration changes. Then, delete and re-initialise the database space and make sure ownership is correct before restarting MySQL:

The final step is re-importation of your data by piping your SQL commands to the database.

For large data imports, the ‘Pipe Viewer’ utility can be useful to track import progress. Ignore any ETA times produced by pv ; they’re based on the average time taken to handle each row of the file, but the speed of inserting can vary wildly from row to row with mysqldumps :

Once this step is complete, you are good to go!

Note:
This is not necessary for all my.cnf changes. Most of the variables you can change to improve performance are adjustable even whilst the server is running. As with anything, make sure to have a good backup copy of your config files and data before making changes.

MySQL Tuner

MySQL Tuner is a Perl script that connects to a running MySQL instance and offers configuration suggestions for optimising the database for your workload. The longer the server has been running, the better the advice mysqltuner can provide. In a production environment, consider waiting for at least 24 hours before running the tool. You can install mysqltuner from the Ubuntu repositories:

Then once it has been installed, simply run: mysqltuner – and wait for its final report.

The top section provides general information about the database server, and the bottom section provides tuning suggestions to alter in your my.cnf . Most of these can be altered live on the server without restarting; look through the official MySQL documentation (link in Resources section at the bottom of this page) for the relevant variables to change in production. The following example is part of a report from a production database showing potential benefits from increasing the query cache:

It goes without saying that performance optimisation strategies vary from application to application. So for example, what works best for WordPress might not be the best for Drupal or Joomla. Performance can be dependent on the types of queries, use of indexes, how efficient the database design is and so on.

You may find it useful to spend some time searching for database tuning tips based on what applications you’re using. Once you’ve reached the point of diminishing returns from database configuration adjustments, look to the application itself for improvements, or invest in more powerful hardware and/or scaling up the database environment.

Resources

Full documentation is available in both online and offline formats from the MySQL Developers portal

For general SQL information see the O’Reilly books Getting Started with SQL: A Hands-On Approach for Beginners by Thomas Nield as an entry point and SQL in a Nutshell as a quick reference.

What is MySQL?

MySQL is an open-source relational database management system. Its name is a combination of “My”, the name of co-founder Michael Widenius’s daughter My, and “SQL”, the abbreviation for Structured Query Language.

MySQL is the most popular open-source relational database management system supported by a huge and active community of open-source developers. It is available on over 20 platforms and operating systems, including Linux, Unix, Mac, and Windows.

MySQL is based on Client and Server Architecture. Here, the Client machine requests specific data by querying using Structured Query Language (SQL) and the server responds with the desired output to the client machine after processing the request. MySQL server is multithreaded, multitasking, and is designed to work also on heavy-load production systems. It has both transactional and non-transactional engines.

Why is MySQL so popular?

Among various databases available out there, MySQL is the most popular Database Management System that uses Structured Query Language. The one reason for its popularity is, it is open-source software that is freely available. And MySQL is flexible enough to also work in a dynamic environment. MySQL is faster than other databases and it is platform-independent and compatible with many programming languages like C++, Java, Python, Javascript, PHP, Ruby, etc. The community of MySQL is very large, so if you are stuck anywhere then you can get help from the community.

Features Of MySQL

  1. Open-Source
  2. Quick and Reliable
  3. Scalable
  4. Data Types
  5. Character Sets
  6. Secure
  7. Support for large Databases
  8. Speed
  9. High Flexibility
  10. Allows Rollback
  11. GUI Support and many more

Install, configure and secure MySQL on ubuntu 22.04. This article will teach how to install, configure and secure MySQL on the ubuntu 22.04 system.

How to Install MySQL on Ubuntu 22.04

1. Prerequisites

  • The operating system running Ubuntu 22.04 Linux
  • A root or non-root user with Sudo privileges
  • Has stable internet connection
  • Terminal window / Command line

2. Update Local Repositories

Updating the local package with the apt-get command. Open a terminal window and run the following command:

3. Install MySQL Server

Please run the following command as sudo to install MySQL from APT-GET repositories.

The [Y / n] question to continue with the installation may appear during the installation process, press the Y key from the keyboard and hit Enter. This will install MySQL on the system.

4. Verify MySQL

After the installation, the MySQL server should start automatically. To check if it’s running, run the following command:

5. Managing the MySQL Process

Now that you have your MySQL up and running, let’s go over basic management commands.

To stop your MySQL, run this command:

To start your MySQL, run this command:

To status your web server, run this command:

6. Configure MySQL Server

By default, MySQL lacks many basic and essential security features. Luckily, it comes with an installation script that walks you through the configuration. Use the mysql_secure_installation command:

You will be asked to configure the VALIDATE PASSWORD PLUGIN which is used to test the strength of the MySQL user’s passwords and improve their security. Type Y to start the Validate Password plugin and you will get the following prompt:

Enter the number for the password strength and press the Enter key:

On the next screen, enter and re-enter the password:

The system will then display the strength of the password you provided and also ask you if you want to continue with the password.

Type Y for Yes and press Enter.

If you get an error:

Login to MySQL First:

Set Root Password:

Exit MySQL:

Run the Secure Installation Script Again:

The script will ask these questions:

  1. Enter the password for user root: type your set password and then press ENTER.
  2. Change the password for root? Press N, then ENTER.
  3. Remove anonymous users? Press Y, then ENTER.
  4. Disallow root login remotely? Press Y, then ENTER.
  5. Remove test database and access to it? Press Y, then ENTER.
  6. Reload privilege tables now? Press Y, then ENTER.

7. Log into Mysql And Configuring

Now, when all is set, let’s log in to MySQL with the root user. In the terminal, run the following command:

To check which authentication method each MySQL user uses, run the following command:

Change the authentication method from auth_socket to mysql_native_password. You can do that by running the following command:

After executing the ALTER USER command, run the following command:

Now, if you recheck the authentication method for your MySQL user accounts using the following command, you see that your root user is now using the mysql_native_password plugin for authentication:

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

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