Перезапуск MySQL
MySQL — это самая популярная система баз данных, которая используется для обеспечения работы большинства сайтов. Пока вы размещаете свой сайт на хостинге, вам нет необходимости думать о её настройке или своевременной перезагрузке, потому что этим занимаются системные администраторы хостинга. Но когда вы переберётесь на VPS, это всё будет уже в зоне вашей ответственности.
В этой статье мы рассмотрим, как выполняется перезапуск MySQL в разных дистрибутивах Linux, а также как сделать, чтобы MySQL перезапускалась автоматически после падения.
Перезапуск MySQL или MariaDB
В большинстве современных дистрибутивов, а особенно тех, что используются для работы серверов, для управления службами применяют Systemd. Именно с её помощью мы будем перезапускать движок баз данных. Ещё один момент, с которым нужно определиться, — это название юнит-файла MySQL. В зависимости от версии и дистрибутива оно может отличаться:
Вы можете попробовать использовать эти варианты, чтобы найти тот, что используется в вашей системе; последние версии Ubuntu понимают несколько имен MySQL. Таким образом, для MariaDB и выше перезапуск MySQL Сentos и Ubuntu не отличается. Просто попробуйте узнать состояние сервиса, если вы выбрали правильное название, то увидите что-то вроде этого:
Выполнить частичную перезагрузку только с обновлением конфигурации, так как это делалось в Apache и Nginx вы не сможете. Здесь необходимо полностью перезагружать сервис:
sudo systemctl restart mysql
В некоторых случаях необходимо полностью остановить работающий сервис, а потом запустить его заново. Для этого используем команду stop, затем start:
sudo systemctl stop mysql
sudo systemctl start mysql
Автоматический перезапуск MySQL
Из-за проблем с памятью на сервере или других ошибок MySQL может завершить свою работу. Это очень неприятное обстоятельство, поскольку вы не можете всегда следить за сервером, а когда такое случиться, ваш сайт будет недоступен для пользователей на протяжении долгого времени.
В systemd есть возможность, которая позволяет делать рестарт MySQL сразу же после того, как он неожиданно завершился. Для этого необходимо добавить такую строчку в конфигурацию юнит-файла MySQL:
Но обратите внимание, что редактировать файлы юнитов в папке /usr нельзя, потому что во время обновления они могут быть перезаписаны, можно только в /etc, и желательно создавать отдельный файл. Можно поступить проще: используйте команду systemctl edit:
sudo systemctl edit mariadb
Сохраните изменения. Эти строки будут записаны в виде отдельного файла, который автоматически подключается к основному.
Выводы
В этой статье мы рассмотрели, как перезапустить MySQL для обновления конфигурации, а также как настроить автоматический перезапуск службы после возникновения ошибок. Если у вас остались вопросы, спрашивайте в комментариях!
How do I start a MySQL server on Windows?
I’ve installed a MySQL server onto my computer and when I first installed it, it ran automatically. Now I’ve restarted my computer it is no longer running. What file do I need to run to get it back up and running again?
I’ve tried running MySQL 5.6 Command Line Client and mysqld.exe from the Program Files/MySQL/MySQLServer/bin directory, and I’ve had no luck.
Upon running mysqld.exe, I get the following error:
Naturally, I tried running it as administrator, and I got this:
5 Answers 5
Make sure the mysqld.exe is ticked under the Startup tab when you go to run and type msconfig . Also, same goes for Services , look for the MySQL services there, right click > properties and make sure the startup types are selected as automatic.
If you installed MySQL using the MSI installer, it should be set up as a service.
You can open the service in two ways
METHOD #1: Access the Installed Service
- Open up the Services icon in the Control Panel
- Scroll alphabetically to the MySQL service
- Right click the service
- Click Start Service
METHOD #2: Command Line Execution
- Open DOS Window
- From the C: Prompt, run this: net start mysql or ‘net start mysql57’. The right name may vary on your system
If you get this error
then you didn’t run the DOS Window as Administrator. Try again as administrator. You should see:
Give it a try.
I had the similar issue and found later that the encoding of my.ini file changes if you open that from notepad. Open the file from Notepad++ and make sure to take a note of the .ini file encoding (mostly it is UTF-8). If the file encoding changes SQL service will not start. Make sure that the new directory in which the data path is set has permissions for the account that runs the mySQLd service in windows (mostly it is network service).
If you are using wamp on windows, you can start mysql from command line by :
This assumes that you have installed wamp at the root
In order to start manually the mysql serve you must run the mysqld executable. Open the command prompt and type:
If mysqld doesn’t start, check the error log. The error log is located in the C:\Program Files\MySQL\MySQLServer\data. It is the file with a suffix of .err. You can also try to start the server as mysqld —console; in this case, you may get some useful information on the screen that may help solve the problem.
Chapter 2 Starting the Server for the First Time on Windows
This section gives a general overview of starting the MySQL server. The following sections provide more specific information for starting the MySQL server from the command line or as a Windows service.
The information here applies primarily if you installed MySQL using the noinstall version, or if you wish to configure and test MySQL manually rather than with the MySQL Installer.
The examples in these sections assume that MySQL is installed under the default location of C:\Program Files\MySQL\MySQL Server 8.0 . Adjust the path names shown in the examples if you have MySQL installed in a different location.
Clients have two options. They can use TCP/IP, or they can use a named pipe if the server supports named-pipe connections.
MySQL for Windows also supports shared-memory connections if the server is started with the shared_memory system variable enabled. Clients can connect through shared memory by using the —protocol=MEMORY option.
For information about which server binary to run, see Selecting a MySQL Server Type.
Testing is best done from a command prompt in a console window (or “ DOS window ” ). In this way you can have the server display status messages in the window where they are easy to see. If something is wrong with your configuration, these messages make it easier for you to identify and fix any problems.
The database must be initialized before MySQL can be started. For additional information about the initialization process, see Initializing the Data Directory.
To start the server, enter this command:
For a server that includes InnoDB support, you should see the messages similar to those following as it starts (the path names and sizes may differ):
When the server finishes its startup sequence, you should see something like this, which indicates that the server is ready to service client connections:
The server continues to write to the console any further diagnostic output it produces. You can open a new console window in which to run client programs.
If you omit the —console option, the server writes diagnostic output to the error log in the data directory ( C:\Program Files\MySQL\MySQL Server 8.0\data by default). The error log is the file with the .err extension, and may be set using the —log-error option.
The initial root account in the MySQL grant tables has no password. After starting the server, you should set up a password for it using the instructions in Securing the Initial MySQL Account.