Установка mariadb [mysql] на ubuntu server 18.04

Schritt 2 — MySQL konfigurieren

Bei Neuinstallationen sollten Sie das mitgelieferte Sicherheitsskript ausführen. Dies ändert einige der weniger sicheren Standardoptionen für Dinge wie Remote-Root-Logins und Musterbenutzer. Bei älteren MySQL-Versionen mussten Sie das Datenverzeichnis auch manuell initialisieren, aber das erfolgt jetzt automatisch.

Führen Sie das Sicherheitsskript aus:

Dies führt Sie durch eine Reihe von Eingabeaufforderungen, in denen Sie einige Änderungen an den Sicherheitsoptionen Ihrer MySQL-Installation vornehmen können. Die erste Eingabeaufforderung fragt, ob Sie das validierte Passwort-Plugin einrichten möchten, mit dem Sie die Stärke Ihres MySQL-Passworts testen können. Unabhängig von Ihrer Wahl wird die nächste Eingabeaufforderung darin bestehen, ein Passwort für den MySQL-Root-Benutzer festzulegen. Geben Sie ein sicheres Passwort Ihrer Wahl ein und bestätigen Sie es anschließend.

Von dort aus können Sie und dann drücken, um die Standardwerte für alle folgenden Fragen zu übernehmen. Dadurch werden einige anonyme Benutzer und die Testdatenbank entfernt, Remote-Root-Logins deaktiviert und diese neuen Regeln geladen, so dass MySQL die von Ihnen vorgenommenen Änderungen sofort berücksichtigt.

Um das MySQL-Datenverzeichnis zu initialisieren, verwenden Sie für Versionen vor 5.7.6 und für 5.7.6 und später. Wenn Sie jedoch MySQL aus der Debian-Distribution installiert haben, wie in Schritt 1 beschrieben, wurde das Datenverzeichnis automatisch initialisiert; Sie müssen nichts tun. Wenn Sie versuchen, den Befehl trotzdem auszuführen, wird folgender Fehler angezeigt:

Output

Beachten Sie, dass, obwohl Sie ein Passwort für den MySQL-Root-Benutzer festgelegt haben, dieser nicht konfiguriert ist, um sich bei der Verbindung mit der MySQL-Shell mit einem Passwort zu authentifizieren. Bei Bedarf können Sie diese Einstellung anpassen, indem Sie Schritt 3 folgen.

Step 1 — Adding the MySQL Software Repository

The MySQL developers provide a package that handles configuring and installing the official MySQL software repositories. Once the repositories are set up, we’ll be able to use Ubuntu’s standard command to install the software. We’ll download this file with and then install it with the command.

First, load the MySQL download page in your web browser. Find the Download button in the lower-right corner and click through to the next page. This page will prompt you to log in or sign up for an Oracle web account. We can skip that and instead look for the link that says No thanks, just start my download. Right-click the link and select Copy Link Address (this option may be worded differently, depending on your browser).

Now we’re going to download the file. On your server, move to a directory you can write to:

Download the file using , remembering to paste the address you just copied in place of the highlighted portion below:

We need to pass two command line flags to . instructs to output to a file instead of standard output. The flag makes follow HTTP redirects, necessary in this case because the address we copied actually redirects us to another location before the file downloads.

The file should now be downloaded in our current directory. List the files to make sure:

You should see the filename listed:

Now we’re ready to install:

is used to install, remove, and inspect software packages. The flag indicates that we’d like to install from the specified file.

During the installation, you’ll be presented with a configuration screen where you can specify which version of MySQL you’d prefer, along with an option to install repositories for other MySQL-related tools. The defaults will add the repository information for the latest stable version of MySQL and nothing else. This is what we want, so use the down arrow to navigate to the menu option and hit .

The package will now finish adding the repository. Refresh your package cache to make the new software packages available:

Let’s also clean up after ourselves and delete the file we downloaded:

Now that we’ve added the MySQL repositories, we’re ready to install the actual MySQL server software. If you ever need to update the configuration of these repositories, just run , select new options, and then to refresh your package cache.

Шаг 4 — Настройка Nginx для работы с обработчиком PHP

Теперь у нас установлены все необходимые компоненты. Единственное, что нам осталось сделать, это настроить Nginx для использования нашего обработчика PHP для отображения динамического контента.

Мы сделаем это на уровне серверных блоков (серверные блоки являются приблизительным аналогом виртуальных хостов в Apache). Откроем серверный блок Nginx сервера по умолчанию командой:

Этот файл должен иметь примерно следующий вид:

/etc/nginx/sites-available/default

  • Прежде всего, нам необходимо добавить первым значением директивы , чтобы веб-сервер в первую очередь искал файлы .
  • Мы можем изменить директиву для указания доменного имени сервера или его публичного IP адреса.
  • Для корректной обработки PHP нам необходимо раскомментировать часть файла, которая отвечает за обработку PHP запросов. Это блок , кусок кода и сокет для работы с .
  • Мы также раскомментируем код, отвечающий за работу с файлами . Nginx не обрабатывает эти файлы. Если какие-то из этих файлов окажутся в корневой директории сайта, они не должны быть доступны пользователям.

Изменения, которые необходимо внести в этот файл помечены красным:

/etc/nginx/sites-available/default

После внесения изменений сохраните и закройте файл.

Проверьте ваш файл конфигурации на наличие ошибок командой:

Если в результате обнаружены какие-либо ошибки, откройте файл и исправьте их перед тем, как продолжить.

Когда всё готово, перезапустите Nginx для применения внесённых изменений:

Перед установкой

Перед тем, как мы начнём, убедитесь, что у вас есть всё необходимое.

Прежде всего, мы будем исходить из того, что у вас есть не-рутовый (non-root) пользователь с привилегиями sudo. Настроить такую учётную запись пользователя можно следуя шагам 1-4 в статье о первичной настройке сервера на Ubuntu 16.04.

Мы также будем считать, что вы завершили настройку стека LAMP (Linux, Apache, MySQL и PHP) на вашем сервере с Ubuntu 16.04. Если вы ещё не сделали этого, вы можете ознакомиться с этим процессом в статье об установке стека LAMP на Ubuntu 16.04.

И, наконец, необходимо иметь в виду некоторые вопросы безопасности при использовании phpMyAdmin, поскольку он:

  • Напрямую взаимодействует с MySQL.
  • Выполняет аутентификацию использую логин и пароль MySQL.
  • Выполняет и возвращает результаты произвольных запросов SQL.

По этим причинам, а также потому, что phpMyAdmin является одним из наиболее распространённых и атакуемых PHP приложений, вам не стоит запускать phpMyAdmin на удалённых машинах с простым соединением HTTP. Если у вас ещё нет домена с настроенным SSL/TLS сертификатом, рекомендуем ознакомиться со статьёй Делаем Apache безопаснее с помощью Let’ Encrypt на Ubuntu 16.04.

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

Step 1 — Installing MySQL

There are two ways to install MySQL. You can either use one of the versions included in the APT package repository by default (which are 5.5 and 5.6), or you can install the latest version (currently 5.7) by manually adding MySQL’s repository first.

If you want to install a specific version of MySQL, follow the appropriate section below. To help you decide which version is best for you, you can read MySQL’s introduction to MySQL 5.5, then what’s new in MySQL 5.6 and what’s new in MySQL 5.7.

If you’re not sure, you can just use the APT package, which just installs the latest version for your Linux distribution. At the time of writing, that’s 5.5, but you can always update to another version later.

To install MySQL this way, update the package index on your server and install the package with .

You’ll be prompted to create a root password during the installation. Choose a secure one and make sure you remember it, because you’ll need it later. Move on to step two from here.

Installing MySQL 5.5 or 5.6

If you want to install MySQL 5.5 or 5.6 specifically, the process is still very straightforward. First, update the package index on your server.

Then, to install MySQL 5.5, install the package.

To install MySQL 5.6, install the package instead.

For both options, you’ll be prompted to create a root password during the installation. Choose a secure one and make sure you remember it, because you’ll need it later.

Installing MySQL 5.7

If you want to install MySQL 5.7, you’ll need to add the newer APT package repository from the MySQL APT repository page. Click Download on the bottom right, then copy the link on the next page from No thanks, just start my download. Download the package to your server.

Next, install it using .

You’ll see a prompt that asks you which MySQL product you want to configure. The MySQL Server option, which is highlighted, should say mysql-5.7. If it doesn’t, press , then scroll down to mysql-5.7 using the arrow keys, and press again.

Once the option says mysql-5.7, scroll down on the main menu to Apply and press again. Now, update your package index.

Finally, install the package, which now contains MySQL 5.7.

You’ll be prompted to create a root password during the installation. Choose a secure one and make sure you remember it, because you’ll need it later.

Step 3 — (Optional) Adjusting User Authentication and Privileges

In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL 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) to access the user.

In order to use a password to connect to MySQL as root, you will need to switch its authentication method from to . To do this, open up the MySQL prompt from your terminal:

Next, check which authentication method each of your MySQL user accounts use with the following command:

In this example, you can see that the root user does in fact authenticate using the plugin. To configure the root account to authenticate with a password, run the following command. Be sure to change to a strong password of your choosing, and note that this command will change the root password you set in Step 2:

Then, run which tells the server to reload the grant tables and put your new changes into effect:

Check the authentication methods employed by each of your users again to confirm that root no longer authenticates using the plugin:

You can see in this example output that the root MySQL user now authenticates using a password. Once you confirm this on your own server, you can exit the MySQL shell:

Alternatively, some may find that it better suits their workflow to connect to MySQL with a dedicated user. To create such a user, open up the MySQL shell once again:

Note: If you have password authentication enabled for root, as described in the preceding paragraphs, you will need to use a different command to access the MySQL shell. The following will run your MySQL client with regular user privileges, and you will only gain administrator privileges within the database by authenticating:

From there, create a new user and give it a strong password:

Then, grant your new user the appropriate privileges. For example, you could grant the user privileges to all tables within the database, as well as the power to add, change, and remove user privileges, with this command:

Note that, at this point, you do not need to run the command again. This command is only needed when you modify the grant tables using statements like , , or . Because you created a new user, instead of modifying an existing one, is unnecessary here.

Following this, exit the MySQL shell:

Finally, let’s test the MySQL installation.

Schritt 4 — MySQL testen

Unabhängig davon, wie Sie es installiert haben, sollte MySQL automatisch gestartet sein. Um dies zu testen, überprüfen Sie den Status.

Sie werden folgende Meldung sehen:

Output

Wenn MySQL nicht ausgeführt wird, können Sie es mit starten.

Für eine zusätzliche Überprüfung können Sie versuchen, sich mit der Datenbank zu verbinden, indem Sie das Tool verwenden, ein Client, mit dem Sie administrative Befehle ausführen können. Dieser Befehl besagt beispielsweise, sich als root () mit MySQL zu verbinden, ein Passwort () einzugeben und die Version zurückzugeben.

Sie sollten folgende Meldung sehen:

Output

Das bedeutet, dass MySQL ausgeführt wird.

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

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

Чтобы использовать пароль для аутентификации root пользователя MySQL, вам необходимо переключить метод аутентификации с auth_socket на другой плагин, например на caching_sha2_password или mysql_native_password. Для этого откройте командную строку MySQL:

Теперь уточните, какой метод аутентификации использует каждый ваш пользователь MySQL:

В нашем случае root-пользователь проходит аутентификацию по плагину auth_socket. Чтобы настроить его для парольной аутентификации, запустите команду ALTER USER.

Вместо password выберите надежный пароль. Имейте в виду: этот пароль заменит тот пароль, что вы выбрали в разделе 2.

Примечание: Данный оператор ALTER USER настраивает root-пользователя MySQL для аутентификации с помощью плагина caching_sha2_password. Согласно , плагин caching_sha2_password рекомендуется использовать для аутентификации MySQL, поскольку он обеспечивает более безопасное шифрование паролей, чем старый, но все еще широко используемый mysql_native_password.

Однако многие приложения PHP – например, phpMyAdmin – не очень хорошо поддерживают caching_sha2_password. Если вы планируете использовать эту базу данных с приложением PHP, рекомендуем настроить аутентификацию root с помощью плагина mysql_native_password:

Затем запустите FLUSH PRIVILEGES, чтобы перезагрузить таблицы привилегий и применить новые настройки:

Проверьте метод аутентификации пользователей, чтобы убедиться, что root больше не поддерживает плагин auth_socket:

Как видите, теперь корневой пользователь MySQL аутентифицируется с помощью caching_sha2_password. После этой проверки вы можете выйти из оболочки MySQL:

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

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

Создайте нового пользователя и выберите для него надежный пароль:

Затем предоставьте новому пользователю соответствующие привилегии. Например, с помощью этой команды вы можете предоставить ему привилегии на все таблицы в базе данных, а также право добавлять, изменять и удалять привилегии других пользователей:

Обратите внимание, на этом этапе вам не нужно снова запускать команду FLUSH PRIVILEGES. Она необходима только при изменении таблиц привилегий с помощью операторов INSERT, UPDATE или DELETE

Поскольку вы создали нового пользователя, а не меняли уже существующего, FLUSH PRIVILEGES здесь не нужна.

После этого выйдите из оболочки MySQL:

А сейчас давайте проверим установку MySQL.

Step 3 — Creating a Dedicated MySQL User and Granting Privileges

Upon installation, MySQL creates a root user account which you can use to manage your database. This user has full privileges over the MySQL server, meaning it has complete control over every database, table, user, and so on. Because of this, it’s best to avoid using this account outside of administrative functions. This step outlines how to use the root MySQL user to create a new user account and grant it privileges.

In Ubuntu systems running MySQL (and later versions), the root MySQL user is set to authenticate using the plugin by default rather than with a password. This plugin requires that the name of the operating system user that invokes the MySQL client matches the name of the MySQL user specified in the command, so you must invoke with privileges to gain access to the root MySQL user:

Note: If you installed MySQL with another tutorial and enabled password authentication for root, you will need to use a different command to access the MySQL shell. The following will run your MySQL client with regular user privileges, and you will only gain administrator privileges within the database by authenticating:

Once you have access to the MySQL prompt, you can create a new user with a statement. These follow this general syntax:

After , you specify a username. This is immediately followed by an sign and then the hostname from which this user will connect. If you only plan to access this user locally from your Ubuntu server, you can specify . Wrapping both the username and host in single quotes isn’t always necessary, but doing so can help to prevent errors.

You have several options when it comes to choosing your user’s authentication plugin. The plugin mentioned previously can be convenient, as it provides strong security without requiring valid users to enter a password to access the database. But it also prevents remote connections, which can complicate things when external programs need to interact with MySQL.

As an alternative, you can leave out the portion of the syntax entirely to have the user authenticate with MySQL’s default plugin, . for users who want to log in with a password due to its security.

Run the following command to create a user that authenticates with . Be sure to change to your preferred username and to a strong password of your choosing:

Note: There is a known issue with some versions of PHP that causes problems with . If you plan to use this database with a PHP application — phpMyAdmin, for example — you may want to create a user that will authenticate with the older, though still secure, plugin instead:

If you aren’t sure, you can always create a user that authenticates with and then it later on with this command:

After creating your new user, you can grant them the appropriate privileges. The general syntax for granting user privileges is as follows:

The value in this example syntax defines what actions the user is allowed to perform on the specified and . You can grant multiple privileges to the same user in one command by separating each with a comma. You can also grant a user privileges globally by entering asterisks () in place of the database and table names. In SQL, asterisks are special characters used to represent “all” databases or tables.

To illustrate, the following command grants a user global privileges to , , and databases, tables, and users, as well as the power to , , and data from any table on the server. It also grants the user the ability to query data with . However, you should only grant users the permissions they need, so feel free to adjust your own user’s privileges as necessary.

You can find the full list of available privileges in .

Run this statement, replacing with your own MySQL user’s name, to grant these privileges to your user:

Note that this statement also includes . This will allow your MySQL user to grant any that it has to other users on the system.

Warning: Some users may want to grant their MySQL user the privilege, which will provide them with broad superuser privileges akin to the root user’s privileges, like so:

Such broad privileges should not be granted lightly, as anyone with access to this MySQL user will have complete control over every database on the server.

Following this, it’s good practice to run the command. This will free up any memory that the server cached as a result of the preceding and statements:

Then you can exit the MySQL client:

In the future, to log in as your new MySQL user, you’d use a command like the following:

The flag will cause the MySQL client to prompt you for your MySQL user’s password in order to authenticate.

Finally, let’s test the MySQL installation.

Step 2 — Configuring MySQL

For fresh installations of MySQL, you’ll want to run the DBMS’s included security script. This script changes some of the less secure default options for things like remote root logins and sample users.

Run the security script with :

This will take you through a series of prompts where you can make some changes to your MySQL installation’s security options. The first prompt will ask whether you’d like to set up the Validate Password Plugin, which can be used to test the password strength of new MySQL users before deeming them valid.

If you elect to set up the Validate Password Plugin, any MySQL user you create that authenticates with a password will be required to have a password that satisfies the policy you select. The strongest policy level — which you can select by entering — will require passwords to be at least eight characters long and include a mix of uppercase, lowercase, numeric, and special characters:

Regardless of whether you choose to set up the Validate Password Plugin, the next prompt will be to set a password for the MySQL root user. Enter and then confirm a secure password of your choice:

Note that even though you’ve set a password for the root MySQL user, this user is not currently configured to authenticate with a password when connecting to the MySQL shell.

If you used the Validate Password Plugin, you’ll receive feedback on the strength of your new password. Then the script will ask if you want to continue with the password you just entered or if you want to enter a new one. Assuming you’re satisfied with the strength of the password you just entered, enter to continue the script:

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 MySQL immediately respects the changes you have made.

Once the script completes, your MySQL installation will be secured. You can now move on to creating a dedicated database user with the MySQL client.

Шаг 3 — Настройка конфигурации Apache для получения доступа к переопределению и перезаписи .htaccess

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

В этом обучающем руководстве в качестве примера мы будем использовать , а вам необходимо заменить путь к вашему файлу конфигурации в соответствующем месте. Также мы будем использовать ​​​ в качестве корневой директории для нашей установки WordPress. Вы должны использовать корневой веб-узел, указанный в вашей собственной конфигурации. Если вы следовали указаниям нашего руководства по LAMP, вы можете использовать ваше доменное имя вместо в обоих случаях.

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

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

Активация переопределения .htaccess

В настоящее время использование файлов отключено. WordPress и многие плагины WordPress активно используют эти файлы для манипуляций с поведением веб-сервера внутри директории.

Откройте файл конфигурации Apache для вашего веб-сайта с помощью текстового редактора, например nano.

Чтобы разрешить использование файлов , нам нужно настроить директиву внутри блока , которая будет указывать на корневую директорию документа. Добавьте следующий текстовый блок внутри блока в вашем файле конфигурации, убедившись, что вы используете правильную корневую веб-директорию:

/etc/apache2/sites-available/wordpress.conf

После завершения редактирования сохраните и закройте файл. В редакторе nano вы можете сделать это, нажав сочетание клавиш и , затем , затем .

Активация модуля перезаписи

Теперь мы сможем активировать для использования постоянных ссылок в WordPress:

Это позволит вам получать более удобные для восприятия постоянные ссылки для ваших постов, как в двух следующих примерах:

Команда ​​​ вызывает скрипт, который активирует заданный модуль в конфигурации Apache.

Активация изменений

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

Вывод может выглядеть следующим образом:

Если вы хотите скрыть верхнюю строку, добавьте директиву в ваш основной (глобальный) файл конфигурации Apache в . Вместо вы можете использовать домен или IP-адрес вашего сервера. Однако это просто сообщение, которое не влияет на функциональность вашего сайта. Если вывод содержит , вы можете двигаться дальше.

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

Теперь мы загрузим и настроим непосредственно WordPress.

Step 2 — Configuring MySQL

For fresh installations, you’ll want to run the included security script. This changes some of the less secure default options for things like remote root logins and sample users. On older versions of MySQL, you needed to initialize the data directory manually as well, but this is done automatically now.

Run the security script.

This will prompt you for the root password you created in Step 1. You can press and then to accept the defaults for all the subsequent questions, with the exception of the one that asks if you’d like to change the root password. You just set it in Step 1, so you don’t have to change it now. For a more detailed walkthrough of these options, you can see .

To initialize the MySQL data directory, you would use for versions before 5.7.6, and for 5.7.6 and later. However, if you installed MySQL from the Debian distribution, like in Step 1, the data directory was initialized automatically; you don’t have to do anything. If you try running the command anyway, you’ll see the following error:

Output

Finally, let’s test the MySQL installation.

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

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

Adblock
detector