- Installing mysql linux ubuntu
- Install MySQL
- Allow remote access
- Start the MySQL service
- Launch at reboot
- Configure interfaces
- Start the mysql shell
- Set the root password
- View users
- User hosts
- Anonymous users
- Create a database
- Add a database user
- Grant database user permissions
- Summary
- Related articles
- Share this information:
- Установка MySQL в Ubuntu 20.04
- Установка MySQL 8 в Ubuntu
- Установка MySQL 5.7 в Ubuntu
- Настройка mysql в Ubuntu
- Удаление MySQL в Ubuntu
- Выводы
Installing mysql linux ubuntu
Last updated on: 2019-12-20
Authored by: Jered Heeschen
MySQL is an open-source relational database that is free and widely used. It is a good choice if you know that you need a database but don’t know much about all the available options.
This article describes a basic installation of a MySQL database server on the Ubuntu operating system. You might need to install other packages to let applications use MySQL, like extensions for PHP. Check your application documentation for details.
Install MySQL
Install the MySQL server by using the Ubuntu operating system package manager:
The installer installs MySQL and all dependencies.
If the secure installation utility does not launch automatically after the installation completes, enter the following command:
This utility prompts you to define the mysql root password and other security-related options, including removing remote access to the root user and setting the root password.
Allow remote access
If you have iptables enabled and want to connect to the MySQL database from another machine, you must open a port in your server’s firewall (the default port is 3306). You don’t need to do this if the application that uses MySQL is running on the same server.
Run the following command to allow remote access to the mysql server:
Start the MySQL service
After the installation is complete, you can start the database service by running the following command. If the service is already started, a message informs you that the service is already running:
Launch at reboot
To ensure that the database server launches after a reboot, run the following command:
Configure interfaces
MySQL, by default is no longer bound to ( listening on ) any remotely accessible interfaces. Edit the “bind-address” directive in /etc/mysql/mysql.conf.d/mysqld.cnf:
Restart the mysql service.
Start the mysql shell
There is more than one way to work with a MySQL server, but this article focuses on the most basic and compatible approach, the mysql shell.
At the command prompt, run the following command to launch the mysql shell and enter it as the root user:
When you’re prompted for a password, enter the one that you set at installation time, or if you haven’t set one, press Enter to submit no password.
The following mysql shell prompt should appear:
Set the root password
If you logged in by entering a blank password, or if you want to change the root password that you set, you can create or change the password.
For versions earlier than MySQL 5.7, enter the following command in the mysql shell, replace password with your new password:
For version MySQL 5.7 and later, enter the following command in the mysql shell, replacing password with your new password:
To make the change take effect, reload the stored user information with the following command:
Note: We’re using all-caps for SQL commands. If you type those commands in lowercase, they’ll work. By convention, the commands are written in all-caps to make them stand out from field names and other data that’s being manipulated.
If you need to reset the root password later, see Reset a MySQL root password.
View users
MySQL stores the user information in its own database. The name of the database is mysql. Inside that database the user information is in a table, a dataset, named user. If you want to see what users are set up in the MySQL user table, run the following command:
The following list describes the parts of that command:
- SELECT tells MySQL that you are asking for data.
- User, Host, authentication_string tells MySQL what fields you want it to look in. Fields are categories for the data in a table. In this case, you are looking for the username, the host associated with the username, and the encrypted password entry.
- FROM mysql.user » tells MySQL to get the data from the mysql database and the user table.
- A semicolon (;) ends the command.
Note: All SQL queries end in a semicolon. MySQL does not process a query until you type a semicolon.
User hosts
The following example is the output for the preceding query:
Users are associated with a host, specifically, the host from which they connect. The root user in this example is defined for localhost, for the IP address of localhost, and the hostname of the server. You usually need to set a user for only one host, the one from which you typically connect.
If you’re running your application on the same computer as the MySQL server, the host that it connects to by default is localhost. Any new users that you create must have localhost in their host field.
If your application connects remotely, the host entry that MySQL looks for is the IP address or DNS hostname of the remote computer (the one from which the client is coming).
Anonymous users
In the example output, one entry has a host value but no username or password. That’s an anonymous user. When a client connects with no username specified, it’s trying to connect as an anonymous user.
You usually don’t want any anonymous users, but some MySQL installations include one by default. If you see one, you should either delete the user (refer to the username with empty quotes, like ‘ ‘) or set a password for it.
Create a database
There is a difference between a database server and a database, even though those terms are often used interchangeably. MySQL is a database server, meaning it tracks databases and controls access to them. The database stores the data, and it is the database that applications are trying to access when they interact with MySQL.
Some applications create a database as part of their setup process, but others require you to create a database yourself and tell the application about it.
To create a database, log in to the mysql shell and run the following command, replacing demodb with the name of the database that you want to create:
After the database is created, you can verify its creation by running a query to list all databases. The following example shows the query and example output:
Add a database user
When applications connect to the database using the root user, they usually have more privileges than they need. You can add users that applications can use to connect to the new database. In the following example, a user named demouser is created.
To create a new user, run the following command in the mysql shell:
When you make changes to the user table in the mysql database, tell MySQL to read the changes by flushing the privileges, as follows:
Verify that the user was created by running a SELECT query again:
Grant database user permissions
Right after you create a new user, it has no privileges. The user can log in, but can’t be used to make any database changes.
Give the user full permissions for your new database by running the following command:
Flush the privileges to make the change official by running the following command:
To verify that those privileges are set, run the following command:
MySQL returns the commands needed to reproduce that user’s permissions if you were to rebuild the server. USAGE on \*.\* means the users gets no privileges on anything by default. That command is overridden by the second command, which is the grant you ran for the new database.
Summary
If you’re just creating a database and a user, you are done. The concepts covered here should give you a solid start from which to learn more.
Related articles
Share this information:
©2020 Rackspace US, Inc.
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License
Источник
Установка MySQL в Ubuntu 20.04
MySQL — это одна из самых популярных систем управления базами данных, которая применяется почти везде, начиная от различных предприятий и промышленности и заканчивая организацией работы веб-сайтов.
Сейчас существует несколько версий MySQL. Непосредственно MySQL, разрабатываемая компанией Oracle и свободный форк от основного разработчика MySQL — MariaDB. Имя MairaDB программа получила в честь первой дочери программиста, также как и MySQL в честь имени второй. В большинстве дистрибутивов Linux используется MariaDB, в том числе и в Ubuntu. Но в этой статье давайте рассмотрим установку именно MySQL в Ubuntu 20.04.
Установка MySQL 8 в Ubuntu
Программа и все необходимые компоненты есть в официальных репозиториях, поэтому установить её не составит труда. Для установки из официальных репозиториев сначала обновите списки пакетов:
sudo apt update
Затем установите необходимые пакеты:
sudo apt install mysql-server mysql-client
На данный момент в репозиториях Ubuntu 20.04 есть уже версия Mysql 8.20. Вы можете проверить установленную версию такой командой:
Кроме того, желательно проверить, запущенна ли служба MySQL:
sudo systemctl status mysql
Вы должны увидеть зеленую надпись Active, Running и версию программы, которую устанавливали.
Установка MySQL 5.7 в Ubuntu
Если вам нужна версия 5.7, то её в репозиториях нет, но вы можете получить эту версию из репозитория разработчика. Если в системе уже есть более новая версия, её надо полностью удалить:
sudo apt remove —autoremove mysql-server mysql-client
Также удалите каталог с базами данных MySQL они не совместимы со старой версией:
sudo rm -Rf /var/lib/mysql
Для установки репозитория скачайте этот пакет:
sudo wget https://dev.mysql.com/get/mysql-apt-config_0.8.12-1_all.deb
Затем установите его:
sudo dpkg -i mysql-apt-config_0.8.12-1_all.deb
В процессе установки программа попросит выбрать дистрибутив. Если у вас Ubuntu 20.04 или выше, выбирайте версию для Ubuntu 18.04 — bionic:
Затем выберите MySQL Server and Cluster:
После этого останется выбрать нужную версию MySQL, например 5.7:
После этого обновите списки репозиториев и посмотрите какие версии MySQL доступны:
sudo apt update
sudo apt-cache policy mysql-server
Осталось установить установить mysql 5.7 в Ubuntu:
sudo apt install mysql-server=5.7.31-1ubuntu18.04 mysql-community-server=5.7.31-1ubuntu18.04 mysql-client=5.7.31-1ubuntu18.04
В процессе установки программа запросит пароль для root пользователя:
После этого вы снова можете посмотреть версию:
Настройка mysql в Ubuntu
Перед тем как вы сможете полноценно использовать только что установленную базу данных, необходимо выполнить ее первоначальную настройку. Для этого был разработан специальный скрипт, выполните его:
На первом шаге настраивается плагин валидации пароля. Чтобы его включить нажмите Y, или его можно не включать. Затем надо задать сложность пароля, который позволит установить этот плагин. Здесь 0 означает слабый пароль, а 2 — сложный. Когда плагин будет настроен введите пароль root и подтвердите, что хотите использовать именно его:
Введите Y для отключения анонимного доступа к MySQL, затем ещё раз Y чтобы запретить подключаться к базе от имени root удаленно:
Снова Y, чтобы удалить тестовую базу данных. Затем, обновите привилегии для пользователей:
После завершения настройки вы можете подключиться к пользователя root к серверу баз данных из командной строки:
sudo mysql -u root
Здесь нам необходимо создать пользователя, от имени которого мы будем использовать базу данных, а также саму базу данных. Для этого воспользуемся командами SQL. Сначала создаем базу данных:
mysql> CREATE DATABASE testDB;
Далее создадим пользователя:
mysql> CREATE USER ‘my_user’@’localhost’ IDENTIFIED BY ‘password’;
Слова my_user и password нужно заменить на свои имя пользователя и пароль. Дальше нужно дать права пользователю на управление этой базой данных:
mysql> GRANT ALL PRIVILEGES ON testDB.* TO ‘my_user’@’localhost’
Или вы можете дать права только на несколько инструкций:
mysql> GRANT SELECT,UPDATE,DELETE ON testDB.* TO ‘my_user’@’localhost’;
Если какую-либо инструкцию нужно запретить, удалите ее:
mysql> REVOKE UPDATE ON testDB.* FROM ‘my_user’@’localhost’;
После завершения работы с правами нужно их обновить:
mysql> FLUSH PRIVILEGES;
Чтобы убедиться что нет никого лишнего, вы можете вывести список пользователей:
mysql> SELECT user,host FROM mysql.user;
Также вы можете посмотреть полномочия для нужного пользователя:
mysql> SHOW GRANTS FOR ‘my_user’@’localhost’;
Теперь установка MySQL Ubuntu 20.04 полностью завершена и вы можете использовать эту базу данных для решения своих задач.
Удаление MySQL в Ubuntu
Чтобы удалить mysql Ubuntu 20.04 понадобиться немного больше команд чем для удаления простого пакета. После удаления основных пакетов в системе остается еще много файлов. Мы рассмотрим как удалить все.
Сначала остановите сервисы:
sudo systemctl stop mysql
sudo killall -KILL mysql mysqld_safe mysqld
Удалите основные пакеты и их зависимости:
sudo apt -y purge mysql-server mysql-client
sudo apt -y autoremove —purge
sudo apt autoclean
Удалите пользователя mysql и остатки программы в системе:
deluser —remove-home mysql
sudo delgroup mysql
rm -rf /etc/apparmor.d/abstractions/mysql /etc/apparmor.d/cache/usr.sbin.mysqld /etc/mysql /var/lib/mysql /var/log/mysql* /var/log/upstart/mysql.log* /var/run/mysqld
updatedb
Удалите все логи подключений к mysql из терминала:
sudo find / -name .mysql_history -delete
Теперь ваша система полностью очищена от MySQL.
Выводы
В этой статье мы рассмотрели как выполняется установка MySQL в Ubuntu 20.04. Как видите, это не очень трудно, хотя и требует некоторых знаний и немного времени на то, чтобы со всем разобраться. Надеюсь, эта информация была для вас полезной.
Источник