Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Move a MySQL Data Directory to a New Location Without Losing Databases

Move a MySQL data directory without losing databases. This guide covers clean shutdowns, mounted destinations, metadata-preserving copies, configuration paths, Linux security policies, Windows services, verification, failure recovery, and rollback.
Length12 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Move a MySQL data directory by taking a tested backup, stopping the server cleanly, copying the complete directory to a mounted destination, changing the active option file, updating AppArmor or SELinux policy when required, and verifying the instance before removing the original. The --datadir option changes where MySQL stores its data, but a working move also has to account for binary logs, relay logs, sockets, PID files, InnoDB files, certificates, and other paths that may be configured separately.

Do not start MySQL against an empty or unmounted destination. A package managed by systemd can treat an empty mount point as a new data directory and initialize a fresh server, making the original databases appear to have disappeared. Keep the old directory untouched until administrative checks and an application smoke test succeed.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What a MySQL data-directory move actually changes

MySQL’s data directory is more than a collection of schema folders. It normally contains database directories, InnoDB tablespace and redo-log files, server metadata, certificates and keys, the PID file, and mysqld-auto.cnf. Some installations place error logs, general or slow query logs, binary logs, relay logs, sockets, and temporary files elsewhere. Changing only one directory setting can therefore leave the running instance looking for files in the old location.

The Oracle MySQL Reference Manual states that the --datadir option changes the location of the data directory. The move is safe when the existing instance is shut down cleanly, the complete directory is copied with its metadata intact, every relevant pathname is reviewed, and the operating system’s access-control policy allows mysqld to use the new location.

Plan the move before stopping MySQL

Identify the instance, service, and effective configuration

First establish which server you are moving. A host can have more than one MySQL installation or service, and editing an unused my.cnf or my.ini has no effect. On Linux, packaged services are commonly named mysql on Debian-family distributions and mysqld on RPM-family distributions.

sudo systemctl status mysql
sudo systemctl status mysqld
ps -ef | grep '[m]ysqld'

Use the service that actually owns the running process. Inspect the service definition and the process command line for option-file arguments, then inspect the option-file order used by that installation. The effective setting, rather than a value in a commented or lower-priority file, is the one that must change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Before shutdown, record the current values for:

  • datadir
  • error, general, slow-query, and audit log locations
  • binary-log and relay-log base names and directories
  • socket and PID-file locations
  • InnoDB data, temporary, and redo-log paths
  • TLS certificate and key paths
  • the service name and the account under which mysqld runs

On a running server, an administrative client can show many of these variables. Also inspect the configuration files and the service’s command line, because a path can be supplied by an option file or by the service unit rather than by the server’s SQL variables.

Choose a destination that is already mounted

Create the destination on the filesystem intended to hold the database. For example, use a directory such as /srv/mysql-data on Linux or D:MySQLdata on Windows. Confirm the filesystem is mounted before stopping the old instance and again immediately before starting the new one.

findmnt /srv/mysql-data
mountpoint /srv/mysql-data
df -h /srv/mysql-data

If the mount is absent, stop. Do not create a new directory there and continue. A systemd-managed package may see the empty directory and initialize it. The MySQL manual documents a NO_INIT=true safeguard for package setups where automatic initialization must be suppressed; apply the mechanism appropriate to your distribution.

Take a recovery copy

Have a tested backup or storage snapshot before changing anything. A filesystem copy made after a clean shutdown is the basis of the direct-move procedure, but it is not a substitute for a backup whose restoration you have verified. If the destination is a storage snapshot, confirm that its consistency and rollback behavior meet your recovery requirements.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Direct filesystem move on Linux

1. Stop the correct service cleanly

The official copy procedure requires a clean shutdown so pending changes are flushed to disk. Stop the service identified during planning:

sudo systemctl stop mysql
# or, on many RPM-family installations:
sudo systemctl stop mysqld

Confirm that the process is gone before copying. A stop command that returns successfully does not prove that every server process has exited.

systemctl is-active mysql
systemctl is-active mysqld
pgrep -a mysqld

If a process remains, investigate the service status and error log rather than copying a live directory. Copying while writes are in progress can produce InnoDB or log-file errors and leaves no clean point from which to recover.

2. Verify the destination mount and capacity

Check that the expected filesystem is mounted at the exact path configured for the move, that it has enough free space, and that its mount options support normal database operation. Check the parent directories as well: the MySQL account needs traversal permission on every parent.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
findmnt /srv/mysql-data
df -h /srv/mysql-data
du -sh /var/lib/mysql

Do not proceed when findmnt shows the wrong device or no mount. Correct the mount first, then repeat the check.

3. Copy the complete data directory

Copy the old directory only after the clean shutdown. Preserve ownership, permissions, symbolic links, timestamps, hard links where used, and extended attributes required by the platform. A typical Linux copy using GNU tools is:

sudo rsync -aHAX --numeric-ids /var/lib/mysql/ /srv/mysql-data/

The trailing slash means the contents of the old directory are copied into the destination. If rsync is unavailable, an archive-preserving copy such as cp -a /var/lib/mysql/. /srv/mysql-data/ can preserve the ordinary Unix metadata, but verify extended attributes and security labels separately.

Do not copy only the individual schema directories. The top-level InnoDB files, server metadata, certificates, keys, and automatically generated configuration may be required for the instance to start or for encrypted data to remain usable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Set ownership and inspect permissions

On Unix, the files must be owned by the account used by mysqld, commonly mysql. Apply ownership to the destination after the copy if the source and destination filesystems mapped numeric IDs differently:

sudo chown -R mysql:mysql /srv/mysql-data
sudo find /srv/mysql-data -maxdepth 1 -printf '%M %u:%g %pn'

Use the actual service account if your installation uses a different name. Avoid broadening permissions as a shortcut. The account needs read and write access to database files and execute permission on each directory in the path; other users should not gain access to database contents merely because the directory moved.

5. Change the active option file

Edit the option file actually read by the service, commonly /etc/mysql/my.cnf, an included file under /etc/mysql/mysql.conf.d/, or an RPM-family configuration under /etc/my.cnf. Under the [mysqld] section, set the new directory:

[mysqld]
datadir=/srv/mysql-data

Search every included configuration file and the service unit for pathnames that still point to /var/lib/mysql. Review log, socket, PID, binary-log, relay-log, and InnoDB-specific settings. If those files were copied into the new directory, update their pathnames accordingly; if they deliberately remain elsewhere, verify that the server account can still access them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not assume that changing datadir relocates files configured by independent options. The manual specifically requires pathnames to be changed when an existing directory is copied to a new location.

6. Update Debian AppArmor policy

On Debian platforms, AppArmor can prevent MySQL from reading or writing outside the locations allowed by its profile. The default profile commonly protects the standard directory and can reject a custom location even when Unix ownership is correct.

Review /etc/apparmor.d/usr.sbin.mysqld and add rules granting the profile access to the new directory and its contents. Include the directory itself and the files below it, with permissions appropriate for database reads, writes, locking, and creation. Reload or restart AppArmor after editing, then check the kernel or AppArmor logs for denials. Do not disable the profile globally to solve a single path problem.

7. Apply SELinux labels on enforcing systems

SELinux evaluates labels as well as Unix permissions. MySQL’s default data-directory type is mysqld_db_t. A custom location should receive a persistent file-context rule and then be relabeled:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo semanage fcontext -a -t mysqld_db_t '/srv/mysql-data(/.*)?'
sudo restorecon -Rv /srv/mysql-data
ls -Zd /srv/mysql-data
ls -Z /srv/mysql-data | head

If semanage is not installed, install the distribution package that provides it or use the system’s documented SELinux administration method. Check the running process label with:

ps -eZ | grep mysqld

When startup fails on an enforcing host, inspect SELinux audit records for denials. Do not replace a missing label with permissive mode as a permanent fix.

8. Reload systemd only when its configuration changed

If you edited a service unit, drop-in, mount dependency, or environment file, reload the manager:

sudo systemctl daemon-reload

A change confined to an option file normally does not require daemon-reload, but restarting the MySQL service is still required. Ensure the destination mount is available before the service starts; an explicit mount dependency is preferable for machines where the database filesystem is remote or assembled during boot.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

9. Start and verify the moved instance

sudo systemctl start mysql
# or:
sudo systemctl start mysqld
sudo systemctl status mysql
sudo journalctl -u mysql -b --no-pager

Use the equivalent unit name for your system. Read the MySQL error log, not just the service summary. Then connect with an administrative client and verify the effective location from the server itself:

mysql -uroot -p -e "SELECT @@datadir;"

The result must show the intended directory. Check representative schemas and tables, confirm that expected users can connect, and run an application-level smoke test that exercises reads and writes. Confirm that new error logs and binary logs are being created at their intended locations. Keep the original directory unchanged until these checks pass.

Moving the data directory on Windows

On Windows, set datadir in the option file used by the MySQL service. A typical [mysqld] section is:

[mysqld]
basedir=C:Program FilesMySQLMySQL Server 8.0
datadir=D:MySQLdata

The basedir value must match the installation, while datadir points to the destination volume. Use the option file associated with the service rather than an unrelated copy in another installation directory.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Stop the MySQL Windows service from Services or with the service-control command appropriate to its registered name.
  2. Confirm that the server process has exited.
  3. Create D:MySQLdata on the intended volume and verify that the volume is present.
  4. Copy the entire existing data directory, including hidden files and subdirectories. Preserve the ACLs needed by the Windows account running the service.
  5. Copy or update the option file, then change every related pathname for logs, sockets or named pipes, PID files, binary logs, relay logs, and InnoDB files.
  6. Grant the service account read, write, modify, and directory-traversal rights required by the installation, without granting unnecessary access to other users.
  7. Start the service and inspect the MySQL error log and Windows service status.
  8. Connect to the server, confirm @@datadir, inspect representative schemas, and perform an application smoke test.

The official Windows procedure describes copying an existing data directory, copying the option file, changing pathnames, and starting the new instance with that option file. Do not delete the old directory until the new service has been verified.

Audit every path that may still reference the old directory

A successful server start does not prove that all features use the new location. Some paths are used only when a particular log, replication role, backup operation, or encryption feature is enabled. Search configuration includes and service arguments for the old directory string, then inspect these categories:

  • Binary and relay logs: replication can fail later if a log base name or relay-log location still points to an unavailable directory.
  • InnoDB files: separately configured data files, temporary tablespaces, undo tablespaces, and redo logs must be present where the configuration expects them.
  • Socket and PID files: local clients or service-management scripts may continue looking in the old directory.
  • Error and query logs: verify both the directory permissions and log rotation configuration.
  • TLS and encryption material: certificates, keys, and keyring files may not be below datadir; preserve their paths and access rights.
  • Server metadata: retain files such as mysqld-auto.cnf when they belong to the instance being moved.

If you intentionally move any of these components separately, document the final layout and test the relevant feature rather than assuming the basic connection test covers it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Diagnose common failures

“Permission denied” or an immediate startup failure

Check ownership of the data directory and every parent directory. Then check mandatory-access-control policy: AppArmor denials are common on Debian when the new path is outside the profile, while SELinux can deny access when the destination lacks the mysqld_db_t context. Review the error log and operating-system audit records before changing permissions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

MySQL starts with no databases

Stop it immediately. This usually means the service started against an empty directory, often because the intended filesystem was not mounted or the edited option file was not the one the service reads. Verify the mount, the effective option-file order, the process command line, and @@datadir. Restore the original configuration or copy before starting again. Do not create databases in the empty location while diagnosing the problem.

InnoDB or log-file errors after the move

Confirm that the copy followed a clean shutdown and included all top-level InnoDB and server files. Check for pathnames that still reference the old directory and verify that logs or tablespaces configured outside datadir were not omitted. If the destination copy is incomplete, stop the server and recopy from the retained original rather than deleting individual files.

The wrong instance starts

Multiple installations can have different service names and option-file search orders. Compare the service unit, process command line, installation base directory, and reported @@datadir. Edit the configuration belonging to the service you actually start, and avoid running an unregistered binary manually while the packaged service is still present.

Rollback procedure

If verification fails, rollback is safer than improvising repairs on the new copy:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Stop the MySQL service and confirm that no mysqld process remains.
  2. Restore the original datadir setting and any related log, socket, PID, or InnoDB pathnames.
  3. Restore the original AppArmor rules or SELinux file contexts if they were changed only for the attempted destination.
  4. Confirm the original directory and its filesystem mount are intact.
  5. Start the service against the retained original copy.
  6. Read the error log, identify the failed condition, and correct it before attempting another move.

Never use the old and new directories concurrently for the same server. The old copy is a rollback asset, not a second live data directory.

Direct copy, logical migration, or a storage snapshot?

A clean, same-instance directory copy is usually the most direct way to relocate storage because it preserves the server’s files, users, tablespaces, and metadata together. Its requirements are a clean shutdown, compatible filesystem access, and careful preservation of ownership, permissions, links, timestamps, and security labels.

A logical dump and restore is a different migration procedure. It can be useful when changing versions, platforms, or storage layouts, but it requires rebuilding the server and separately transferring users, grants, routines, events, and other metadata. Do not treat it as an in-place datadir move.

A storage-level snapshot can shorten the copy window when the storage platform provides a consistent snapshot mechanism. It still needs a consistency guarantee suitable for MySQL, a tested restore path, and correct security labels and mount dependencies at the destination. The snapshot method does not remove the need to audit configuration paths.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose based on the required downtime, consistency guarantee, storage-engine coverage, rollback speed, cross-version portability, and whether the method preserves users, tablespaces, logs, and server metadata. The official MySQL copy procedure specifically addresses copying an existing directory after a clean shutdown; other methods require their own operational runbook.

Non-negotiable safety boundaries

Never run two MySQL servers against one data directory. The MySQL manual warns that sharing a directory can cause interference and is unsuitable for most storage engines. A network filesystem such as NFS introduces additional performance and file-locking risks and should not be used as a shortcut for a local datadir relocation.

The move is complete only when the intended service starts from the intended mounted filesystem, reports the expected @@datadir, can read and write representative data, and passes the application’s smoke test. Retain the original directory and your tested backup until those checks are complete and you have a deliberate retention or deletion decision.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.