Sign In
Sign In

MySQL Database Migration

MySQL Database Migration
Hostman Team
Technical writer
MySQL
12.12.2023
Reading time: 14 min

The need for database migration may arise in several situations, such as:

  • changing your working platform or provider, 

  • modernizing and restoring IT infrastructure, 

  • introducing new developments into the existing system,

  • combining several different programs (in case of a merger of companies, branches, etc.). 

In this article, we will consider all the options for hosted MySQL database migration, how the process is carried out, and how to prepare for migrating the data.

General terms

  • Data is a format for storing information electronically (files, catalogs) on local and cloud media.

  • Information system is a program for storing, processing and retrieving data. 

  • Database, DB is a data set belonging to a particular enterprise, department or project. This includes information entered by users, tables, and other objects. The database also stores reports, multimedia, text files, service reminders, etc.

  • Database Management System (DBMS) is a software product created specifically for editing and managing databases. Examples of DBMS are MySQL, PostgreSQL, and others.

  • Database Schema is a database structure in the language supported by a particular DBMS. It includes both typical objects, such as tables and relations within them, as well as views, indexes, and other user information.

  • Table is a structured way of displaying values stored in a database. It includes columns and rows that have a specific purpose.

  • Data migration. The term has a dual purpose. 1. A mass transfer from a source to a receiving database. Once completed, the original system is usually discontinued as a working system. 2. A database conversion with a change in the database, either upgrade or downgrade (db_upgrade or db_downgrade).

  • Source system (historical system) is the database from which business and service information is to be copied.

  • Receiver system is the database to which the information will be transferred during the migration process.

  • Source data is the information obtained from the historical system, for example, in an Excel file (XLS).

  • Data transformation is converting the source structure into the format of the receiving database following its typical information storage template.

  • Data for loading is the information prepared for loading into the target database.

  • Data templates for loading describe the information storage structure in which the information is to be loaded into the receiver system.

  • Database version is the current or previous state of the database structure with a certain number, linked to a specific program release.

Reasons for database migration

The IT technologies are constantly improving. At least once every couple of years, new products radically different from the previous ones enter the market. The latter partly complicates maintenance, increases the cost of IT maintenance, and introduces certain limitations, which leads to the need for modernization with database migration. Developers additionally "incentivize" this approach by phasing out support for old products.

Here is a brief list of when migration is necessary:

  1. Launching a new site.

  2. Increasing the security of the IT infrastructure.

  3. Reducing the cost of the information system maintenance.

  4. Introducing fundamentally new technologies.

Types of data migration

The choice of MySQL database migration option depends on your current business objectives. Examples:

  1. Information migration. Data stored in the source database is converted to a different one supported by the destination database. This includes digitizing paper documents to digitize archives, applying encryption algorithms.

  2. Introduction of new programs. Transition to new releases of programs with preservation of previous settings, to fundamentally new programs with transfer from the old software.

  3. Database migration. Moving a database while maintaining consistency. For example, when moving local IT infrastructure to cloud environment, when import substitution according to the current regulations.

  4. Release migration. Updating the database structure to the current version so that it corresponds to both the program and the tools of third-party services. The procedure is performed in reverse order, with the release number decreasing.

Regardless of the migration type, the procedure is performed manually or automatically. The choice is up to the user, but partly it depends on objective factors. For example, if the product is no longer supported, automation is practically unrealistic or will be expensive. It is easier to manually find the necessary numbers, unload them from the old database, and load them into the new one.

-

Typical processes in database migration

Let's consider two options in more detail: database migration to a new software and versioned migration, when the application is regularly adjusted, often without stopping its work.

What you will need when migrating the entire database

The process is divided into two stages: preparation and migration itself, which also involves working in several steps.

Organizational part

  1. Determine the strategy. It is important to choose in advance the technology by which the migration of the MySQL database will take place. The stage includes determining the rules for opening access to employees related to the procedure. Each participant must understand what is required of them. It is also desirable to add testing to the strategy, after the migration is completed, in order to identify errors and correct them before they begin to create problems.

  2. Assemble a working group. It includes specialists familiar with the operation of the "old" system (historical) and the new program. It is better to assign monitoring to individual employees. The latter is mandatory even if the migration procedure is fully automated.

  3. Make a plan. It includes the amount of information to be transferred, the date of its transfer, testing, and the final implementation of the new software. This does not exclude the possibility of adjusting the plan based on the migration results, emerging errors, appearance of other inputs.

  4. List the data to be migrated. What do you want to copy? Classifiers, balances, turnovers, transactional and reference information.

  5. Discuss methods and criteria for quality control. It is important to check the integrity and correctness of the migrated data, the absence of unreasonable duplicates, the presence of full consistency, links provided by the structure of the base-receiver.

  6. Determine the method of database rollback. In case of serious errors, you may have to temporarily return to the old database to avoid downtime. Discuss the return mechanism in advance.

Technological part

  1. Prepare data loading templates, file loader. They include a description of fields to be loaded, rules for loading a table based on the structure of the receiver database. They also specify how to transform data if transformation is required.

  2. Identify data sources. At this stage, determine what information will be migrated, where, in what databases, and in what format it is located. The list of sources should be thought through carefully to avoid losing important information.

  3. Unload the source data. The speed of unloading depends on the amount of information, sometimes on its type, on whether conversion is required, whether reading errors occur, leading to repetitive reading. In practice, it is common to do test uploads of a small part of the database for preliminary evaluation.

  4. Data comparison. This stage is mandatory, its results guarantee the identity of the information in the source database and the upload file. It will take time approximately equal to the third step. Depending on the tasks, normalize table fields, remove duplicates, etc. at the same time.

  5. Prepare transformation rules. It includes writing scripts that automatically, according to pre-created templates, transform the structure into a given format.

  6. Load data into the receiver base. This step includes a series of test and final migrations or "main" migration at once, if the user is sure of the quality. For example, when the procedure is performed for the second or more times with the same tools.

  7. Verify data. In the last step, check the source database and the destination base to exclude inconsistency, correct probable defects, reduce the database size, and exclude duplicates.

Data version migration

Database version migration is used when developing software or new releases of existing programs to avoid desynchronization if different programmers create separate modules. It's also used when creating a new release in several stages, with periodic rollback to previous versions. The main idea of versioned migration is to set a rule: any SQL query is executed only once, because some changes often depend on others.

During migration, "atypical" errors occur. For example, we may assume that null rows can be deleted, but they are sometimes a part of the mandatory database structure. That is why it is better to provide the rule of storing "null" string fields right away:

  1. Regardless of the current value, set the field type to Nullable.

  2. Replace all empty strings of the processed database with NULL.

  3. Adjust the code so that the program reacts to reading NULL without errors.

Remember that when updating only an application without a database, an error of inserting a NULL value into the Not Nullable field will appear sooner or later. 

In practice, several methods of version migration are used - incremental, idempotent changes, likening the database structure to the source code, etc. There are tools for migration: Migrator.NET, ECM7.Migrator, Active Record Migrations and a dozen more. Regardless of the choice, the following principles are adhered to everywhere:

  1. It is important that any version of the database is upgradable to any of the existing ones.

  2. The same applies to the set of SQL queries, due to which the migration takes place.

  3. It is recommended to be able to create a database from scratch with up-to-date data at any time.

  4. It is desirable to minimize manual editing of files when merging branches.

  5. Rollback to one of the previous releases is as easy as an upgrade.

Preparing a database migration plan

Migration is carried out according to a clear plan so that the process is organized and uninterrupted. Lack of planning often leads to unforeseen downtime, serious errors in business processes, and sometimes even loss of critical data. It looks like an unfinished program with regular "glitches" and failures. Therefore, a plan is mandatory.

Conduct an audit in advance and determine the current quality, format, and privacy policy. The plan also includes monitoring of probable changes that migration sometimes leads to. This approach allows you to identify potential problems, adjust the work based on real inputs.

The planning also includes the assignment of responsible employees - for the transfer, for the individual steps of the process. It is desirable to separate the team of specialists from the operations team and at the same time maintain interaction for feedback and new inputs. 

Database migration example

Before starting the migration, make sure that the receiver system supports the version of the database to be migrated. You should also provide access to the source and target objects in advance. Information from the official guide "SQL Server to MySQL Migration Assistant" will help in the process.

Preparing for migration

If current conditions allow for a smooth migration, assess the database and related objects for readiness for migration. This procedure is possible by using the SSMA tool. The sequence of actions is as follows:

  1.     Open the SSMA software for MySQL.

  2.     Select the "Create Project" menu item in the "File" section.

  3.     Enter its name, where it will be located, specify the target object.

  4.     Set the "Transfer" parameter to SQL Server.

  5.     Use the "Connect to MySQL" window to connect to the MySQL server.

  6.     Select the database to be migrated.

  7.     Right-click on the "MySQL Metadata Explorer".

  8.     Select the "Create Report" tab (upper right corner).

This will generate a report containing statistics of conversions, errors or warnings that occur. The system will save this file in the SSMAProjects folder located in the current user's system directory. When viewed in Excel, the user will see the list of MySQL objects and actions to be converted during migration.

Now, we need to match the "default" data types and adjust them based on the requirements of the statement of work. The procedure looks like this:

  1.     Select "Project Parameters" from the Tools menu item.

  2.     Go to the "Type Matching" tab.

  3.     Perform the mapping by selecting the table in the MySQL Metadata Explorer.

Now, let's move on to the conversion of database objects. They should be taken from MySQL, "converted" into an analog for SQL Server, and loaded into SSMA metadata for MySQL. After that, you can view the contents through the "SQL Server Metadata Explorer". The SSMA product displays error messages (Output field), from which it is easy to judge whether a database conversion is required for the migration to be successful. If the procedure is required, follow the steps:

  1.     Open Connect to SQL Server.

  2.     Enter the credentials to connect to it.

  3.     Specify the target or new database.

  4.     Click "Connect."

  5.     In the "MySQL Metadata Explorer" area, use the right mouse button to select "Convert Schema".

  6.     When finished, compare the resulting data with the original data to make sure there are no problems.

If corrections are required, save the project offline with the "File>Save Project" command.

Migration

If there are no errors, proceed directly to migration. In practice, two options are used: client-side and server-side. In the first case, select "Client-side data migration subsystem" in the Project Options dialog box. In the second case, "Server-side data migration subsystem". If the target database is SQL Express Edition, only the first migration method is available.

If the server is involved, you will need to install the SSMA extension package for MySQL on the SQL Server instance and start the SQL Server agent service on it. Data migration is performed using a sequence of actions:

  1. Publish the schema. Right-click on "SQL Server Metadata Explorer". There select "Synchronize with database". Result - the MySQL database will be published inside the SQL Server instance.

  2. Reconcile the source and target project. In the same place as "Synchronize...", select "Transfer data". Check the boxes next to all items to migrate all tables.

  3. Examine the report on the migrated information. Connect to the SQL Server instance using SQL Server Management Studio utility and check how the database migration went.

That's it, the information migration procedure is complete.

Migration using console commands

The procedure includes two stages - creating a database dump and its deployment to the cloud platform where we plan to host the system. Make sure that the local machine and the remote host support the MySQL version being used. Migration between different database releases is not guaranteed.

Creating SQL dump

Let's perform the task using the mysqldump utility:

mysqldump --user=<user_name> \
   --password=<password> \
   --host=<host> \
   --port=<port> \
   --set-gtid-purged=off \
   --no-tablespaces \
<database_name> > dump.sql

Here, --set-gtid-purget=off means that replication does not use global GTIDs, and --notablespaces means that the dump of service information will be excluded, as it is not really needed.

Restoring the database from the dump

The mysql utility will help you to restore a SQL dump:

mysql --user=<user_name> \
   --password=<password> \
   --host=<host> \
 --port=6033 <database_name> < dump.sql

When using SSL, the list of commands will look like this:

mysql --user=<user_name> \
   --password=<password> \
   --host=<host> \
   --port=6033 \
   --ssl-ca=~/.mysql/root.crt \
 --ssl-mode=required <database_name> < dump.sql

Conclusion

Migration is a manageable process. With quality planning, the task will be realized without problems. In the opposite situation, errors and data loss are possible. Therefore, the approach to migration is as important as working with financial documents. Damage or loss of information may well lead to losses. But consistent execution (with preparation, templates, etc.) usually yields positive results immediately.

MySQL
12.12.2023
Reading time: 14 min

Similar

MySQL

How to Import and Export Databases in MySQL or MariaDB

Database management is a crucial aspect of Linux server and web application administration. Importing and exporting databases are essential tasks for DevOps and system administrators. At a minimum, developers should know how to back up databases and transfer them between servers. This guide explains how to import and export database dumps in MySQL or MariaDB on a Linux server (using Ubuntu as an example). Working with Databases MySQL and MariaDB are popular relational database management systems (RDBMS) used for storing data in large applications. MariaDB is a fork of MySQL developed by its original creators due to licensing concerns following Oracle's acquisition of MySQL. Both MariaDB and MySQL share identical or similar APIs and operating mechanisms. Creating a Database Connect to MySQL or MariaDB with root privileges: For MySQL: mysql -u root -p   For MariaDB: mariadb -u root -p   Create a database (if it doesn't already exist): CREATE DATABASE IF NOT EXISTS <database_name>; Viewing Databases To see the list of available databases: SHOW DATABASES; Switching Databases To switch to a specific database: USE <database_name>; Viewing Tables To list all tables in the selected database: SHOW TABLES; Common SQL Commands Creating a table: CREATE TABLE IF NOT EXISTS users (  user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,  username VARCHAR(100) NOT NULL); This creates a table named users with fields user_id and username. Inserting data into the table: INSERT INTO users (username) VALUES ('John Doe'); This adds a new row to the users table. Selecting all rows from the table: SELECT * FROM users; Monitoring MySQL/MariaDB status To check the server's global status and statistics: SHOW GLOBAL STATUS; Exporting Databases Exporting data from MySQL or MariaDB can be efficiently done using the mysqldump CLI utility or third-party tools like phpMyAdmin. The mysqldump utility allows you to save your database as an SQL dump, which contains the necessary commands for creating columns and populating them with data. This dump file can be easily managed, imported, or transferred. You will need: A database you want to export. User credentials with at least read access to the database. In the terminal, run the following command: mysqldump -u <username> -p<password> <database_name> > db_dump.SQL Where: -p<password>: Password for the database user (you can omit the password and simply use -p to prompt for it manually). db_dump.SQL: The name of the output dump file. <username>: The privileged user with read access. <database_name>: The name of the database you are exporting. To create dumps from a remote server, add the -h flag: mysqldump -h <ip-address> -u <username> -p<password> <database_name> > db_dump.SQL If the MySQL server uses a non-standard port, specify it with the -P flag: mysqldump -h <ip-address> -P <port> -u <username> -p<password> <database_name> > db_dump.SQL While the default export format is SQL, mysqldump also supports exporting data as CSV, XML, and other formats by configuring additional parameters. The SQL dump typically includes: Information about the RDBMS (MySQL or MariaDB) Commands for creating the required tables and their columns Data to populate those columns By default, it provides a comprehensive snapshot of the database structure and contents, making it an essential tool for database backups and migrations. Importing Data into MySQL or MariaDB To import a database dump, you don’t need mysqldump; a direct call to MySQL will suffice. Run the following command in your terminal: mysql -u <username> -p<password> <new_database_name> < db_dump.SQL Where: -p<password>: The user's password (use -p without the password to be prompted manually). db_dump.SQL: The dump file containing your database data. <username>: A privileged user with write access. <new_database_name>: The name of the target database to which you are importing the dump. If the process completes successfully, there will be no output. If any errors or warnings occur, MySQL or MariaDB will display them. You can check if the import was successful with these commands: SHOW DATABASES;  -- Lists all databasesUSE <database_name>;  -- Selects the target databaseSHOW TABLES;  -- Lists all tables within the selected database By executing these commands, you can confirm that the database structure and data have been imported correctly. Creating a systemd Service for Backup Suppose you want to automate the database backup (export) process. In this guide, we will create a service-timer that will trigger a script for backing up data. A Timer is a mechanism used to schedule the execution of a specific service at a given time or through certain intervals. Follow these steps to set it up: First, connect to the server and create the directory for backup scripts: mkdir -p /usr/bin/backup_scripts  # Create directory for backup scripts Create and open the file /usr/bin/backup_scripts/mysql_backup.sh in any text editor (e.g., nano): nano /usr/bin/backup_scripts/mysql_backup.sh Inside the file, add the following script: TIMESTAMP=$(date +'%F') # Get the current date BACKUP_DIR='<path_to_backup_directory>' MYSQL_USER='<username>' MYSQL_PASSWORD='<password>' DATABASE_NAME='<database_name>' mkdir -p "$BACKUP_DIR/$TIMESTAMP" # Create directory for this date mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD $DATABASE_NAME > "$BACKUP_DIR/$TIMESTAMP/$DATABASE_NAME-$TIMESTAMP.sql" # Create dump find "$BACKUP_DIR" -type d -mtime +28 -exec rm -rf {} \; # Delete backups older than 28 days Replace the placeholder variables with the actual backup directory path, MySQL user credentials, and the database name. Grant execution permissions to the script: chmod +x /usr/bin/backup_scripts/mysql_backup.sh Create the service file /etc/systemd/system/mysql-backup.service: sudo nano /etc/systemd/system/mysql-backup.service Add the following content: [Unit] Description=MySQL Database Backup Service [Service] Type=oneshot ExecStart=/usr/bin/backup_scripts/mysql_backup.sh [Install] WantedBy=multi-user.target Create the timer file: sudo nano /etc/systemd/system/mysql-backup.timer Add this content to schedule the backup: [Unit] Description=Run MySQL Backup Service Weekly [Timer] OnCalendar=weekly Persistent=true [Install] WantedBy=timers.target Reload the systemd configuration, enable the timer for autostart, and start it: systemctl daemon-reload  # Reload systemd configurationsystemctl enable mysql-backup.timer  # Enable timer to start automaticallysystemctl start mysql-backup.timer  # Start the timer Check the status of the timer and ensure it is working: systemctl status mysql-backup.timersystemctl list-timers  # Lists active timers Now, your system will automatically create a backup of the specified database every week. Export and Import via phpMyAdmin You can perform database imports and exports not only through command-line utilities but also through the phpMyAdmin web interface. This method is typically more convenient when the dump size is small (less than 1GB). This section will cover the basic process of importing and exporting databases. Export To export a database: Go to the phpMyAdmin interface and select the desired database from the left-hand panel. Click on the Export tab. Choose export method: Quick Export: Select this if you want a basic export with default settings. Custom Export: Choose this for more specific export options, such as selecting certain tables, formats, or compression methods. Click Export. To export specific tables: Click on the database name in the left sidebar to view its tables. Select the tables you want to export by checking the boxes next to their names. At the bottom of the page, choose Export from the list of actions. On the next page, verify the export format and options, then click Go to save the dump to your local machine. Import The process of importing a database is very similar to exporting. Follow these steps: Open phpMyAdmin and navigate to the database you want to import into. If the database doesn't exist, create it by clicking Create Database from the left sidebar. Inside the database, click on the Import tab. Click the Choose File button to browse for and select the SQL dump file from your device. Choose the necessary options like file encoding, format (typically default settings are fine), and other options as needed. Click Go to start the import process. Once the process is complete, you will see the imported files and their contents listed in the left sidebar. You can also modify them if needed. Conclusion The choice of method depends on your needs: phpMyAdmin is ideal for manually creating backups or for quick access to a database. It’s user-friendly and simple for small-scale tasks. Using command-line utilities would be more efficient and flexible for automation or if you’re transferring infrastructure.
10 February 2025 · 8 min to read
MySQL

How to Secure MySQL Server

MySQL is the best choice for relational database management, but its widespread use also makes it an appealing target for potential attackers. This tutorial outlines essential steps to fortify your MySQL server, protecting your data from unauthorized access and activities that are malicious. Prerequisites Prior to diving into security configurations, ensure the prerequisites mentioned below: MySQL is Installed and Running: Consider reading the official MySQL documentation if needed.  Access to Administrator Privileges: sudo or root access is required for many steps. Familiarity with MySQL Commands: Basic command-line knowledge will be helpful. Understanding Threat Landscape MySQL databases face various threats, including:   Unauthorized Logins: Weak credentials or misconfigurations can allow attackers to access your data.   SQL Injection Attacks: Unvalidated inputs in applications can expose your database to manipulation.   Insufficient Network Security: Open ports and weak firewalls leave the server vulnerable.   Proactively securing the database reduces the likelihood of such incidents. Step 1: Update the Server and MySQL As new updates provide new security features and also fixes bugs, it is highly important that your system stays updated because if will fix known vulnerabilities and leverage latest security enhancements.  Utilize the commands mentioned below to update both the operating system and MySQL. sudo apt updatesudo apt upgrade -y Verify the current MySQL version: mysql --version Keep an eye on official release notes to understand updates and security patches. Step 2: Secure Initial Configuration   The mysql_secure_installation script is an essential tool for strengthening the security of your MySQL server's. It streamlines sensitive tasks such as: Setting a root password Removing anonymous user accounts Disabling remote root logins Deleting the test database To run the script: sudo mysql_secure_installation Follow the prompts to implement the recommended security measures. Step 3: Configure User Authentication   Effective user management is essential for database security.   Use Unique Users for Applications Create separate users for each application, and assign only the permissions they need. For example:   CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'StrongPassword123!';GRANT SELECT, INSERT ON app_database.* TO 'app_user'@'localhost';FLUSH PRIVILEGES; This ensures that a breach in one application doesn’t compromise the entire database.   Enable Authentication Plugins MySQL provides plugins like caching_sha2_password for secure authentication. To enable it:   ALTER USER 'root'@'localhost' IDENTIFIED WITH 'caching_sha2_password' BY 'SecurePassword!'; Step 4: Enforce Password Policies   If passwords are strong then the possibility of brute force attacks may not be of any help for the hackers. Install the password validation plugin if it isn’t already enabled: INSTALL PLUGIN validate_password SONAME 'validate_password.so'; Configure password strength rules in the MySQL configuration file: validate_password_policy=STRONGvalidate_password_length=12 These settings enforce strong, hard-to-guess passwords. Step 5: Restrict Remote Access   Unnecessary remote access exposes the database to risks. Disable Remote Root Access By default, MySQL allows root logins from remote systems. Disable this feature by editing the MySQL configuration file: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf Set the bind address to localhost: bind-address = 127.0.0.1 Restart the MySQL service:   sudo systemctl restart mysql Use Firewalls for Remote Connections If remote access is necessary then configure firewalls. This will only allow traffic from trusted IPs. sudo ufw allow from <trusted_ip> to any port 3306sudo ufw enable Step 6: Secure Data Transmission   Encryption will make sure that data transferred between the client and server is safe from eavesdropping. Enable SSL/TLS Certificates for MySQL are generated automatically at the time of installation.  Add the following lines to /etc/mysql/mysql.conf.d/mysqld.cnf:   [mysqld]ssl-ca=/var/lib/mysql/ca.pemssl-cert=/var/lib/mysql/server-cert.pemssl-key=/var/lib/mysql/server-key.pemrequire_secure_transport = ON Restart MySQL to apply changes. Use tools like OpenSSL to verify encrypted connections. Step 7: Audit and Monitor Database Activity   Monitoring user activity can help detect unauthorized actions. Enable Logs Activate general logs and error logs in the configuration file:   general_log=1log_error=/var/log/mysql/error.log Analyze Access Patterns Periodically review logs to identify anomalies or suspicious activity. Use automated tools like Percona Monitoring and Management for advanced analytics. Step 8: Protect Against SQL Injection   SQL injection is a common attack vector for web-based MySQL applications. Mitigate this risk by: Using Parameterized Queries: This prevents attackers from injecting malicious SQL commands Validating User Inputs: Sanitize and validate inputs at the application level. Implementing a Web Application Firewall (WAF): Tools like ModSecurity can block malicious queries. Step 9: Regular Backups and Disaster Recovery   Prepare for the unexpected by setting up automated backups. Full Database Backups Use mysqldump to create complete backups:   mysqldump -u root -p --all-databases > backup.sql Incremental Backups For large databases, consider incremental backups using tools like Percona XtraBackup. Step 10: Disable Unused Features   Reducing the database’s attack surface is crucial.   Disable Unused Plugins Run the following command to list active plugins:   SHOW PLUGINS; Unload any unnecessary plugins UNINSTALL PLUGIN plugin_name; Remove Sample Databases Delete test databases that come pre-installed with MySQL:   DROP DATABASE test; Step 11: Use Security Updates and Best Practices   Regularly update MySQL to address vulnerabilities and ensure you’re using the most secure version. Stay connected with the MySQL Community for updates, news, and security alerts. Advance Practices: Segmentation Isolate your database server from other services using network segmentation to reduce the risk of unauthorized access. Intrusion Detection Systems (IDS). Use tools like Snort to monitor for unusual activity and detect potential intrusions in real-time. Two-Factor Authentication (2FA). Enable 2FA for administrative accounts to add an extra layer of protection against unauthorized access. Conclusion Securing a MySQL server requires a comprehensive approach, combining careful configuration, continuous monitoring, and proactive management. If you utilize these practices then your database can be safeguarded very effectively, protecting sensitive data as well as mitigating the chance of unauthorized access. You must evaluate and update the security measures regularly so that you can stay prepared for emerging threats.
24 January 2025 · 6 min to read
Debian

How to Install MySQL on Debian

Installing MySQL on Debian effectively creates a robust and flexible database (DB) infrastructure that accommodates a wide range of applications as well as services. It is renowned for its scalability, dependability, and durability. By setting it, individuals experience the operations in an efficient manner and enhance the overall efficiency of DB infrastructure. This combination is especially beneficial for administrators, DB analysts, and industries that demand a dependable database solution for dealing with huge data. Additionally, MySQL's comprehensive guide and supporters help make it simpler to troubleshoot problems and enhance operations.  In this guide, we will demonstrate the thorough procedure for installing and configuring MySQL on Debian. How to Install MySQL on Debian The default repositories do not contain the MySQL database server package on Debian. To install it on a  Linux system follow the below instructions. We will download the recent version of the MySQL. Step 1: Download MySQL Package Let us obtain the MySQL repository information package, which is in the .deb format: wget https://dev.mysql.com/get/mysql-apt-config_0.8.30-1_all.deb Note: To authenticate the most updated release, go to the MySQL repository webpage. Step 2: MySQL Configuration Package Installation Then, employ the .deb file for initializing the installation via dpkg: sudo dpkg -i mysql-apt-config_0.8.30-1_all.deb Respond to the prompt. For instance, pick MySQL Server & Cluster and hit Enter for starting configurations: For picking a version such as (mysql-8.4-lts), scroll downward and hit OK for the next step: Step 3: Refresh the System Now, update the server's package indexes to implement the updated MySQL info: sudo apt update Step 4: MySQL Installation Debian's default manager makes sure to install MySQL in an easier manner. Installing the package with this command: sudo apt install mysql-server -y You will see the interface for setting the root account. Input a stronger password to secure the database. In the end, hit the Ok button: Check the version on the server via the --version utility: mysql --version Step 5: Managing the Services Now, you can enable the MySQL service to initialize automatically at boot time: sudo systemctl enable mysql Activate the service via the systemctl utility: sudo systemctl start mysql Check if the system service is operational by viewing its status: sudo systemctl status mysql Step 6: MySQL Secure Installation The key or password that the individual created at the initialising procedure is currently protecting the root DB user on the server. MySQL also includes other insecure defaults, such as remote access to test databases and the root database user on the server.  It is vital to secure the MySQL installation after it has been completed as well as disable all unsafe default settings. There is a security script that can assist us in this procedure. Run the script: sudo mysql_secure_installation To activate the VALIDATE PASSWORD component and guarantee stringent password procedures, type Y and hit Enter. Next, you will need to configure several security settings: Set the Root Password: Select a strong password and make sure that it is correct. Configure the password policy for the DB server. For instance, type 2 to permit only the strong passwords on the server and hit Enter. When required to modify the root password, input N; alternatively, input Y to modify the password. Eliminate Anonymous Users: It is advised to eliminate the accessibility of anonymous users. For this, input Y and Enter when prompted. Prevent Accessibility of Remote Root: It is a better practice to avoid remote root login for multiple security concerns. To prevent the root user from having a remote access, input Y and hit Enter. Delete the Test DB: For enhancing security, the test database, which is utilized for testing, can be deleted. To do so, input Y and hit Enter. Refreshing Privilege Tables: It guarantees that all modifications are implemented instantly. To implement the configuration and edit the privileges table, hit Enter. Step 7: Access MySQL Utilizing the mysql client utility, MySQL establishes the connection and provides access to the database server console.  Now, access the shell interface and run general statements on the DB server. Let’s input the root and the password created at the time of the safe installation procedure: sudo mysql -u root -p Step 8: Basic MySQL Operations The creation of a DB and a new user for your applications rather than utilizing the root is a better practice. To accomplish the task, employ the given instructions: Create a Database: First, create a database. For instance, hostmandb is created via the below command: CREATE DATABASE hostmandb; Display All Databases: List all databases to make sure hostmandb is created: SHOW DATABASES; Create of a New User: Create a user and assign a strong password. In our example, we set Qwer@1234 as a password for the user  minhal. Replace these values with your data. CREATE USER 'minhal'@'localhost' IDENTIFIED BY 'Qwer@1234'; Give Permissions to the User: Give complete access to the hostmandb to the new user: GRANT ALL PRIVILEGES ON hostmandb.* TO 'minhal'@'localhost'; Flush Privileges: To implement the modifications, refresh the table: FLUSH PRIVILEGES; Exit the Shell: For closing the interface, utilize the EXIT statement: EXIT; Access MySQL Console as the Particular User For the purpose of testing hostmandb access, log in to MySQL as the new user, in our case minhal. sudo mysql -u minhal -p It accesses the console after entering the minhal user password when prompted: For verification, display all DBs and confirm that the hostmandb is available: SHOW DATABASES; Step 9: Configuration for Remote Access Setting up the server for supporting remote accessibility is necessary if an individual is required to access MySQL remotely. Follow these steps: Access the mysql.cnf file and modify the particular file for MySQL: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf Look for the line with the bind-address and change it to: bind-address = 0.0.0.0 Reload the MySQL service: sudo systemctl restart mysql Permit the user to have remote access: sudo mysql -u root -p GRANT ALL PRIVILEGES ON hostmandb.* TO 'minhal'@'localhost';FLUSH PRIVILEGES;EXIT; Step 10: Firewall Configuration If you have a firewall activated, you need to open the MySQL port 3306 to traffic. Set up the firewall following the below steps: Allow traffic through MySQL: sudo ufw allow mysql Now, activate the UFW on the system: sudo ufw enable Reload the firewall: sudo ufw reload Step 11: Restore and Backup Maintaining regular backups is crucial to avoiding data loss. The mysqldump utility is provided by MySQL for backup creation. To achieve this, consider these instructions: Backup a Single Database: This command employs mysqldump to create the backup of the hostmandb as a hostmandb_backup.sql file: sudo mysqldump -u root -p hostmandb> hostmandb_backup.sql Backup All Databases: For creating a backup of all databases as a file named all_databases_backup.sql with root privileges, utilize mysqldump: sudo mysqldump -u root -p --all-databases > all_databases_backup.sql Restore a Particular Database: Now, restore the hostmandb from the backup file hostmandb_backup.sql: sudo mysql -u root -p hostmandb < hostmandb_backup.sql Step 12: Optimize MySQL Operations (Optional) Depending on the workload and server resources, you can adjust settings to guarantee peak performance. These instructions will help you maximize MySQL's speed: Adjust InnoDB Buffer Pool Size: Caches for data and indexes are kept in the InnoDB buffer pool. Expanding its size can enhance its functionality. Edit the MySQL configuration file: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf The below line should be added or changed: innodb_buffer_pool_size = 1G Its size should be adjusted according to the amount of memory on the server. Enable Query Cache: The query cache stores the outcome of SELECT queries. Enabling it can enhance operations for repetitive queries. Modify the .cnf file: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf Add or edit the below lines: query_cache_type = 1query_cache_size = 64M Optimize Table Structure: Frequently optimize your customers table in hostmandb to recover wasted space and boost efficiency: USE hostmandb;OPTIMIZE TABLE customers; Analyze Operations: DB operations can be tracked and analyzed with tools like MySQL Workbench and mysqltuner. Using the command below, install mysqltuner: sudo apt install mysqltuner Run mysqltuner to get performance recommendations: sudo mysqltuner Conclusion Installing a MySQL environment is important in today's digital world. By following this instruction, you'll be able to safely install and connect to your MySQL database. This strategy not only increases security but also improves remote database maintenance efficiency. It helps to prevent breaches and ensures the confidentiality of your data. This article has given thorough instructions for the installation of MySQL's database environment on Debian. It is suggested that MySQL servers should be regularly monitored and optimized to guarantee optimum performance and dependability. In addition, Hostman offers pre-configured and ready-to-use cloud databases, including cloud MySQL. 
14 January 2025 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support