Linux перезапустить сервер mysql

How do I start/stop mysql server?

I tried to find in some articles describing how to correctly start & stop mysql server. I found this link: How to start/stop MySql server on Ubuntu 8.04 | Abhi’s Blogging World I ran this command:

ERROR 1045 (28000) Access denied for user. 
sudo /etc/init.d/mysql - root -p start 
ERROR 1049 (42000) Unknown database 'start'. 

MySQL server success started. Cool! So, what’s wrong with the other commands? Why do they result in error?

In fact, even with sudo it didn’t work for me, but then I found in the script the following hint: Rather than invoking init scripts through /etc/init.d, use the service(8) and it was ok

Generally you can use sudo -l to see what your specific user on your specific system is allowed to do with sudo. (Your permissions are configured in /etc/sudoers.) However I don’t know for sure if it would help in this particular case. EDIT: Wait, never mind, the access denied error looks like it is coming from MySQL or something, not sudo.

11 Answers 11

Your first two commands weren’t run as root so that is expected behaviour. You need to be root to stop/start mysql.

should work. Indeed it does, for me:

kojan:~> sudo /etc/init.d/mysql restart [sudo] password for chris: Stopping MySQL database server: mysqld. Starting MySQL database server: mysqld. Checking for corrupt, not cleanly closed and upgrade needing tables.. 

I used restart rather than start, since it was already running, but the effect is the same. Are you sure you entered your password correctly? 🙂 Have you edited your sudo config at all which would stop this working?

sudo /etc/init.d/mysql - root -p start 

The arguments are wrong. an init.d script only takes start or stop or restart — just one word telling it what to do. You cannot give it multiple arguments as you were trying to do.

Anyway, the short answer is the one you actually got to work, is the recommended way. service is replacing all the init.d scripts over time, so you should get into the habit of using service . The page you link to was written in 2008, so has to be taken with some salt 🙂

Источник

Перезапуск MySQL

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

Читайте также:  Блокировка пароля пользователя linux

В этой статье мы рассмотрим, как выполняется перезапуск MySQL в разных дистрибутивах Linux, а также как сделать, чтобы MySQL перезапускалась автоматически после падения.

Перезапуск MySQL или MariaDB

В большинстве современных дистрибутивов, а особенно тех, что используются для работы серверов, для управления службами применяют Systemd. Именно с её помощью мы будем перезапускать движок баз данных. Ещё один момент, с которым нужно определиться, — это название юнит-файла MySQL. В зависимости от версии и дистрибутива оно может отличаться:

  • mysql-server;
  • mariadb-server;
  • mysql;
  • mariadb;
  • mariadbd
  • mysqld;

Вы можете попробовать использовать эти варианты, чтобы найти тот, что используется в вашей системе; последние версии 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 для обновления конфигурации, а также как настроить автоматический перезапуск службы после возникновения ошибок. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Перезагрузка MySQL-сервера в Linux

Наибольшее распространение дистрибутивы Linux имеют на серверах, а работа сервера чаще всего связана с использованием баз данных. Без базы данных невозможна работа любого динамического сайта, БД нужны для self-hosted сервисов и приложений. Тот же Home Asisstant использует БД для хранения исторических данных с сенсоров. В общем, если у вас есть сервер на Linux, то практически наверняка на нем запущен сервер MySQL.

И порой встречаются ситуации, когда сервер баз данных по какой-то причине подвисает и нуждается в перезагрузке.

Что нам понадобится

Для перезапуска сервера баз данных потребуется:

  • SSH-подключение к серверу
    Оставлю отсылку на свою старую статью про SSH на примере Raspberry Pi.
  • Административные доступы (root-права) к серверу
    По умолчанию только администратор (пользователь root ) имеет права на остановку или перезапуск системных процессов.

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

Читайте также:  Linux переход на новую строку

Как перезагрузить SQL-сервер

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

Ubuntu / Debian

В Ubuntu/Debian и системах на их основе можно использовать следующие команды для запуска, остановки и перезапуска SQL-сервера:

service mysql start service mysql stop service mysql restart
/etc/init.d/mysql start /etc/init.d/mysql stop /etc/init.d/mysql restart
systemctl start mysql systemctl stop mysql systemctl restart mysql

Fedora / CentOS

В Fedora/CentOS и системах на их основе (в частности, на популярной сборке BitrixVM для сайтов на базе «1С-Битрикс») команды немного отличаются — вместо mysql нужно использовать mysqld :

service mysqld start service mysqld stop service mysqld restart
systemctl start mysqld.service systemctl stop mysqld.service systemctl restart mysqld.service

macOS

Если MySQL установлен на десктопной macOS через Homebrew, то для управления им можно использовать следующие команды в терминале:

brew services start mysql brew services stop mysql brew services restart mysql

При этом использовать sudo не требуется — Homebrew всегда управляется из-под активного пользователя.

Заключение

Необходимость перезагрузки MySQL-сервера может ввести неопытного пользователя в ступор, но при знании азов работы в командной строке это не составляет проблемы. В различных версиях Linux команды для перезапуска запущенных процессов могут отличаться, так что пробуйте варианты пока какой-то из них не сработает.

Руководитель отдела в IT-компании. Веду этот блог с 2013 года, пишу о гаджетах и домашней автоматизации, обозреваю одноплатные компьютеры, неспешно собираю «умный дом».

Уведомления о статьях. 0% рекламы.

Источник

How to Restart MySQL in Ubuntu

MySQL is an RDMS (Relational Database Management System), which is used in the back-end development of any website, to store its data and the data is stored in the form of rows and columns, which are combined to form tables. With the help of MySQL, one can not only store data, but also can insert it, delete it, or modify it in tables, and to improve the performance of the system MySQL needs to be restarted. In this article, we will learn how to restart MySQL in Ubuntu by running simple commands.

How to validate the installation of MySQL in Ubuntu

Before restarting, MySQL first confirmed that MySQL is installed in Ubuntu or not. To verify this, we will run the command to check the version of MySQL:

The output is displaying the version details of MySQL which mean MySQL has been installed in Ubuntu.

How to restart MySQL using the systemctl command in Ubuntu

The systemctl command is used to start, restart, and stop the applications in Ubuntu and it is also used to check the status of applications. To restart MySQL, using the systemctl command:

Though successful execution of the above command without generating any error is the indication that MySQL has been restarted, we can confirm it by checking its status again using the systemctl command:

How to restart MySQL using the service command in Ubuntu

Likewise the systemctl command, the service command can also be used to manage the different applications to start, stop and restart. To restart MySQL in Ubuntu using the service command:

Читайте также:  Mobile operating system based on debian linux

Once the command is executed, it will ask for the password for authentication purposes:

Type password, and click on Authenticate to proceed with the command. To confirm the successful execution of the above command, check the status of MySQL using the service command:

How to restart MySQL through init.d process in Ubuntu

Similar to the service and systemctl command, we can start, stop, and restart the applications by using the init.d command with the path of MySQL in Ubuntu. Before restarting the MySQL let us understand what is init.d?

There are many other services like ssh, MongoDB, etc whose scripts are located in this directory. When Linux is started, it’s the first process that initialized in Ubuntu is init.d, later on, other services start using init.d Now using the extension of “.d” with the path of a directory, which is stands for daemon, we can run these services and also supervise the processes. To restart MySQL in Ubuntu using the init.d:

Though from the output, it is being obvious the MySQL has been restarted but to confirm this by checking its status, run the command:

Conclusion

In MySQL after making changes in any configuration file, it is recommended to restart the MySQL, so modified changes can be implemented. To restart the MySQL in Ubuntu is not very tough, one has to simply run some simple commands in the terminal.

This article is related to the methods of the restart of MySQL in Ubuntu, three methods are discussed by using the systemctl command, by using the service command, or by using the init.d command. It is not recommended to restart the MySQL regularly because it removes the cache memory while restarting, and also engines have to wait until it starts again, as a result, it decreases the performance.

About the author

Hammad Zahid

I’m an Engineering graduate and my passion for IT has brought me to Linux. Now here I’m learning and sharing my knowledge with the world.

Источник

Restart MySQL Server

Summary: in this tutorial, you will learn how to restart MySQL Server on Windows and Linux.

Restart MySQL Server on Windows

If MySQL installed as a Window service, you follow these steps to restart the MySQL Server:

First, open the Run window by using the Windows+R keyboard.

Second, type services.msc and press Enter :

Third, select the MySQL service and click the restart button.

Restart MySQL Server on Linux

You use the following command to restart the MySQL server On Linux:

service mysql restart Code language: SQL (Structured Query Language) (sql)

If the name is MySQL service is mysqld not mysql , you need to change the service name in the command as shown in the following command:

service mysqld restart Code language: SQL (Structured Query Language) (sql)

Or you can use the init.d to start the MySQL service:

 /etc/init.d/mysqld restart Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to restart the MySQL server on Windows and Linux.

Источник

Оцените статью
Adblock
detector