MySQL Option Settings: Complete Guide from Basics to Fixes

目次

1. What are MySQL options?

MySQL is a powerful database management system used by many websites and applications. Among its features, “option settings” are a crucial element for optimizing performance and strengthening security. This article will step-by-step explain MySQL options from basics to advanced usage.

What are MySQL options?

MySQL options are configuration items that finely control the behavior of the MySQL server and client. For example, options that specify the target host or username, cache size settings to improve database performance, and many others. Properly configuring these options provides benefits such as:
  • Performance improvement: Efficiently utilize server resources.
  • Security enhancement: Prevent unauthorized access.
  • Troubleshooting: Quickly identify the cause of errors.

How to configure MySQL options

MySQL options are primarily set using the following methods.
  1. Specifying via command line is the method of specifying options directly on the command line. For example, you can connect to a specific host with the following command.
   mysql --host=127.0.0.1 --user=root --password=yourpassword
  1. Specifying via option file (my.cnf) is the method of saving options to a file that MySQL reads at startup. This eliminates the need to enter multiple command-line options each time.

Article structure

In this article, we will explain MySQL options in detail following this flow.
  • Basic option configuration methods
  • Practical option examples
  • Troubleshooting and FAQ
By reading this article, you’ll gain both foundational knowledge and practical skills for MySQL options.

2. Basics and Configuration of MySQL Options

MySQL options are essential for optimizing system behavior and performance. In this section, we explain information useful for real-world scenarios by introducing basic configuration methods and concrete examples.

Roles and Features of MySQL Options

MySQL options are used to customize the behavior of the server and client. This allows you to achieve the following purposes.
  • Connection Management: Specify connection information such as username, password, host.
  • Performance Tuning: Optimize query cache size and buffer pool size.
  • Security Enhancement: SSL settings and remote connection restrictions.
Since options can be flexibly changed according to use cases, it is important to apply optimal settings based on the environment and operational needs.

Explanation of Configuration Methods

MySQL options can be configured using the two main methods below.

1. Specifying via Command Line

On the command line, you can temporarily specify options when launching the MySQL client. Below is a common usage example.
mysql --host=127.0.0.1 --user=root --password=yourpassword
In this command,
  • --host: Specifies the target host
  • --user: Specifies the username
  • --password: Specifies the password
Note: Entering the password directly on the command line poses a security risk, so it is recommended to prompt for it interactively.
mysql --host=127.0.0.1 --user=root -p
With this format, you will be prompted for the password.

2. Using an Option File (my.cnf)

Saving options to a file eliminates the need to enter the same settings each time. Location of the my.cnf file
  • Linux/Unix: /etc/my.cnf or ~/.my.cnf
  • Windows: %PROGRAMDATA%MySQLMySQL Server x.xmy.ini
Example File Structure
[client]
host=127.0.0.1
user=root
password=yourpassword
[mysqld]
port=3306 datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock innodb_buffer_pool_size=128M query_cache_size=16M
In this example,
  • [client] section defines client settings.
  • [mysqld] section defines server-side settings.
After editing the configuration file, restart the MySQL service to apply the changes.
sudo systemctl restart mysql

Specific Sample Code and Explanation

Example 1: Specifying a Destination
mysql --host=192.168.1.100 --port=3306 --user=testuser --password=testpass
This is an example of connecting to a specific host and port. It is useful in multiple server environments. Example 2: Changing Memory Settings
[mysqld]
innodb_buffer_pool_size=256M
Setting the InnoDB buffer pool size to 256 MB enables handling of large query workloads.

How to Verify Settings After Configuration

To verify that the settings have been applied correctly, use the following commands. Check Client Settings
mysql --print-defaults
Check Server Settings
mysqladmin variables
This will list the current configuration values.

3. Commonly Used MySQL Options and Category-by-Category Explanation

MySQL provides many options, but here we organize and explain the most commonly used ones by category. Leveraging these settings enables connection management, performance optimization, and security hardening.

1. Connection-Related Options

The options you specify when connecting to MySQL are the most frequently used basic settings.
OptionDescriptionExample
--host (-h)Specifies the hostname or IP address to connect to.mysql -h 127.0.0.1
--port (-P)Specifies the port number to use for the connection.mysql -P 3306
--user (-u)Specifies the username for the connection.mysql -u root
--password (-p)Specifies the password (be mindful of security).mysql -p yourpassword
--database (-D)Specifies the initial database to connect to.mysql -D testdb
--socketSpecifies the UNIX domain socket file.mysql --socket=/tmp/mysql.sock
Key Points:
  • In development environments, specifying IP addresses or hostnames makes testing across multiple server setups and data migration smoother.
  • From a security standpoint, it’s preferable to avoid embedding passwords directly in commands and instead enter them interactively.

2. Performance Tuning Options

These options are for optimizing MySQL performance. Proper tuning is especially required for high-load systems.
OptionDescriptionExample
innodb_buffer_pool_sizeSpecifies the amount of memory used for the InnoDB buffer pool (database cache).innodb_buffer_pool_size=256M
query_cache_sizeSets the size of the query cache. It was removed in MySQL 8.0.query_cache_size=16M (MySQL 5.7 and earlier only)
max_connectionsSpecifies the maximum number of simultaneous client connections.max_connections=200
thread_cache_sizeSpecifies the size of the thread cache.thread_cache_size=16
sort_buffer_sizeSpecifies the buffer size used during sort operations.sort_buffer_size=1M
Key Points:
  • Because default settings may not fully utilize resources, conduct load testing to determine optimal values.
  • innodb_buffer_pool_size is the most critical option for improving InnoDB table performance.

3. Security-Related Options

These options are used to strengthen database security. Be sure to review them to enhance safety.
OptionDescriptionExample
skip-networkingDisables network-based connections (only local connections are allowed).skip-networking
bind-addressSpecifies the IP address that is allowed to connect.bind-address=127.0.0.1
ssl-caSpecifies the CA file for SSL certificates.ssl-ca=/etc/mysql/ca.pem
require_secure_transportAllows only encrypted connections.require_secure_transport=ON
default_authentication_pluginSpecifies the authentication plugin.default_authentication_plugin=caching_sha2_password
Key Points:
  • If internet-based connections are unnecessary, enable skip-networking to prevent unauthorized external access.
  • Requiring SSL connections strengthens encryption of the communication channel.

4. Other Handy Options

Below are some other useful options.
OptionDescriptionExample
log-errorSpecifies the error log file.log-error=/var/log/mysql/error.log
slow_query_logEnables logging of slow queries.slow_query_log=1
long_query_timeSets the threshold in seconds for classifying a query as slow.long_query_time=2
general_logLogs all queries (recommended for development).general_log=1
expire_logs_daysSpecifies the number of days to retain binary logs.expire_logs_days=7
Key Points:
  • During development or debugging, you can enable general_log to review query logs, but be cautious of performance impact in production.
  • Log management is extremely useful for troubleshooting and audit trails.

4. Option Configuration Priority and Considerations

Because MySQL allows options to be set in multiple ways, it’s important to understand which setting takes precedence. This section explains the order in which options are applied and their behavior during conflicts, and highlights points to watch to prevent issues.

1. Order of Option Application

MySQL reads configuration from several locations at startup. Therefore, if the same option is defined in different places, you need to know which setting takes precedence.

Priority of Configuration Application

  1. Command-line Options
  • Options specified directly when starting MySQL have the highest priority.
  • Example: bash mysql --host=127.0.0.1 --user=root --port=3306
  1. User-specific configuration file (~/.my.cnf)
  • A separate file that can be configured per user.
  • Convenient for settings in local environments or personal use.
  1. System-wide configuration file (/etc/my.cnf or /etc/mysql/my.cnf)
  • Manages default settings that apply to the entire system.
  • Used to manage global settings during server operation.
  1. Default Settings
  • If not explicitly set, MySQL’s built-in default values are applied.
Example: If you set the port to 3307 in /etc/my.cnf but specify 3306 on the command line, the command-line 3306 takes precedence.

2. Behavior and Considerations When Configuration Conflicts Occur

If the same option is set in multiple locations, the setting with higher priority overwrites the others. However, configuration conflicts can cause unexpected behavior, so pay attention to the following points.

Consideration 1: Understand Command-line Priority

Since the command line takes precedence over configuration files, it’s convenient for temporary changes, but can become cumbersome to manage over the long term. Establish operational rules.

Consideration 2: Managing Configuration Files

  • Keep configuration files centralized and avoid spreading settings across multiple files.
  • When changing settings, back up the files and ensure they can be restored.

Consideration 3: Checking for Configuration Errors

A typo in a configuration file can prevent MySQL from starting. Use the following command to perform a pre‑check.
mysqld --verbose --help | grep -A 1 "Default options"
This command lets you verify that the settings are being read correctly.

3. Troubleshooting When Applying Settings

Here are ways to address issues that arise after applying settings.

1. Verify Settings Have Been Applied

Check that the options have been applied correctly.
mysqladmin variables
Check the output to see if the configuration values are reflected.

2. Check the Error Log

If a configuration error occurs, review the error log.
cat /var/log/mysql/error.log
This log records startup errors and the causes of configuration mistakes.

3. Restoring to the Initial State

If a configuration mistake prevents MySQL from starting, follow these steps to revert to the default state.
  1. Restore the configuration file from a backup.
  2. Restart the server.
   sudo systemctl restart mysql

4. Best Practices for Configuration

1. Pre‑validation in a Test Environment

Always verify changes in a test environment before modifying settings. In production, avoid making direct configuration changes.

2. Thorough Backups

Always back up configuration files before editing them.
cp /etc/my.cnf /etc/my.cnf.backup

3. Leveraging Configuration Management Tools

If multiple configuration files exist, using a version‑control system (such as Git) to track changes makes it easier to monitor modifications.

5. Best Practices for Option Settings

Optimizing MySQL option settings can significantly improve performance and security. This section explains configuration examples for different environments and concrete operational procedures, presenting practical best practices.

1. Configuration Examples by Environment

MySQL settings need to address different needs depending on the environment. Here we present recommended configurations for development and production environments.

Settings for Development Environments

In development environments, flexible settings are required to make testing and debugging work efficiently.
OptionExample SettingDescription
general_loggeneral_log=1Logs all queries. Handy for debugging.
slow_query_logslow_query_log=1Records slow queries to identify performance issues.
long_query_timelong_query_time=1Sets the slow‑query threshold to 1 second, logging even short queries.
max_connectionsmax_connections=50Keeps the maximum connections low to limit resource consumption.
innodb_buffer_pool_sizeinnodb_buffer_pool_size=64MSets memory usage to a modest level.
Key point: In development environments, take regular backups to minimize data‑loss risk. Also, because logs can fill disk space, perform regular clean‑ups.

Settings for Production Environments

In production environments, stability and performance are top priorities.
OptionExample SettingDescription
innodb_buffer_pool_sizeinnodb_buffer_pool_size=1GAllocates a large buffer size for large‑scale data processing.
max_connectionsmax_connections=200Increases connections to handle high traffic.
thread_cache_sizethread_cache_size=32Sets thread cache to improve connection efficiency.
query_cache_sizequery_cache_size=0(推奨OFF)Deprecated in MySQL 8.0. Instead, optimize the InnoDB buffer.
log_binlog_bin=mysql-binEnables binary logging to simplify recovery in case of failure.
expire_logs_daysexpire_logs_days=7Shortens binary log retention to limit disk usage.
Key point: In production, enforce strict security settings and conduct regular performance monitoring. Enabling binary logs also enables rapid recovery when failures occur.

2. Safe Procedures for Changing Settings

1. Preparation Before Changes

  1. Obtain backups Take a full backup of configuration files and the database.
   mysqldump -u root -p --all-databases > backup.sql
   cp /etc/my.cnf /etc/my.cnf.bak
  1. Validate in a test environment Before applying new settings to production, verify them in a test environment.

2. Applying the Settings

  1. Edit the configuration file.
   sudo nano /etc/my.cnf
  1. Restart the server to apply the changes.
   sudo systemctl restart mysql
  1. Verify that the settings have taken effect.
   mysqladmin variables

3. Best Practices to Prevent Issues

  1. Enforce log management Regularly check error logs and slow‑query logs to spot issues early.
  2. Strengthen access control
  • Allow connections only from specific IP addresses.
  • Block unnecessary remote access.
  1. Leverage monitoring tools Use tools such as Percona Monitoring and Management (PMM) to monitor performance and load in real time.
  2. Perform regular maintenance
  • Delete unnecessary databases and users.
  • Clear old logs and caches.
  • Optimize indexes.

6. Troubleshooting: Error Resolution Guide

In MySQL option settings, errors can occur due to incorrect configurations or environment-specific issues. This section explains common MySQL errors and how to resolve them. It presents practical troubleshooting steps to help you when problems arise.

1. Troubleshooting Connection Errors

Error 1: Access denied for user ‘root’@’localhost’

Error Message Example
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Cause
  • Mistyped username or password.
  • Issues with permission settings.
Solution
  1. Verify and Reset Password
   mysql -u root -p
If the password is unknown, reset it using the steps below.
  1. Password Reset Procedure
  2. Start MySQL in safe mode. bash sudo systemctl stop mysql sudo mysqld_safe --skip-grant-tables &
  3. Set a new password. sql UPDATE mysql.user SET authentication_string=PASSWORD('newpassword') WHERE User='root'; FLUSH PRIVILEGES;
  4. Restart the server. bash sudo systemctl restart mysql

Error 2: Can’t connect to MySQL server on ‘localhost’ (10061)

Cause
  • MySQL service is not running.
  • Port number or socket configuration is incorrect.
Solution
  1. Check Service Status
   sudo systemctl status mysql
  1. Restart the Service
   sudo systemctl restart mysql
  1. Verify Socket File Path Check the socket file location in the configuration file.
   grep socket /etc/my.cnf

2. Performance-Related Troubleshooting

Error 3: Too many connections

Error Message Example
ERROR 1040 (08004): Too many connections
Cause
  • The number of concurrent connections exceeds the limit.
Solution
  1. Check Current Connection Count
   SHOW STATUS LIKE 'Threads_connected';
  1. Increase Max Connections Modify the following option in the configuration file.
   [mysqld]
   max_connections=500
After changing the setting, restart MySQL.
   sudo systemctl restart mysql

Error 4: Query execution time is too slow

Cause
  • Insufficient query optimization.
  • Improper memory or cache settings.
Solution
  1. Check Slow Query Log Enable the slow query log to identify slow queries.
   [mysqld]
   slow_query_log=1
   long_query_time=2
   slow_query_log_file=/var/log/mysql-slow.log
  1. Review Execution Plan Examine the query execution plan and optimize indexes.
   EXPLAIN SELECT * FROM orders WHERE customer_id = 1;

3. Configuration File Troubleshooting

Error 5: Unknown variable ‘query_cache_size’

Error Message Example
ERROR 1193 (HY000): Unknown system variable 'query_cache_size'
Cause
  • A deprecated option is set for the MySQL version you are using (the query_cache_size option was removed in MySQL 8.0).
Solution
  1. Check the Version
   mysql --version
  1. Update Configuration Options
  • Remove the deprecated option and use a replacement setting.
  • For example, expand the InnoDB buffer instead of query_cache_size.
   innodb_buffer_pool_size=512M

4. Database Corruption Recovery Steps

Error 6: Table ‘tablename’ is marked as crashed and should be repaired

Error Message Example
ERROR 145 (HY000): Table './dbname/tablename' is marked as crashed and should be repaired
Cause
  • The table became corrupted while the server was down.
Solution
  1. Run the Table Repair Command
   REPAIR TABLE tablename;
  1. Use the MyISAM Check Tool
   myisamchk /var/lib/mysql/dbname/tablename.MYI
  1. Repair Procedure for InnoDB In InnoDB, recover using the following steps.
   sudo systemctl stop mysql
   sudo mysqld_safe --innodb_force_recovery=1 &

7. Frequently Asked Questions (FAQ)

When configuring MySQL options, various questions and issues can arise during actual operation. This section compiles common questions and their solutions in an FAQ format.

1. Questions About Configuration Files

Q1. I can’t find the MySQL configuration file (my.cnf). A. The location of the configuration file varies by environment, but you can check it with the following command.
mysql --help | grep my.cnf
Common locations for the configuration file are as follows:
  • Linux: /etc/my.cnf or /etc/mysql/my.cnf
  • Windows: %PROGRAMDATA%MySQLMySQL Server X.Xmy.ini
  • macOS: /usr/local/etc/my.cnf
Q2. Changes to the configuration file aren’t taking effect? A. After editing the configuration file, you need to restart the MySQL server. Use the following command.
sudo systemctl restart mysql
To verify that the settings have been applied, run the following command.
mysqladmin variables

2. Security and Authentication Questions

Q3. I’m getting an error with password authentication. What should I do? A. Password authentication errors can be caused by permission settings or differences in password format. Check the following steps.
  1. Verify user privileges
SELECT user, host FROM mysql.user;
  1. Reset password
ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpassword';
FLUSH PRIVILEGES;
  1. In MySQL 8.0 and later, the authentication plugin has changed to caching_sha2_password, which can cause compatibility issues with older clients. In that case, you can change the authentication method with the following setting.
ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'newpassword';
FLUSH PRIVILEGES;
Q4. How can I restrict connections from external sources? A. You can limit external connections by adding the following options to the configuration file.
[mysqld]
bind-address=127.0.0.1
This will block connections from anything other than localhost. To completely disable network connections, set the following.
skip-networking
Restart after making the changes.
sudo systemctl restart mysql

3. Performance Questions

Q5. What settings improve database performance? A. The main settings for performance improvement are listed below.
SettingRecommended Setting ExampleDescription
innodb_buffer_pool_sizeinnodb_buffer_pool_size=1GIncrease memory usage to speed up query processing.
query_cache_sizequery_cache_size=0 (deprecated)Deprecated in MySQL 8.0. Instead, strengthen InnoDB.
thread_cache_sizethread_cache_size=16Enable thread reuse to improve connection efficiency.
tmp_table_sizetmp_table_size=64MIncrease the size of temporary tables.
max_connectionsmax_connections=200Increase the number of simultaneous connections to improve load distribution.
Q6. I want to identify and address slow queries? A. You can enable the slow query log to pinpoint problematic queries.
  1. Edit the configuration file.
[mysqld]
slow_query_log=1
long_query_time=2
slow_query_log_file=/var/log/mysql/slow.log
  1. Restart the server to apply the settings.
sudo systemctl restart mysql
  1. Check the slow query log.
cat /var/log/mysql/slow.log

4. Other Common Questions

Q7. Is there a way to reset the configuration? A. To reset the configuration, either revert the configuration file to its default state or create a new one. Below is an example of the reset procedure.
  1. Back up the current configuration.
cp /etc/my.cnf /etc/my.cnf.bak
  1. Restore the default configuration file.
sudo cp /usr/share/mysql/my-default.cnf /etc/my.cnf
  1. Restart the server.
sudo systemctl restart mysql

8. Summary

In this article, we provided a comprehensive guide to MySQL option settings, covering everything from basics to advanced topics. We walked through configuration methods, specific options, and troubleshooting to help you acquire practical knowledge. Here, we recap the key points and reaffirm the importance of MySQL option settings.

1. Reviewing the Article’s Key Points

Basics

  • Understanding the overview and role of MySQL options, we learned the basic configuration methods using the command line and configuration files.

Practical

  • Category-wise explanations of commonly used options introduced configuration examples useful for connection management, performance tuning, and security hardening.
  • Understanding priority and conflict considerations explained procedures for efficient operation while preventing configuration errors.

Advanced

  • Environment-specific configuration examples and best practices provided concrete optimal settings for development and production environments and taught how to apply them safely.
  • Troubleshooting and FAQ detailed common issues that arise during operation and their solutions.

2. The Importance of MySQL Option Settings

Performance Optimization

Proper option settings enable efficient resource utilization and faster query processing. In large-scale databases or high-load environments, performance tuning directly translates to overall system efficiency.

Security Hardening

By properly restricting external access and configuring SSL, you can prevent unauthorized access and data leaks. Tailored security settings for each operational environment are essential.

Improving Troubleshooting Capability

Through log management and error message analysis, you can respond quickly when issues arise. Proactively applying proper settings to prevent problems is crucial.

3. Future Action Plan

Review and Optimize Settings

  • Review your current MySQL configuration and optimize it using the best practices presented in this article.

Leverage a Test Environment

  • Always validate new settings or changes in a test environment before applying them to production to minimize risk.

Create Documentation and Records

  • Document configuration changes and troubleshooting procedures to aid future operations and knowledge sharing within the team.

4. Conclusion

MySQL option settings play a critical role in database administration. As system size grows, proper configuration and management have an increasingly significant impact on performance and security. Use this article as a reference to tailor settings to your operational environment and aim for a stable system. Continuously review configurations and adopt the latest best practices to achieve a more robust and efficient database operation.