- HowTo SSH Restart Mysql Server on a Linux and Unix Command Line
- CentOS/RHEL/Fedora/Scientific Linux version 4.x/5.x/6.x or older users
- CentOS/RHEL/Fedora/Scientific Linux version 7.x or newer users
- Debian/Ubuntu Linux users
- FreeBSD Unix server user
- Перезапуск MySQL
- Перезапуск MySQL или MariaDB
- Автоматический перезапуск MySQL
- Выводы
- Linux stop mysql server
- TablePlus
- How to start, stop, and restart MySQL database server?
- Linux stop mysql server
- Overview of systemd
- Configuring systemd for MySQL
- Configuring Multiple MySQL Instances Using systemd
- Migrating from mysqld_safe to systemd
HowTo SSH Restart Mysql Server on a Linux and Unix Command Line
I ‘m using a CentOS, RHEL, Fedora Linux server. I want to restart my mysqld server after making some changes to my.cnf file. How do I restart mysql server from a command line on a Linux or Unix-like systems?
The syntax is as follows to start, stop, or restart the mysql server on a Linux or Unix-like systems. [donotprint]
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | None |
Est. reading time | 1m |
[/donotprint]You must run the following command as per your Linux/Unix variant. You must be the root user to run the following commands.
CentOS/RHEL/Fedora/Scientific Linux version 4.x/5.x/6.x or older users
CentOS/RHEL/Fedora/Scientific Linux version 7.x or newer users
The syntax is as follows to start mariadb/mysql server:
The syntax is as follows to stop mariadb/mysql server:
The syntax is as follows to restart mariadb/mysql server:
Debian/Ubuntu Linux users
The syntax is as follows to start/stop/restart mysql server:
FreeBSD Unix server user
To start the Mysql server type:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
To restart the Mysql server type:
To stop the Mysql server type:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Перезапуск 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 для обновления конфигурации, а также как настроить автоматический перезапуск службы после возникновения ошибок. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
Linux stop mysql server
MySQL distributions on Unix and Unix-like system include a script named mysql.server , which starts the MySQL server using mysqld_safe . It can be used on systems such as Linux and Solaris that use System V-style run directories to start and stop system services. It is also used by the macOS Startup Item for MySQL.
mysql.server is the script name as used within the MySQL source tree. The installed name might be different (for example, mysqld or mysql ). In the following discussion, adjust the name mysql.server as appropriate for your system.
For some Linux platforms, MySQL installation from RPM or Debian packages includes systemd support for managing MySQL server startup and shutdown. On these platforms, mysql.server and mysqld_safe are not installed because they are unnecessary. For more information, see Managing MySQL Server with systemd.
To start or stop the server manually using the mysql.server script, invoke it from the command line with start or stop arguments:
mysql.server changes location to the MySQL installation directory, then invokes mysqld_safe . To run the server as some specific user, add an appropriate user option to the [mysqld] group of the global /etc/my.cnf option file, as shown later in this section. (It is possible that you must edit mysql.server if you’ve installed a binary distribution of MySQL in a nonstandard location. Modify it to change location into the proper directory before it runs mysqld_safe . If you do this, your modified version of mysql.server may be overwritten if you upgrade MySQL in the future; make a copy of your edited version that you can reinstall.)
mysql.server stop stops the server by sending a signal to it. You can also stop the server manually by executing mysqladmin shutdown .
To start and stop MySQL automatically on your server, you must add start and stop commands to the appropriate places in your /etc/rc* files:
If you use the Linux server RPM package ( MySQL-server- VERSION .rpm ), or a native Linux package installation, the mysql.server script may be installed in the /etc/init.d directory with the name mysqld or mysql . See Installing MySQL on Linux Using RPM Packages from Oracle, for more information on the Linux RPM packages.
If you install MySQL from a source distribution or using a binary distribution format that does not install mysql.server automatically, you can install the script manually. It can be found in the support-files directory under the MySQL installation directory or in a MySQL source tree. Copy the script to the /etc/init.d directory with the name mysql and make it executable:
After installing the script, the commands needed to activate it to run at system startup depend on your operating system. On Linux, you can use chkconfig :
On some Linux systems, the following command also seems to be necessary to fully enable the mysql script:
On FreeBSD, startup scripts generally should go in /usr/local/etc/rc.d/ . Install the mysql.server script as /usr/local/etc/rc.d/mysql.server.sh to enable automatic startup. The rc(8) manual page states that scripts in this directory are executed only if their base name matches the *.sh shell file name pattern. Any other files or directories present within the directory are silently ignored.
As an alternative to the preceding setup, some operating systems also use /etc/rc.local or /etc/init.d/boot.local to start additional services on startup. To start up MySQL using this method, append a command like the one following to the appropriate startup file:
For other systems, consult your operating system documentation to see how to install startup scripts.
mysql.server reads options from the [mysql.server] and [mysqld] sections of option files. For backward compatibility, it also reads [mysql_server] sections, but to be current you should rename such sections to [mysql.server] .
You can add options for mysql.server in a global /etc/my.cnf file. A typical my.cnf file might look like this:
The mysql.server script supports the options shown in the following table. If specified, they must be placed in an option file, not on the command line. mysql.server supports only start and stop as command-line arguments.
Table 4.2 mysql.server Option-File Options
Option Name | Description | Type |
---|---|---|
basedir | Path to MySQL installation directory | Directory name |
datadir | Path to MySQL data directory | Directory name |
pid-file | File in which server should write its process ID | File name |
service-startup-timeout | How long to wait for server startup | Integer |
The path to the MySQL installation directory.
The path to the MySQL data directory.
The path name of the file in which the server should write its process ID. The server creates the file in the data directory unless an absolute path name is given to specify a different directory.
Источник
TablePlus
How to start, stop, and restart MySQL database server?
October 29, 2018
In this post, we are going to see how to start, stop, and restart MySQL Server on macOS, Linux, and Windows.
1. On Mac
You can start/stop/restart MySQL Server via the command line.
- For the version of MySQL older than 5.7:
- For the MySQL version 5.7 and newer:
- Or you can turn it on/off via the macOS Preference Panel
There’s another way which you can use DBngin, an free utility to install and manage multiple database servers on Mac.
- To turn on/off, it’s just one click away from the server control panel:
2. On Linux
- On Linux start/stop from the command line:
- Some Linux flavours offer the service command too
3. On Windows
- Open Run Window by Winkey + R
- Type services.msc
- Search MySQL service based on version installed.
- Click stop, start or restart the service option.
Or you can start/stop MySQL from the command prompt:
Need a good GUI tool for MySQL on MacOS and Windows? TablePlus is a modern, native tool with an elegant GUI that allows you to simultaneously manage multiple databases such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server and more.
Источник
Linux stop mysql server
If you install MySQL using an RPM or Debian package on the following Linux platforms, server startup and shutdown is managed by systemd:
RPM package platforms:
Enterprise Linux variants version 7 and higher
SUSE Linux Enterprise Server 12 and higher
Fedora 29 and higher
Debian family platforms:
If you install MySQL from a generic binary distribution on a platform that uses systemd, you can manually configure systemd support for MySQL following the instructions provided in the post-installation setup section of the MySQL 8.0 Secure Deployment Guide.
If you install MySQL from a source distribution on a platform that uses systemd, obtain systemd support for MySQL by configuring the distribution using the -DWITH_SYSTEMD=1 CMake option. See Section 2.9.7, “MySQL Source-Configuration Options”.
The following discussion covers these topics:
On platforms for which systemd support for MySQL is installed, scripts such as mysqld_safe and the System V initialization script are unnecessary and are not installed. For example, mysqld_safe can handle server restarts, but systemd provides the same capability, and does so in a manner consistent with management of other services rather than by using an application-specific program.
One implication of the non-use of mysqld_safe on platforms that use systemd for server management is that use of [mysqld_safe] or [safe_mysqld] sections in option files is not supported and might lead to unexpected behavior.
Because systemd has the capability of managing multiple MySQL instances on platforms for which systemd support for MySQL is installed, mysqld_multi and mysqld_multi.server are unnecessary and are not installed.
Overview of systemd
systemd provides automatic MySQL server startup and shutdown. It also enables manual server management using the systemctl command. For example:
Alternatively, use the service command (with the arguments reversed), which is compatible with System V systems:
For the systemctl command (and the alternative service command), if the MySQL service name is not mysqld then use the appropriate name. For example, use mysql rather than mysqld on Debian-based and SLES systems.
Support for systemd includes these files:
mysqld.service (RPM platforms), mysql.service (Debian platforms): systemd service unit configuration file, with details about the MySQL service.
mysqld@.service (RPM platforms), mysql@.service (Debian platforms): Like mysqld.service or mysql.service , but used for managing multiple MySQL instances.
mysqld.tmpfiles.d : File containing information to support the tmpfiles feature. This file is installed under the name mysql.conf .
mysqld_pre_systemd (RPM platforms), mysql-system-start (Debian platforms): Support script for the unit file. This script assists in creating the error log file only if the log location matches a pattern ( /var/log/mysql*.log for RPM platforms, /var/log/mysql/*.log for Debian platforms). In other cases, the error log directory must be writable or the error log must be present and writable for the user running the mysqld process.
Configuring systemd for MySQL
To add or change systemd options for MySQL, these methods are available:
Use a localized systemd configuration file.
Arrange for systemd to set environment variables for the MySQL server process.
Set the MYSQLD_OPTS systemd variable.
To use a localized systemd configuration file, create the /etc/systemd/system/mysqld.service.d directory if it does not exist. In that directory, create a file that contains a [Service] section listing the desired settings. For example:
The discussion here uses override.conf as the name of this file. Newer versions of systemd support the following command, which opens an editor and permits you to edit the file:
Whenever you create or change override.conf , reload the systemd configuration, then tell systemd to restart the MySQL service:
With systemd, the override.conf configuration method must be used for certain parameters, rather than settings in a [mysqld] , [mysqld_safe] , or [safe_mysqld] group in a MySQL option file:
For some parameters, override.conf must be used because systemd itself must know their values and it cannot read MySQL option files to get them.
Parameters that specify values otherwise settable only using options known to mysqld_safe must be specified using systemd because there is no corresponding mysqld parameter.
For additional information about using systemd rather than mysqld_safe , see Migrating from mysqld_safe to systemd.
You can set the following parameters in override.conf :
To set the number of file descriptors available to the MySQL server, use LimitNOFILE in override.conf rather than the open_files_limit system variable for mysqld or —open-files-limit option for mysqld_safe .
To set the maximum core file size, use LimitCore in override.conf rather than the —core-file-size option for mysqld_safe .
To set the scheduling priority for the MySQL server, use Nice in override.conf rather than the —nice option for mysqld_safe .
Some MySQL parameters are configured using environment variables:
LD_PRELOAD : Set this variable if the MySQL server should use a specific memory-allocation library.
NOTIFY_SOCKET : This environment variable specifies the socket that mysqld uses to communicate notification of startup completion and service status change with systemd. It is set by systemd when the mysqld service is started. The mysqld service reads the variable setting and writes to the defined location.
In MySQL 8.0, mysqld uses the Type=notify process startup type. ( Type=forking was used in MySQL 5.7.) With Type=notify , systemd automatically configures a socket file and exports the path to the NOTIFY_SOCKET environment variable.
TZ : Set this variable to specify the default time zone for the server.
There are multiple ways to specify environment variable values for use by the MySQL server process managed by systemd:
Use Environment lines in the override.conf file. For the syntax, see the example in the preceding discussion that describes how to use this file.
Specify the values in the /etc/sysconfig/mysql file (create the file if it does not exist). Assign values using the following syntax:
After modifying /etc/sysconfig/mysql , restart the server to make the changes effective:
To specify options for mysqld without modifying systemd configuration files directly, set or unset the MYSQLD_OPTS systemd variable. For example:
MYSQLD_OPTS can also be set in the /etc/sysconfig/mysql file.
After modifying the systemd environment, restart the server to make the changes effective:
For platforms that use systemd, the data directory is initialized if empty at server startup. This might be a problem if the data directory is a remote mount that has temporarily disappeared: The mount point would appear to be an empty data directory, which then would be initialized as a new data directory. To suppress this automatic initialization behavior, specify the following line in the /etc/sysconfig/mysql file (create the file if it does not exist):
Configuring Multiple MySQL Instances Using systemd
This section describes how to configure systemd for multiple instances of MySQL.
Because systemd has the capability of managing multiple MySQL instances on platforms for which systemd support is installed, mysqld_multi and mysqld_multi.server are unnecessary and are not installed.
To use multiple-instance capability, modify the my.cnf option file to include configuration of key options for each instance. These file locations are typical:
/etc/my.cnf or /etc/mysql/my.cnf (RPM platforms)
/etc/mysql/mysql.conf.d/mysqld.cnf (Debian platforms)
For example, to manage two instances named replica01 and replica02 , add something like this to the option file:
The replica names shown here use @ as the delimiter because that is the only delimiter supported by systemd.
Instances then are managed by normal systemd commands, such as:
To enable instances to run at boot time, do this:
Use of wildcards is also supported. For example, this command displays the status of all replica instances:
For management of multiple MySQL instances on the same machine, systemd automatically uses a different unit file:
mysqld@.service rather than mysqld.service (RPM platforms)
mysql@.service rather than mysql.service (Debian platforms)
In the unit file, %I and %i reference the parameter passed in after the @ marker and are used to manage the specific instance. For a command such as this:
systemd starts the server using a command such as this:
The result is that the [server] , [mysqld] , and [mysqld@replica01] option groups are read and used for that instance of the service.
On Debian platforms, AppArmor prevents the server from reading or writing /var/lib/mysql-replica* , or anything other than the default locations. To address this, you must customize or disable the profile in /etc/apparmor.d/usr.sbin.mysqld .
On Debian platforms, the packaging scripts for MySQL uninstallation cannot currently handle mysqld@ instances. Before removing or upgrading the package, you must stop any extra instances manually first.
Migrating from mysqld_safe to systemd
Because mysqld_safe is not installed on platforms that use systemd to manage MySQL, options previously specified for that program (for example, in an [mysqld_safe] or [safe_mysqld] option group) must be specified another way:
Some mysqld_safe options are also understood by mysqld and can be moved from the [mysqld_safe] or [safe_mysqld] option group to the [mysqld] group. This does not include —pid-file , —open-files-limit , or —nice . To specify those options, use the override.conf systemd file, described previously.
On systemd platforms, use of [mysqld_safe] and [safe_mysqld] option groups is not supported and may lead to unexpected behavior.
For some mysqld_safe options, there are alternative mysqld procedures. For example, the mysqld_safe option for enabling syslog logging is —syslog , which is deprecated. To write error log output to the system log, use the instructions at Section 5.4.2.8, “Error Logging to the System Log”.
Источник