search
HomeDatabaseMysql TutorialHow to change the MySQL data directory to another location on Ubuntu 16.04

如何在 Ubuntu 16.04 上将 MySQL 数据目录更改为另一个位置

In this article, we will learn how to change the MySQL data directory or relocate the MySQL database data to a new location. This situation may be used when the database grows very fast, or when something goes wrong. For some security reasons we want to move the data directory to a new location.

Prerequisites

  • An Ubuntu computer with Sudo privileges as a non-root user.
  • MySQL is installed and running.
  • The new volume or location we want to move the database data location to, the new location will be /mnt/data_vol/MySQL because data_vol is a new volume connected to the computer

Changing the MySQL data folder location

Before continuing, we first find the current location of the data directory

$ mysql –u root –p
Output:
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 472
Server version: 5.6.30-0ubuntu0.14.04.1 (Ubuntu)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>

When prompted for the MySQL root password, enter the password. Run the following command to know MySQL's current working data directory.

Mysql> select @@datadir;
Output:
+-----------------+
| @@datadir       |
+-----------------+
| /var/lib/mysql/ |
+-----------------+
1 row in set (0.00 sec)

As shown in the output, the MySQL database uses /var/lib/MySQL as the default folder for the data directory. Before we modify anything, we will check the integrity of the data, we will stop MySQL and check the status

$ sudo systemctl stop mysql

because systemctl will not show anything for the services command

$ sudo systemctl status mysql
Output:
mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Mon 2016-09-12 13:57:43 IST; 1s ago
   Process: 17669 ExecStartPost=/usr/share/mysql/mysql-systemd-start post (code=exited, status=0/SUCCESS)
   Process: 17668 ExecStart=/usr/sbin/mysqld (code=exited, status=0/SUCCESS)
   Process: 17664 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
   Main PID: 17668 (code=exited, status=0/SUCCESS)
Sep 12 13:55:14 ubuntu-16 systemd[1]: Starting MySQL Community Server...
Sep 12 13:55:15 ubuntu-16 systemd[1]: Started MySQL Community Server.
Sep 12 13:57:40 ubuntu-16 systemd[1]: Stopping MySQL Community Server...
Sep 12 13:57:43 ubuntu-16 systemd[1]: Stopped MySQL Community Server.

Once we confirm the MySQL is stopped, we will move the data to the new location. To move the data, we will use Rsync with the –a option, which preserves permissions on the data files, and –v which displays verbose output.

Below is the complete command to move the data to the new location –

$ rsync –av /var/lib/mysql /mnt/data_vol/
OutPut:
sending incremental file list
mysql/
mysql/auto.cnf
mysql/debian-5.7.flag
mysql/ib_buffer_pool
mysql/ib_logfile0
mysql/ib_logfile1
mysql/ibdata1
mysql/mysql/
mysql/mysql/columns_priv.MYD
mysql/mysql/columns_priv.MYI
mysql/mysql/columns_priv.frm
mysql/mysql/db.MYD
mysql/mysql/db.MYI
mysql/mysql/db.frm
mysql/mysql/db.opt
….
mysql/sys/x@0024user_summary.frmmysql/sys/x@0024user_summary_by_file_io.frm
mysql/sys/x@0024user_summary_by_file_io_type.frm
mysql/sys/x@0024user_summary_by_stages.frm
mysql/sys/x@0024user_summary_by_statement_latency.frm
mysql/sys/x@0024user_summary_by_statement_type.frm
mysql/sys/x@0024wait_classes_global_by_avg_latency.frm
mysql/sys/x@0024wait_classes_global_by_latency.frm
mysql/sys/x@0024waits_by_host_by_latency.frm
mysqlsys//x@0024waits_by_user_by_latency.frm
mysql/sys/x@0024waits_global_by_latency.frm
sent 199,384,083 bytes received 6,858 bytes 132,927,294.00 bytes/sec
total size is 199,307,568 speedup is 1.00

After rsync, the data folder was successfully moved to the new location. For security reasons, we will retain the data folder until we confirm that the data is in the new location, and we will rename the current data directory from /var/lib/mysql to /var/lib/mysql_backup . Below is the command to change the current data directory.

Below is the command to change the current data directory –

$ sudo mv /var/lib/mysql /var/lib/mysql_backup

Now, we will change the default data directory, there are many ways to change it, but we will edit the file located at /etc/mysql/mysql mysqld.cnf file in .conf.d/mysqld.cnf.

Edit mysqld.cnf, the command is as follows

$ sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
Output:
[mysqld_safe]
socket    = /var/run/mysqld/mysqld.sock
nice      = 0
[mysqld]
#
# * Basic Settings
#
user             = mysql
pid-file         = /var/run/mysqld/mysqld.pid
socket           = /var/run/mysqld/mysqld.sock
port             = 3306
basedir          = /usr
datadir          = /mnt/data_vol/mysql/
tmpdir           = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking

Change Apparmor alias settings

In addition, we need to edit /etc/apparmor.d/tunables/alias

At the bottom of the file we need to add the following lines in the alias rules.

$ sudo vi /etc/apparmor.d/tunables/alias
Output:
# ------------------------------------------------------------------
#
# Copyright (C) 2010 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# ------------------------------------------------------------------
# Alias rules can be used to rewrite paths and are done after variable
# resolution. For example, if '/usr' is on removable media:
# alias /usr/ -> /mnt/usr/,
#
# Or if mysql databases are stored in /home:
# alias /var/lib/mysql/ -> /home/mysql/,
alias /var/lib/mysql/ -> /mnt/data_vol/mysql

After editing the file, we need to restart apparmor.

The following is the command to restart apparmor.

Since we changed the default data directory, we need to run the following command, which will create a minimal directory folder structure to pass the scripting environment.

$ sudo mkdir /var/lib/mysql/mysql –p

Now we will restart the mysql service.

$ sudo systemctl start mysql

Now we will check the status of the MySQL service using the following command

$ sudo systemctl status mysql
Output:
mysql.service - MySQL Community Server
    Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
    Active: active (running) since Mon 2016-09-12 14:17:27 IST; 23s ago
   Process: 18481 ExecStartPost=/usr/share/mysql/mysql-systemd-start post (code=exited, status=0/SUCC
   Process: 18477 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCES
  Main PID: 18480 (mysqld)
     Tasks: 28 (limit: 512)
    Memory: 137.3M
   CPU: 329ms
CGroup: /system.slice/mysql.service
        └─18480 /usr/sbin/mysqld
Sep 12 14:17:26 ubuntu-16 systemd[1]: Starting MySQL Community Server...
Sep 12 14:17:27 ubuntu-16 systemd[1]: Started MySQL Community Server.

To ensure that the new data directory has been changed, we will run the following command

$ mysql -uroot -p
Output:
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.13-0ubuntu0.16.04.2 (Ubuntu)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select @@datadir
+----------------------+
| @@datadir            |
+----------------------+
| /mnt/data_vol/mysql/ |
+-----------------+
1 row in set (0.00 sec)
mysql>

Once we confirm the data Directory changes, we will delete the default data directory, which is located at /var/lib/mysql_backup, below is the command to delete the old database directory.

$ sudo rm –rf /var/lib/mysql_backup

In the above configuration and steps, we learned to relocate the MySQL data directory to a new location, which will help us protect or store more data to a different location.

The above is the detailed content of How to change the MySQL data directory to another location on Ubuntu 16.04. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft