The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →To move MariaDB’s data directory, stop the server, copy the complete existing directory with its ownership and security metadata intact, point the active configuration at the new path, update systemd and any AppArmor or SELinux policy, then start MariaDB and verify @@datadir. Keep the original directory untouched until reads, writes, logs and a rollback have all been tested.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
The procedure below applies to packaged Linux installations using systemd, including Ubuntu, Debian, RHEL and CentOS. Paths and policy controls differ by distribution, so verify the service unit and the configuration files your installation actually loads.
As an Amazon Associate I earn from qualifying purchases.
Free tools Windows power users keep installed
One-click scans. No signup required.
What changes when you move the datadir?
MariaDB’s datadir is the directory where the server stores databases, system tables, InnoDB and Aria files, logs that are configured inside the data tree, and other runtime data. The variable is documented by MariaDB as the “Directory where the data is stored.” See the MariaDB Server System Variables reference.
A successful move has four separate parts:
- The files must be copied completely while MariaDB is stopped.
- The service account must own the files and be able to traverse every parent directory.
- MariaDB must read the new path from the configuration used by its systemd unit.
- Linux access controls must permit the service to read and write the new location.
Changing only one of these usually produces a service that fails immediately, starts against the old directory, or starts without access to its system tables.
#1 Best Overall
Before you touch the existing directory
Confirm the service and effective path
Record the current state while MariaDB is still running. The packaged unit is commonly named mariadb.service, but check your host rather than assuming.
sudo systemctl status mariadb
sudo systemctl show mariadb -p User -p Group -p FragmentPath
sudo mariadb -NBe 'SELECT @@datadir;'
sudo my_print_defaults --mysqld
SELECT @@datadir; reports the path used by the running server. my_print_defaults --mysqld shows options assembled from the option files visible to that command. To inspect compiled defaults and recognized options, you can also run:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorssudo mariadbd --verbose --help 2>/dev/null | grep -E '(^|[[:space:]])datadir'
Do not treat a value printed by a utility as proof that the systemd service uses the same files. The unit may set a different option-file location, an environment variable, or an explicit --datadir. The authoritative checks are the unit definition, its drop-ins and the value returned by the running server.
Check capacity, mounts and recovery space
Make sure the destination filesystem has room for the whole source directory and for temporary growth during the copy. If the destination is a separate volume, ensure it is mounted before MariaDB starts after a reboot.
sudo du -sh /var/lib/mysql
sudo df -h /var/lib/mysql /srv
findmnt /var/lib/mysql
findmnt /srv
Keep enough free space to retain the original directory until validation is complete. Do not delete the source as part of the move command.
Plan a maintenance window
Stopping MariaDB makes the database unavailable. Schedule the outage, notify applications that connect to it, and pause jobs that might reconnect while the files are being copied. A hot copy of active InnoDB or Aria files is not a safe substitute for a clean stop in this procedure.
Step 1: Stop MariaDB and prove no process is using the files
Stop the exact unit you identified earlier, then verify that no mariadbd process remains.
sudo systemctl stop mariadb
sudo systemctl is-active mariadb
pgrep -a mariadbd || true
If a process remains, investigate it before copying. A manually started server, a second systemd unit, a container, or a monitoring script may still have the files open. On systems with lsof or fuser, check the old directory:
sudo lsof +D /var/lib/mysql
sudo fuser -vm /var/lib/mysql
Do not start a second MariaDB instance against the same InnoDB or Aria files. Concurrent access can produce lock errors and can damage data.
Step 2: Create and mount the destination
Use a dedicated directory
Choose a path on the intended filesystem, such as /srv/mariadb or /data/mariadb. Create it while MariaDB is stopped:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
sudo install -d -m 0750 /srv/mariadb
If the path is on a new block device, format and mount it according to your operating system’s storage procedure, then add a persistent /etc/fstab entry if appropriate. Test the mount before proceeding:
findmnt /srv
sudo touch /srv/mariadb/.mount-test
sudo rm /srv/mariadb/.mount-test
A separate volume can expand database capacity and isolate database failures from the root filesystem, but MariaDB will fail at boot if the volume is absent or mounted at a different path. Use a filesystem and mount options compatible with your workload and backup tools.
Rank #2
Ensure parent-directory traversal
The service account needs execute permission on every parent directory, not merely read and write permission on the final directory. For example, a directory mode of 0700 owned by root on /srv would block a mysql service account even if /srv/mariadb itself is correctly owned. Check each component with:
namei -l /srv/mariadb
Step 3: Copy the complete datadir with metadata
Copy the contents, including the mysql system schema. Missing that schema removes privilege tables and commonly causes startup or authentication failures.
Preferred method: archive-preserving rsync
With the old directory confirmed idle, copy its contents into the destination. The trailing slash on the source copies the contents rather than creating an extra nested directory.
sudo rsync -aHAX --numeric-ids /var/lib/mysql/ /srv/mariadb/
The archive options preserve ownership, modes, timestamps and symbolic links; -HAX preserves hard links, extended attributes and ACLs where the filesystem supports them; --numeric-ids avoids translating numeric owners between systems. If your rsync build or filesystem does not support ACLs or extended attributes, preserve the metadata your platform uses and record the limitation for your validation and backup plan.
Run a second rsync after the first copy to catch an interrupted transfer or a file changed by an administrative action:
sudo rsync -aHAX --numeric-ids --delete /var/lib/mysql/ /srv/mariadb/
Use --delete only after checking that source and destination paths are correct. It removes destination files that are not in the source.
Fallback: recursive archive copy
If rsync is unavailable, a local archive-preserving copy is preferable to a plain recursive copy:
sudo cp -a /var/lib/mysql/. /srv/mariadb/
Verify that the destination contains the same top-level databases and the mysql directory. A plain cp -r can lose ownership, modes, timestamps, links or extended attributes and should not be your default for a database directory.
Step 4: Set ownership and permissions
Find the account configured for the service rather than assuming its name. Packaged installations commonly use mysql or mariadb.
sudo systemctl show mariadb -p User -p Group
Set the destination tree to that account and group. Replace the example names if your unit reports different values:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →sudo chown -R mysql:mysql /srv/mariadb
sudo chmod 0750 /srv/mariadb
Do not make the directory world-writable. Preserve the more specific modes on files and subdirectories produced by the archive copy. Check representative entries:
sudo stat -c '%U:%G %a %n' /srv/mariadb /srv/mariadb/mysql
sudo namei -l /srv/mariadb
If the destination is mounted with restrictive options or is encrypted, confirm that the service account can create and remove a test file before changing MariaDB’s configuration. Remove the test file afterward.
Rank #3
Step 5: Change the configuration MariaDB actually reads
Edit the option file included by the running unit, or set the documented --datadir=path option in the unit’s startup configuration. Do not edit an unused file and assume the service will notice.
Distribution layouts vary. Debian- and Ubuntu-family installations often include files below /etc/mysql/; RHEL- and CentOS-family installations commonly use /etc/my.cnf and an included directory. Verify the include chain with the defaults tools and the unit definition before editing.
In the server section, set the new absolute path:
[mysqld]
datadir=/srv/mariadb
Use one active datadir setting. If another included file defines a later value, remove or update the duplicate so the effective configuration is unambiguous. Keep a dated backup of the file you edit.
Step 6: Adjust systemd hardening for the new path
MariaDB’s packaged systemd unit may deliberately restrict writable locations. The official MariaDB systemd documentation describes adding a writable-path override for nonstandard locations, including a datadir under /usr/local.
Use a drop-in rather than editing the vendor unit
Create a drop-in:
sudo systemctl edit mariadb
Add a [Service] section with the destination path:
[Service]
ReadWritePaths=/srv/mariadb
If the datadir is under /usr/local, use the real path, for example:
[Service]
ReadWritePaths=/usr/local/mysql/data
A drop-in survives package upgrades better than modifying the file under /lib/systemd/system or /usr/lib/systemd/system. If the unit already has a ReadWritePaths assignment, inspect the merged configuration and preserve any required existing entries.
Recommended Free Tools
Destinations below /home
systemd may enable ProtectHome, which hides or restricts /home, /root and /run/user from services. A datadir below /home can therefore fail even when Unix ownership is correct. In the drop-in, set:
[Service]
ProtectHome=false
ReadWritePaths=/home/your-user/mariadb
Using a system location such as /srv or a dedicated mount is usually simpler than weakening this protection. If you must use /home, document the security trade-off and restrict the directory permissions carefully.
Reload and inspect the merged unit
sudo systemctl daemon-reload
systemctl cat mariadb
systemctl show mariadb -p ReadWritePaths -p ProtectHome
These commands confirm that systemd has loaded the drop-in you intended. Do not restart until the configuration, ownership and policy changes are all in place.
Step 7: Update AppArmor when it is enabled
On distributions using AppArmor, the profile can continue to allow the old path while denying the new one. MariaDB’s startup troubleshooting guidance shows an alias in /etc/apparmor.d/tunables/alias:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutealias /var/lib/mysql/ -> /data/mariadb/,
Change both sides to your actual old and new directories, preserving the trailing slashes. The alias maps accesses expected by the profile to the new location; it does not replace Unix permissions.
After saving the alias, reload or restart AppArmor:
Rank #4
sudo systemctl restart apparmor
Check the AppArmor service and kernel or journal messages if MariaDB still reports permission denied:
sudo systemctl status apparmor
sudo journalctl -k -b | grep -i apparmor
The exact profile file and reload behavior can vary by distribution. Follow the profile name shown in the denial rather than creating a second, conflicting rule.
Step 8: Relabel the destination for SELinux
SELinux denies access when a file’s security type is not permitted for the service, even if owner and mode bits look correct. MariaDB’s SELinux guide documents labeling a custom datadir with the mysqld_db_t type.
For a destination such as /mariadb/data, run:
sudo semanage fcontext -a -t mysqld_db_t '/mariadb/data(/.*)?'
sudo restorecon -Rv /mariadb/data
ls -Zd /mariadb/data
ls -Z /mariadb/data
Substitute the real destination. If semanage is not installed, install the SELinux management tools supplied by your distribution, then repeat the command. Use ls --context or ls -Z to verify the resulting type. Do not disable SELinux to make the move work; correct the file-context rule and investigate any denial in the audit log.
Step 9: Start and validate the new location
Start MariaDB only after the copy, configuration, systemd and mandatory-access-control changes are complete:
sudo systemctl start mariadb
sudo systemctl status mariadb --no-pager
If startup fails, inspect the service journal and MariaDB error log before changing anything else:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorssudo journalctl -u mariadb -b --no-pager
sudo journalctl -xeu mariadb
Confirm the effective datadir
sudo mariadb -NBe 'SELECT @@datadir;'
The result must be the destination path, not the old directory. Also inspect open files or the process command line if the result is unexpected:
ps -ef | grep '[m]ariadbd'
sudo lsof -p "$(pidof mariadbd)" | head
Exercise reads and writes
Do not remove the original directory immediately. Connect with a normal application account and test representative operations:
- Read several existing tables from each important database.
- Insert and update a disposable test row, then roll it back or remove it.
- Create and drop a temporary table.
- Confirm that scheduled jobs, replication, monitoring and backups can connect.
- Review the MariaDB error log for permission, path, tablespace or lock warnings.
Check that new files appear under the destination and that their owners and security contexts remain correct. Reboot during a maintenance window if the move involves a new mount or a systemd protection change; then repeat the service and SQL checks to prove the configuration survives boot.
Rollback plan if MariaDB will not start
Keep the original directory unchanged until the new setup has passed validation. If startup fails:
- Stop MariaDB and confirm no
mariadbdprocess is running. - Read
journalctl -u mariadband the MariaDB error log. Classify the failure as path, ownership, systemd, AppArmor, SELinux, mount or lock related. - Temporarily restore the original
datadirvalue in the active option file or unit configuration. - Remove or comment the new drop-in only if it prevents access to the original path; otherwise retain it and add the original path to the appropriate writable rule.
- Reload systemd, restart the relevant AppArmor profile if changed, and restore the original SELinux context rules if you altered them.
- Start MariaDB and verify
SELECT @@datadir;points to the original location.
Do not synchronize the destination back over the source unless you understand which files changed and have a backup. If the destination contains newer writes, blindly copying it over the source can destroy the last known-good state.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Direct move, bind mount or symlink?
There are three common ways to make MariaDB use another physical location. A direct configuration change is generally the clearest because the server and backup tools see the real path.
| Approach | Operational behavior | Advantages | Risks and policy work |
|---|---|---|---|
Change datadir to the new directory |
MariaDB opens files at the destination path. | Clear configuration, straightforward backups and monitoring, no indirection. | Requires updates to systemd, AppArmor or SELinux when the path changes. |
| Bind mount the new filesystem at the old path | The operating system presents the new volume at the existing datadir path. | Applications and policies that already reference the old path may need fewer changes. | The mount must exist before MariaDB starts; backups and troubleshooting can hide the real volume unless documented. |
| Symlink the old directory to the new one | The old path resolves through a filesystem link. | Quick to create and easy to reverse during a short maintenance window. | systemd sandboxing, AppArmor path rules and SELinux labeling may treat the resolved path differently; some backup tools do not follow links as expected. |
If you choose a bind mount, put the mount in /etc/fstab and make the service depend on it or otherwise ensure ordering. A symlink does not remove the need for correct ownership, labels or writable-path rules, so it is rarely the best long-term design.
Same filesystem versus a separate volume
| Choice | Best fit | Important checks |
|---|---|---|
| Another directory on the same filesystem | Reorganizing paths without changing storage capacity or failure boundaries. | Available free space, identical filesystem behavior and enough room to retain the source during validation. |
| Dedicated filesystem or block volume | Capacity expansion, independent backup snapshots, or keeping database growth away from the root filesystem. | Persistent mount configuration, boot ordering, filesystem permissions, monitoring and recovery when the volume is unavailable. |
A new volume does not itself improve durability. Continue to use tested backups and document how to mount the volume on a replacement host.
Common errors and precise fixes
“Can’t create test file” or read-only filesystem
First verify that the destination is mounted read-write with findmnt. Then inspect the merged systemd unit for ReadWritePaths and other sandboxing settings. A path under a protected location can appear writable to root while remaining read-only to the service. Correct the drop-in, reload systemd and retry.
Permission denied
Check all four layers: destination ownership, execute permission on every parent directory, AppArmor profile or alias, and SELinux context. The MariaDB startup troubleshooting documentation covers this class of failure at What to do if MariaDB doesn’t start. Look for a denial timestamped at the failed start rather than changing permissions broadly.
Aria or InnoDB lock errors
Stop every MariaDB process that might reference either directory. A second server, a forgotten manual start, or an attempted restart during copying can hold locks. Verify with pgrep, lsof or fuser, then start one instance only.
Missing privilege tables or authentication failures
Confirm that the copy included the complete mysql system schema and that the active datadir points to the destination. Do not initialize a new empty datadir over the copied files; initialization creates a different system database and does not repair an incorrect path.
Recommended Free Tools
Destination below /home is rejected
Inspect ProtectHome in the systemd unit and its drop-ins. Set ProtectHome=false only in a deliberate drop-in, add the exact writable path, reload systemd and test again. Moving the datadir to a dedicated system location can avoid weakening this protection.
MariaDB starts but still uses the old directory
Query SELECT @@datadir;, inspect systemctl cat mariadb, and review the option-file include order. You likely edited a file that the service does not read or left a later datadir assignment overriding it.
Distribution and installation differences
Ubuntu and Debian packages
These systems commonly provide a mariadb.service unit and a split configuration under /etc/mysql. Confirm the actual include files with my_print_defaults --mysqld and systemctl cat mariadb. AppArmor is frequently enabled, so inspect its status before the first restart.
RHEL and CentOS packages
These systems commonly rely on /etc/my.cnf and included my.cnf.d files. SELinux is commonly enforcing, making the mysqld_db_t file context and restorecon step essential for a custom path.
Tarball or custom installations
A tarball installation may use a custom unit, a different service account, or a manually supplied --defaults-file. The same data-copy and validation principles apply, but the unit’s User, Group, option-file path and sandbox rules are authoritative. Do not copy assumptions from a package-managed layout.
Final removal checklist
Only after a successful restart and representative workload test should you retire the old directory.
SELECT @@datadir;returns the intended destination.- The service starts cleanly after a reboot or mount remount test.
- Applications, scheduled jobs, replication and backups work.
- The destination has the expected ownership, modes, AppArmor rules and SELinux contexts.
- You have a tested rollback and a current backup.
- You have preserved any required mount entry and documented the new path for operators.
Rename the original directory to a clearly marked quarantine name rather than deleting it immediately, for example /var/lib/mysql-old, and keep it until your retention policy and backup verification permit removal. Once it is removed, securely reclaim the space using your organization’s storage procedures.
Quick Recap
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.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →




