MySQL Options Explained: How to Configure my.cnf and Command-Line Settings

目次

1. What Are MySQL Options?

MySQL is a powerful database management system used by many websites and applications. Among its many features, “option settings” are a critical element for performance optimization and security hardening. In this article, we’ll explain MySQL options step by step—from the basics to more advanced use cases.

What Are MySQL Options?

MySQL options are configuration items used to finely control how the MySQL server and clients behave. For example, there are options to specify the host you connect to or the username you use, as well as settings such as cache sizes to improve database performance. By configuring these options properly, you can gain benefits such as:

  • Improved performance: Use server resources more efficiently.
  • Stronger security: Prevent unauthorized access.
  • Troubleshooting: Identify the cause of errors more quickly.

How to Configure MySQL Options

MySQL options are mainly configured in the following ways:

  1. Specify them on the command line
    This method specifies options directly on the command line. For example, you can connect to a specific host using the following command:
   mysql --host=127.0.0.1 --user=root --password=yourpassword
  1. Specify them in an option file (my.cnf)
    This method saves options in a file and has MySQL read them at startup. This eliminates the need to type multiple command-line options every time.

Article Structure

In this article, we’ll explain MySQL options in detail using the following flow:

  • How to configure basic options
  • Practical options you’ll actually use
  • Troubleshooting and FAQ

By the end, you’ll have both foundational knowledge and practical skills for working with MySQL options.

2. MySQL Option Basics and How to Configure Them

MySQL options are essential for optimizing system behavior and performance. In this section, we’ll explain basic configuration methods and practical examples that are useful in real-world scenarios.

Roles and Characteristics of MySQL Options

MySQL options are used to customize how the server and clients operate. This helps you achieve goals such as:

  • Connection management: Specify connection details such as username, password, and host.
  • Performance tuning: Optimize settings like query cache size and buffer pool size.
  • Security improvements: Configure SSL and restrict remote connections.

Because options can be changed flexibly depending on your needs, it’s important to choose optimal settings based on your environment and operational requirements.

Configuration Methods Explained

MySQL options can be configured in two primary ways:

1. Setting Options on the Command Line

On the command line, you can launch the MySQL client with temporary option settings. Here is a common 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 a password directly on the command line increases security risk. It’s recommended to prompt for the password interactively instead.

mysql --host=127.0.0.1 --user=root -p

With this format, you’ll be prompted to enter the password.

2. Using an Option File (my.cnf)

Saving options in a file reduces the hassle of typing the same settings each time.

Where to find my.cnf

  • Linux/Unix: /etc/my.cnf or ~/.my.cnf
  • Windows: %PROGRAMDATA%\MySQL\MySQL Server x.x\my.ini

Example configuration 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:

  • The [client] section defines client settings.
  • The [mysqld] section defines server-side settings.

After editing the configuration file, restart the MySQL service to apply the changes.

sudo systemctl restart mysql

Concrete Sample Code and Explanations

Example 1: Specifying a remote host

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’s useful when working across multiple server environments.

Example 2: Changing memory settings

[mysqld]
innodb_buffer_pool_size=256M


Setting the InnoDB buffer pool size to 256MB helps support large-scale query processing.

How to Verify Settings After Applying Them

To confirm whether your settings have been applied correctly, use the following commands.

Check client defaults

mysql --print-defaults

Check server variables

mysqladmin variables

This will display the current configuration values.

3. Commonly Used MySQL Options by Category

MySQL provides many options. Here, we organize and explain commonly used options by category. By leveraging these settings, you can improve connection management, optimize performance, and strengthen security.

1. Connection-Related Options

Options specified when connecting to MySQL are among the most frequently used basic settings.

OptionDescriptionExample
--host (-h)Specifies the host name or IP address to connect to.mysql -h 127.0.0.1
--port (-P)Specifies the port number used for the connection.mysql -P 3306
--user (-u)Specifies the username used for the connection.mysql -u root
--password (-p)Specifies the password (be careful about security).mysql -p yourpassword
--database (-D)Connects while specifying the initial database.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 and data migration across multiple server environments smoother.
  • For security, it’s better not to write the password directly in the command; use interactive input instead.

2. Performance Tuning Options

These options help optimize MySQL performance. In high-load systems, proper tuning is especially important.

OptionDescriptionExample
innodb_buffer_pool_sizeSpecifies the memory size used for database caching.innodb_buffer_pool_size=256M
query_cache_sizeSets the query cache size. Removed in MySQL 8.0.query_cache_size=16M (MySQL 5.7 and earlier only)
max_connectionsSpecifies the maximum number of concurrent 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 sorting operations.sort_buffer_size=1M

Key points:

  • Default settings may not fully utilize resources, so run load testing and tune values accordingly.
  • innodb_buffer_pool_size is one of the most important options for improving InnoDB table performance.

3. Security-Related Options

These options are used to strengthen database security. Make sure to review them to improve safety.

OptionDescriptionExample
skip-networkingDisables network connections (only local connections are allowed).skip-networking
bind-addressSpecifies the IP address 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 access is not required, enable skip-networking to prevent unauthorized external access.
  • Requiring SSL connections can strengthen encryption for data in transit.

4. Other Useful Options

Below are some other useful options.

OptionDescriptionExample
log-errorSpecifies the error log file.log-error=/var/log/mysql/error.log
slow_query_logEnables a log that records slow queries.slow_query_log=1
long_query_timeSets the threshold (in seconds) for what counts as a slow query.long_query_time=2
general_logLogs all queries (recommended for development).general_log=1
expire_logs_daysSpecifies how many days to keep binary logs.expire_logs_days=7

Key points:

  • In development or debugging, you can enable general_log to review query history, but be careful about performance impact in production.
  • Log management is extremely useful for troubleshooting and audit trails.

4. Option Precedence and Important Notes

Because MySQL options can be configured in multiple ways, it’s important to understand which settings take highest priority. In this section, we explain the order in which options are applied, how MySQL behaves when conflicts occur, and key precautions to help you avoid problems.

1. The Order in Which Option Settings Are Applied

When MySQL starts, it reads configuration from multiple locations. If the same option is defined in multiple places, you need to know which setting will take precedence.

Configuration Precedence (Priority Order)

  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 per-user file for individual settings.
  • Useful for local environments and personal setups.
  1. System-wide configuration file (/etc/my.cnf or /etc/mysql/my.cnf)
  • Manages default settings applied across the entire system.
  • Used to manage global settings during server operations.
  1. Default settings
  • If not explicitly configured, MySQL’s built-in default values are used.

Example:
If the port is set to 3307 in /etc/my.cnf but 3306 is specified on the command line, the command-line value (3306) takes precedence.

2. Behavior and Precautions When Settings Conflict

If the same option is configured in multiple places, MySQL will overwrite values according to precedence. However, configuration conflicts can cause unexpected behavior, so keep the following in mind.

Note 1: Understand Command-Line Priority

Because the command line overrides configuration files, it’s convenient for temporary changes, but it can become difficult to manage in long-term operations. Establish operational rules.

Note 2: Manage Configuration Files Carefully

  • Manage configuration files centrally and avoid scattering settings across multiple files.
  • When changing settings, take backups and keep the system in a restorable state.

Note 3: Check for Configuration Errors

If there are mistakes in a configuration file, MySQL may fail to start. Perform a pre-check with the following command:

mysqld --verbose --help | grep -A 1 "Default options"

This command helps confirm whether the configuration will be read correctly.

3. Troubleshooting When Applying Settings

Here are steps to take if problems occur after applying configuration changes.

1. Confirm the Settings Were Applied

Check whether options are being applied correctly.

mysqladmin variables

Check whether the output reflects the expected values.

2. Check the Error Log

If a configuration error occurs, check the error log.

cat /var/log/mysql/error.log

This log records startup errors and the causes of configuration mistakes.

3. Restore to the Initial State

If MySQL can’t start due to a configuration mistake, restore the default state using these steps:

  1. Restore the configuration file from a backup.
  2. Restart the server.
   sudo systemctl restart mysql

4. Best Practices for Applying Configuration Settings

1. Validate in a Test Environment First

Before changing settings, always verify behavior in a test environment. Especially in production, you should avoid applying changes directly without prior validation.

2. Back Up Thoroughly

Before editing configuration files, always take a backup.

cp /etc/my.cnf /etc/my.cnf.backup

3. Use Configuration Management Tools

If multiple configuration files exist, using a version control tool (such as Git) to track history makes it easier to audit and trace changes.

5. Best Practices for Option Settings

By optimizing MySQL option settings, you can significantly improve performance and security. In this section, we explain environment-specific examples and concrete operational procedures, and introduce practical best practices.

1. Environment-Specific Configuration Examples

MySQL settings should be tailored to the needs of your environment. Here, we introduce recommended settings for development environments and production environments.

Recommended Settings for Development Environments

In development environments, flexible settings are needed so testing and debugging can proceed efficiently.

OptionExample SettingDescription
general_loggeneral_log=1Logs all queries. Useful 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 to capture shorter queries too.
max_connectionsmax_connections=50Limits maximum connections to reduce resource consumption.
innodb_buffer_pool_sizeinnodb_buffer_pool_size=64MKeeps memory usage smaller for lightweight environments.

Key points: In development environments, take regular backups to reduce the risk of data loss. Also, logs can consume disk space, so perform regular cleanup.

Recommended Settings for Production Environments

In production environments, prioritize stability and performance above all.

OptionExample SettingDescription
innodb_buffer_pool_sizeinnodb_buffer_pool_size=1GAllocates a larger buffer pool for large-scale data processing.
max_connectionsmax_connections=200Increases connections to handle higher traffic.
thread_cache_sizethread_cache_size=32Improves connection efficiency by caching threads.
query_cache_sizequery_cache_size=0 (recommended OFF)Not recommended in MySQL 8.0. Optimize the InnoDB buffer instead.
log_binlog_bin=mysql-binEnables binary logging to simplify recovery after failures.
expire_logs_daysexpire_logs_days=7Limits disk usage by keeping binary logs for fewer days.

Key points: In production, enforce strict security settings and monitor performance regularly. Enabling binary logs helps you recover more quickly when incidents occur.

2. Safe Procedures When Changing Settings

1. Preparation Before Changes

  1. Create backups
    Create full backups of both the configuration file 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 behavior in a test environment.

2. Steps to Apply 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 are applied.
   mysqladmin variables

3. Best Practices to Prevent Trouble

  1. Manage logs thoroughly
    Check error logs and slow query logs regularly to detect early signs of issues.
  2. Strengthen access control
  • Allow connections only from specific IP addresses.
  • Block unnecessary remote access.
  1. Use monitoring tools
    Use tools such as Percona Monitoring and Management (PMM) to monitor performance and load in real time.
  2. Perform regular maintenance
  • Remove unnecessary databases and users.
  • Clear old logs and caches.
  • Optimize indexes.

6. Troubleshooting: Error Resolution Guide

With MySQL option settings, errors can occur due to incorrect configuration or environment-specific issues. In this section, we explain common MySQL errors and how to fix them. We’ll provide practical troubleshooting steps you can use when problems arise.

1. Troubleshooting Connection Errors

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

Example error message

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Cause

  • Incorrect username or password.
  • Permission settings are incorrect.

Solution

  1. Verify and reset the password
   mysql -u root -p

If you don’t know the password, reset it using the following steps.

  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

  • The MySQL service is not running.
  • The port number or socket settings are incorrect.

Solution

  1. Check service status
   sudo systemctl status mysql
  1. Restart the service
   sudo systemctl restart mysql
  1. Check the socket file path
    Check the socket file location in the configuration file.
   grep socket /etc/my.cnf

2. Troubleshooting Performance Issues

Error 3: Too many connections

Example error message

ERROR 1040 (08004): Too many connections

Cause

  • The number of concurrent connections exceeds the limit.

Solution

  1. Check the current number of connections
   SHOW STATUS LIKE 'Threads_connected';
  1. Increase the maximum number of connections
    Change 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

  • The query is not optimized.
  • Memory or cache settings are inappropriate.

Solution

  1. Check the 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 the execution plan
    Review the query execution plan and optimize indexes.
   EXPLAIN SELECT * FROM orders WHERE customer_id = 1;

3. Troubleshooting Configuration File Issues

Error 5: Unknown variable ‘query_cache_size’

Example error message

ERROR 1193 (HY000): Unknown system variable 'query_cache_size'

Cause

  • A removed option is configured for your MySQL version (in MySQL 8.0, query_cache_size was removed).

Solution

  1. Check your version
   mysql --version
  1. Update configuration options
  • Remove deprecated options and use alternative settings instead.
  • Example: Expand the InnoDB buffer instead of query_cache_size.
   innodb_buffer_pool_size=512M

4. Recovery Procedures for Database Corruption

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

Example error message

ERROR 145 (HY000): Table './dbname/tablename' is marked as crashed and should be repaired

Cause

  • The table was corrupted while the server was stopped.

Solution

  1. Run a table repair command
   REPAIR TABLE tablename;
  1. Use a MyISAM check tool
   myisamchk /var/lib/mysql/dbname/tablename.MYI
  1. Recovery steps for InnoDB
    For InnoDB, recover using the following steps.
   sudo systemctl stop mysql
   sudo mysqld_safe --innodb_force_recovery=1 &

7. Frequently Asked Questions (FAQ)

When working with MySQL option settings in real operations, you may encounter various questions and issues. In this section, we summarize common questions and solutions in an FAQ format.

1. Questions About Configuration Files

Q1. I can’t find the MySQL configuration file (my.cnf). Where is it?
A. The configuration file location depends on your environment, but you can check it using the following command:

mysql --help | grep my.cnf

Common configuration file locations include:

  • Linux: /etc/my.cnf or /etc/mysql/my.cnf
  • Windows: %PROGRAMDATA%\MySQL\MySQL Server X.X\my.ini
  • macOS: /usr/local/etc/my.cnf

Q2. After editing the configuration file, the changes don’t apply. What should I do?
A. After editing the configuration file, you must restart the MySQL server. Use the following command:

sudo systemctl restart mysql

To confirm the applied settings, run:

mysqladmin variables

2. Questions About Security and Authentication

Q3. I’m getting a password authentication error. What should I do?
A. Password authentication errors can occur due to permission settings or differences in password formats. Check the following steps:

  1. Check user privileges
SELECT user, host FROM mysql.user;
  1. Reset the password
ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpassword';
FLUSH PRIVILEGES;
  1. In MySQL 8.0 and later, the authentication plugin changed to caching_sha2_password. If you are using an older client, compatibility issues may occur. 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 outside?
A. Add the following option in the configuration file to restrict external connections:

[mysqld]
bind-address=127.0.0.1

This blocks connections from anything other than localhost. If you want to disable network connections completely, set:

skip-networking

Restart after changing the setting.

sudo systemctl restart mysql

3. Questions About Performance

Q5. What settings help improve database performance?
A. Key settings for performance improvement include:

SettingRecommended ExampleDescription
innodb_buffer_pool_sizeinnodb_buffer_pool_size=1GSpeeds up query processing by increasing memory usage.
query_cache_sizequery_cache_size=0 (removed)Removed in MySQL 8.0; strengthen InnoDB instead.
thread_cache_sizethread_cache_size=16Improves connection efficiency by reusing threads.
tmp_table_sizetmp_table_size=64MIncreases the size limit for temporary tables.
max_connectionsmax_connections=200Improves load handling by increasing concurrent connections.

Q6. I want to identify slow queries and address them. How?
A. Enable the slow query log to identify 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 setting.
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 settings to defaults?
A. To reset settings, restore the configuration file to its default state or create a new configuration file. Here is an example procedure:

  1. Back up the current settings.
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 covered MySQL option settings comprehensively—from the basics to advanced use cases. We walked through configuration methods, specific options, troubleshooting, and other practical knowledge in a step-by-step way. Here, we’ll review the key points and reaffirm why MySQL option settings matter.

1. Key Takeaways

Basics

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

Practical Use

  • In the category-based explanation of commonly used options, we introduced example settings for connection management, performance tuning, and security hardening.
  • We explained how understanding precedence and precautions during conflicts helps prevent configuration mistakes and supports efficient operations.

Advanced Use

  • In environment-specific configuration examples and best practices, we provided concrete examples of optimal settings for development and production environments, as well as safe procedures for applying changes.
  • In troubleshooting and FAQ, we explained common operational issues and detailed solutions.

2. Why MySQL Option Settings Are Important

Performance Optimization

With proper option settings, you can use resources efficiently and improve query processing speed. In large databases and high-load environments, performance tuning directly impacts overall system efficiency.

Security Hardening

By correctly configuring things like external access restrictions and SSL, you can prevent unauthorized access and data leaks. Security settings tailored to your operational environment are essential.

Better Incident Response

Through log management and error message analysis, you can respond more quickly when issues occur. Proper configuration in advance helps prevent incidents before they happen.

3. Next Action Plan

Review and Optimize Your Settings

  • Review your current MySQL settings and optimize them using the best practices introduced in this article.

Use a Test Environment

  • Verify new settings and changes in a test environment before applying them to production to minimize risk.

Create Documentation and Records

  • Record configuration changes and troubleshooting procedures to support future operations and knowledge sharing within your team.

4. Final Notes

MySQL option settings play a critical role in database administration. The larger your system becomes, the more these settings and their management affect performance and security.

Use this article as a reference to configure settings that match your operational environment and build a stable system. By reviewing settings regularly and incorporating up-to-date best practices, you can achieve more robust and efficient database operations.