Перейти к содержимому

Centos 7 где находится база mysql

  • автор:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 803a683fde3029c2 • Your IP: Click to reveal 178.175.133.149 • Performance & security by Cloudflare

Путь до базы MySQL / MariaDB

В статье пойдет речь о просмотре и смене пути расположения файлов баз данных MySQL. Приведенные примеры выполнены на CentOS 7 — также они будут работать на Ubuntu и многих других дистрибутивах Linux, FreeBSD и Windows.

Посмотреть текущий путь

Увидеть, где хранятся базы можно несколькими способами.

Способ 1. Командная строка Linux.

В командной строке вводим:

systemctl status mysql || systemctl status mariadb

* для Windows используем оснастку Службы. Для FreeBSD используем команду service mysql-server stop.

mariadb.service — MariaDB database server
Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
Active: active (running) since Ср 2018-07-11 15:38:16 MSK; 23h ago
Process: 1067 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
Process: 992 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
Main PID: 1066 (mysqld_safe)
CGroup: /system.slice/mariadb.service
??1066 /bin/sh /usr/bin/mysqld_safe —basedir=/usr
??1248 /usr/libexec/mysqld —basedir=/usr —datadir=/var/lib/mysql —plugin-dir=/usr/lib64/mysql/plugin —log-error=/var/log/mariadb/mariadb.log —pid-file=/var/run/mariadb/mariadb.pid —socket.

* в выделенном фрагменте /var/lib/mysql — путь до файлов базы данных.

Способ 2. Командная оболочка MySQL.

Данный способ является более универсальным — он подойдет для любого дистрибутива Linux, FreeBSD, Windows. Также, метод универсален с точки зрения метода установки MySQL — чистая установка или в составе готовой сборки (Open Server, Xampp, Denwer . ).

Как узнать путь до файлов базы данных MySQL/MariaDB в Linux и Windows

Файлы базы MySQL/MariaDB данных хранятся на жёстком диске. По умолчанию это папка data внутри директории исполнимых файлов MySQL (в Windows) или в директории /var/lib/mysql/ (Linux).

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

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

Далее будет показано, как в командной строке можно определить, где расположены файлы баз данных MySQL в Windows и в Linux.

Определение пути без подключения к серверу СУБД

В Windows

В ОС Windows для получения пути до базы данных введите команду:

Если вы получите сообщение, что команда mysqld не найдена, значит нужно указать путь до исполнимого файла mysqld или перейти в директорию с исполнимым файлом. Предположим, MySQL/MariaDB установлена в папке C:\Server\bin\mariadb, тогда переходим в поддиректорию bin, содержащую исполнимые файлы, и выполняем там указанную выше команду:

В Linux

В операционной системе Linux выполните следующую команду и она покажет вам путь до базы данных:

Переменная @@datadir;

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

И затем в консоли MySQL/MariaDB выполните:

Как видно на скриншоте, путь до файлов базы данных на сервере, где введена команда, c:\Server\data\DB\data\.

Ещё один вариант выполнения данной команды:

Как узнать настройки директорий в MySQL/MariaDB

Чтобы показать информацию о всех настройках директорий СУБД сервера, выполнит команду:

Пример вывода в Windows для MariaDB:

Чтобы вывести только datadir выполните команду:

Как узнать путь до базы данных MySQL/MariaDB в скрипте

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

Примечание: если в Linux у вас проблемы с последними командами, то инвертируйте (поменяйте местами) одинарные и двойные кавычки.

Также не забывайте менять пользователя root на имя вашего пользователя.

How to Change MySQL Data Directory to New Location on CentOS 7

Databases are constantly growing and it is likely to outgrow your / partition at some point, especially these days in the age of “the cloud” where you may be limited to a small / partition, but can pay to add bulk storage, or attach more disks. Alternatively, you may wish to move your database to a separate location because you want to configure some sort of snapshotting technique, such as with ZFS or LVM.

In this tutorial I will show you how you can change or move your data directory to new location on CentOS 7.

Step #1: Move MySQL Data Directory

Before moving MySQL’s data directory lets see the current location using mysql command line as shown below.

In the above output in can see the MySQL default data direcror /var/lib/mysql/. So we are going to move this directory. Once you’ve confirmed this, type exit and press “ENTER” to leave the monitor:

Before changing the data directory you will need to shut down MySQL service.

systemctl doesn’t display the outcome of all service management commands, so if you want to be sure you’ve succeeded, use the following command:

Now MySQL service is shut down lets start copy the existing data directory to new location with rsync command using with –a option to preserves the permissions and other directory properties while-v provides verbose output so you can follow the progress.

Once the rsync is complete, rename the current folder with a .bak extension and keep it until we’ve confirmed the move was successful. By re-naming it, we’ll avoid confusion that could arise from files in both the new and the old location.

Step #2: Pointing to the New Data Location

By default MySQL data directory set to /var/lib/mysql in the /etc/my.cnf file. Now edit this file to reflect the new data directory as shown below.

Save and close file.

After updating the existing lines, we’ll need to add configuration for the mysql client. Insert the following settings at the bottom of the file so it won’t split up directives in the [mysqld] block.

Save and close file.

Step #3: Restart MySQL Service

Now restart the MySQL service after updated its configuration to use the new location.

To make sure that the new data directory is indeed in use, start the MySQL monitor.

In the above output you can see the MySQL new data directory location is /mnt/data/mysql/.

If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com . To become an author at LookLinux Submit Article . Stay connected to Facebook .

You may also like

How to Install MySQL Server on CentOS / Redhat 6/7/8

How to Change MySQL User Password

How to Enable Slow Query Log in MySQL 5.6

How to Install MongoDB Server on Ubuntu and Debian Based System

How to Install MySQL 8.0 on CentOS, RHEL and Fedora Systems

How to Disable Strict SQL Mode in MySQL 5.7

Skip Duplicate Replication Error in MySQL

Alter Table Statement in MySQL : How to Add Column in Table

How to :- Alter Table or Add Multiple Columns in Table? – MySQL

Alter Table Statement in MySQL : How to Modify Column in Table

Alter Table Statement in MySQL : How to Modify Multiple Columns in Table

Alter Table Statement in MySQL : How to Drop Column in Table

Alter Table Statement in MySQL : How to Rename Column in Table

Alter Table Statement in MySQL : How to Rename Table

ERROR 1130 (HY000): Host ” is not allowed to connect to this MySQL server

How to Setup MySQL Master Slave Replication Using Rsync

How to Install and Configure phpMyAdmin on CentOS 7

How to Setup MySQL Master Slave Replication using Percona XtraBackup

Fix : Mysql Warning Using a Password on The Command Line Interface Can be Insecure

How To Install PostgreSQL 10 On CentOS/RHEL 7/6 and Fedora 26/25

Fix phpMyAdmin :- unblock with ‘mysqladmin flush-hosts’ / Error Host ” is blocked because of many connection

How To Install MySQL 8.0 On CentOS, RHEL and Fedora

Case study: Alternative Way To Recover MySQL Root Password

Installing Percona XtraBackup on RHEL and CentOS

Restore Mysqldump Backup Faster

How To Setup GTID Replication In MySQL 5.6

MySQL : Show How Many INSERT, UPDATE, DELETE In Binary Log File

How To Change MySQL Binary Log File Location To Another Directory

Restore MySQL Database From Dump File

MySQL Database Backup From The Command Line

MySQL Database Backup Automatic Script

Steps To Configure Master Slave MySQL Replication

How To Extract Tables From MySQL Dump File

How To Recover MySQL Root Password

How To Connect MySQL Server Without Password Prompt

Unable To Connect MySQL Database Server From PHP

Steps Before Shutting Down MySQL Server

How To Reinstall MySQL Server v5.x On Linux

Automated Installation and Configurations – Apache/Nginx, MySQL ,PHP or PHP-FPM on Linux/UNIX

How to Find Table & Database Size in MySQL

How To Install Only MySQL Client On CentOS/Redhat 6/7/8 or Ubuntu

Change MySQL default Data Directory to New Location in Linux

Check and Update max_connections value to fix MySQL Error: Too many connections

Why You Should Upgrade Your Open Source Database Software?

MySQL Basic Commands For Database Administrator

Adding Multiple MySQL Database Server In Single PhpMyAdmin Installation

Guide :- How to Install MySQL 5.6 Server on CentOS / Redhat 6/7/8

Types Of MySQL Backup

Types of Transaction in MySQL

How To Migrate MariaDB to MySQL?

How To Configure And Install PhpMyAdmin With Apache

About the author

mm

Santosh Prasad

Hi! I’m Santosh and I’m here to post some cool article for you. If you have any query and suggestion please comment in comment section.

2 Comments

Followed this blog for MySQL5.7 on CentOS 8 to move default /var/lib/mysql to my NFSv4.1 mount point /mnt/mysql57 but at the time of starting mysqld, i got the following error:

[root@mysql-test2 /]# systemctl start mysqld
Job for mysqld.service failed because the control process exited with error code.
See “systemctl status mysqld.service” and “journalctl -xe” for details.
[root@mysql-test2 /]# journalctl -xe
Jan 19 11:01:23 mysql-test2 setroubleshoot[44924]: SELinux is preventing /usr/sbin/mysqld from write access on the directory mysql.

***** Plugin catchall (100. confidence) suggests **************************

If you believe that mysqld should be allowed write access on the mysql directory by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# ausearch -c ‘mysqld’ –raw | audit2allow -M my-mysqld
# semodule -X 300 -i my-mysqld.pp

Jan 19 11:01:23 mysql-test2 setroubleshoot[44924]: AnalyzeThread.run(): Set alarm timeout to 10
Jan 19 11:01:23 mysql-test2 setroubleshoot[44924]: AnalyzeThread.run(): Cancel pending alarm
Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: SELinux is preventing /usr/sbin/mysqld from write access on the directory mysql. For complete SELinux mes>
Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: SELinux is preventing /usr/sbin/mysqld from write access on the directory mysql.

***** Plugin catchall (100. confidence) suggests **************************

If you believe that mysqld should be allowed write access on the mysql directory by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# ausearch -c ‘mysqld’ –raw | audit2allow -M my-mysqld
# semodule -X 300 -i my-mysqld.pp

Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: AnalyzeThread.run(): Set alarm timeout to 10
Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: AnalyzeThread.run(): Cancel pending alarm
Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: failed to retrieve rpm info for /mnt/mysql57/mysql/ibdata1
Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: SELinux is preventing /usr/sbin/mysqld from getattr access on the file /mnt/mysql57/mysql/ibdata1. For co>
Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: SELinux is preventing /usr/sbin/mysqld from getattr access on the file /mnt/mysql57/mysql/ibdata1.

***** Plugin catchall (100. confidence) suggests **************************

If you believe that mysqld should be allowed getattr access on the ibdata1 file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# ausearch -c ‘mysqld’ –raw | audit2allow -M my-mysqld
# semodule -X 300 -i my-mysqld.pp

Jan 19 11:01:24 mysql-test2 setroubleshoot[44924]: AnalyzeThread.run(): Set alarm timeout to 10
lines 2693-2736/2736 (END)

The content of my /etc/my.cnf is as shown below
[root@mysql-test2 /]# cat /etc/my.cnf
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
datadir=/mnt/mysql57/mysql
socket=/mnt/mysql57/mysql/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[client]
port=3306
socket=/mnt/mysql57/mysql/mysql.sock

[nutanix123@mysql-test2 mysql57]$ df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 7.7G 0 7.7G 0% /dev
tmpfs 7.8G 0 7.8G 0% /dev/shm
tmpfs 7.8G 9.5M 7.7G 1% /run
tmpfs 7.8G 0 7.8G 0% /sys/fs/cgroup
/dev/mapper/cl-root 70G 5.7G 65G 9% /
/dev/mapper/cl-home 122G 911M 121G 1% /home
/dev/sda1 1014M 239M 776M 24% /boot
tmpfs 1.6G 1.2M 1.6G 1% /run/user/42
tmpfs 1.6G 6.9M 1.6G 1% /run/user/1000
XXXXXXXXXXXXXXXXXX:/mysql-centos 2.0T 800M 2.0T 1% /mnt/mysql57
(Mount path IP is masked for security reasons)

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

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