Chapter 3 Postinstallation Setup and Testing

Table of Contents

3.1 Initializing the Data Directory
3.1.1 Initializing the Data Directory Manually Using mysqld
3.1.2 Initializing the Data Directory Manually Using mysql_install_db
3.1.3 Problems Running mysql_install_db
3.2 Starting the Server
3.2.1 Troubleshooting Problems Starting the MySQL Server
3.3 Testing the Server
3.4 Securing the Initial MySQL Accounts
3.5 Starting and Stopping MySQL Automatically

This section discusses tasks that you should perform after installing MySQL:

When you are ready to create additional user accounts, you can find information on the MySQL access control system and account management in Chapter 4, The MySQL Access Privilege System, and Chapter 5, MySQL User Account Management.

3.1 Initializing the Data Directory

After installing MySQL, you must initialize the data directory, including the tables in the mysql system database. For some MySQL installation methods, data directory initialization may be done automatically, as described in Chapter 3, Postinstallation Setup and Testing. For other installation methods, including installation from generic binary and source distributions, you must initialize the data directory yourself.

This section describes how to initialize the data directory on Unix and Unix-like systems. (For Windows, see Windows Postinstallation Procedures.) For some suggested commands that you can use to test whether the server is accessible and working properly, see Section 3.3, “Testing the Server”.

In the examples shown here, the server runs under the user ID of the mysql login account. This assumes that such an account exists. Either create the account if it does not exist, or substitute the name of a different existing login account that you plan to use for running the server. For information about creating the account, see Creating a mysql System User and Group, in Installing MySQL on Unix/Linux Using Generic Binaries.

  1. Change location into the top-level directory of your MySQL installation, represented here by BASEDIR:

    shell> cd BASEDIR
    

    BASEDIR is likely to be something like /usr/local/mysql or /usr/local. The following steps assume that you have changed location to this directory.

    You will find several files and subdirectories in the BASEDIR directory. The most important for installation purposes are the bin and scripts subdirectories, which contain the server as well as client and utility programs.

  2. Create a directory that provides a location to use as the value of the secure_file_priv system variable that limits import/export operations to a specific directory. See Server System Variables.

    shell> mkdir mysql-files
    shell> chmod 750 mysql-files
    
  3. If necessary, ensure that the distribution contents are accessible to mysql. If you installed the distribution as mysql, no further action is required. If you installed the distribution as root, its contents will be owned by root. Change its ownership to mysql by executing the following commands as root in the installation directory. The first command changes the owner attribute of the files to the mysql user. The second changes the group attribute to the mysql group.

    shell> chown -R mysql .
    shell> chgrp -R mysql .
    
  4. If necessary, initialize the data directory, including the mysql database containing the initial MySQL grant tables that determine how users are permitted to connect to the server.

    Typically, data directory initialization need be done only the first time you install MySQL. If you are upgrading an existing installation, you should run mysql_upgrade instead (see mysql_upgrade — Check and Upgrade MySQL Tables). However, the command that initializes the data directory does not overwrite any existing privilege tables, so it should be safe to run in any circumstances.

    As of MySQL 5.7.6, use the server to initialize the data directory:

    shell> bin/mysqld --initialize --user=mysql
    

    Before MySQL 5.7.6, use mysql_install_db:

    shell> bin/mysql_install_db --user=mysql
    

    For more information, see Section 3.1.1, “Initializing the Data Directory Manually Using mysqld”, or Section 3.1.2, “Initializing the Data Directory Manually Using mysql_install_db”, depending on which command you use.

  5. If you want the server to be able to deploy with automatic support for secure connections, use the mysql_ssl_rsa_setup utility to create default SSL and RSA files:

    shell> mysql_ssl_rsa_setup
    

    For more information, see mysql_ssl_rsa_setup — Create SSL/RSA Files.

  6. After initializing the data directory, you can establish the final installation ownership settings. To leave the installation owned by mysql, no action is required here. Otherwise, most of the MySQL installation can be owned by root if you like. The exception is that the data directory and the mysql-files directory must be owned by mysql. To accomplish this, run the following commands as root in the installation directory. For some distribution types, the data directory might be named var rather than data; adjust the second command accordingly.

    shell> chown -R root .
    shell> chown -R mysql data mysql-files
    

    If the plugin directory (the directory named by the plugin_dir system variable) is writable by the server, it may be possible for a user to write executable code to a file in the directory using SELECT ... INTO DUMPFILE. This can be prevented by making the plugin directory read only to the server or by setting the secure_file_priv system variable at server startup to a directory where SELECT writes can be performed safely. (For example, set it to the mysql-files directory created earlier.)

  7. To specify options that the MySQL server should use at startup, put them in a /etc/my.cnf or /etc/mysql/my.cnf file. You can use such a file, for example, to set the secure_file_priv system variable. See Server Configuration Defaults. If you do not do this, the server starts with its default settings.

  8. If you want MySQL to start automatically when you boot your machine, see Section 3.5, “Starting and Stopping MySQL Automatically”.

Data directory initialization creates time zone tables in the mysql database but does not populate them. To do so, use the instructions in MySQL Server Time Zone Support.

3.1.1 Initializing the Data Directory Manually Using mysqld

This section describes how to initialize the data directory using mysqld, the MySQL server.

Note

The procedure described here is available for all platforms as of MySQL 5.7.6. Prior to 5.7.6, use mysql_install_db on Unix and Unix-like systems (see Section 3.1.2, “Initializing the Data Directory Manually Using mysql_install_db”). Prior to MySQL 5.7.7, Windows distributions include a data directory with prebuilt tables in the mysql database.

The following instructions assume that your current location is the MySQL installation directory, represented here by BASEDIR:

shell> cd BASEDIR

To initialize the data directory, invoke mysqld with the --initialize or --initialize-insecure option, depending on whether you want the server to generate a random initial password for the 'root'@'localhost' account.

On Windows, use one of these commands:

C:\> bin\mysqld --initialize
C:\> bin\mysqld --initialize-insecure

On Unix and Unix-like systems, it is important to make sure that the database directories and files are owned by the mysql login account so that the server has read and write access to them when you run it later. To ensure this if you run mysqld as root, include the --user option as shown here:

shell> bin/mysqld --initialize --user=mysql
shell> bin/mysqld --initialize-insecure --user=mysql

Otherwise, execute the program while logged in as mysql, in which case you can omit the --user option from the command.

Regardless of platform, use --initialize for secure by default installation (that is, including generation of a random initial root password). In this case, the password is marked as expired and you will need to choose a new one. With the --initialize-insecure option, no root password is generated; it is assumed that you will assign a password to the account in timely fashion before putting the server into production use.

It might be necessary to specify other options such as --basedir or --datadir if mysqld does not identify the correct locations for the installation directory or data directory. For example (enter the command on one line):

shell> bin/mysqld --initialize --user=mysql
         --basedir=/opt/mysql/mysql
         --datadir=/opt/mysql/mysql/data

Alternatively, put the relevant option settings in an option file and pass the name of that file to mysqld. For Unix and Unix-like systems, suppose that the option file name is /opt/mysql/mysql/etc/my.cnf. Put these lines in the file:

[mysqld]
basedir=/opt/mysql/mysql
datadir=/opt/mysql/mysql/data

Then invoke mysqld as follows (enter the command on a single line with the --defaults-file option first):

shell> bin/mysqld --defaults-file=/opt/mysql/mysql/etc/my.cnf
         --initialize --user=mysql

On Windows, suppose that C:\my.ini contains these lines:

[mysqld]
basedir=C:\\Program Files\\MySQL\\MySQL Server 5.7
datadir=D:\\MySQLdata

Then invoke mysqld as follows (the --defaults-file option must be first):

C:\> bin/mysqld --defaults-file=C:\my.ini --initialize

When invoked with the --initialize or --initialize-insecure option, mysqld performs the following initialization sequence.

Note

The server writes any messages to its standard error output. This may be redirected to the error log, so look there if you do not see the messages on your screen. For information about the error log, including where it is located, see The Error Log.

On Windows, use the --console option to direct messages to the console.

  1. The server checks for the existence of the data directory as follows:

    • If no data directory exists, the server creates it.

    • If a data directory exists and is not empty (that is, it contains files or subdirectories), the server exits after producing an error message:

      [ERROR] --initialize specified but the data directory exists. Aborting.
      

      In this case, remove or rename the data directory and try again.

      As of MySQL 5.7.11, an existing data directory is permitted to be nonempty if every entry either has a name that begins with a period (.) or is named using an --ignore-db-dir option.

  2. Within the data directory, the server creates the mysql system database and its tables, including the grant tables, server-side help tables, and time zone tables. For a complete listing and description of the grant tables, see Chapter 4, The MySQL Access Privilege System.

  3. The server initializes the system tablespace and related data structures needed to manage InnoDB tables.

    Note

    After mysqld sets up the InnoDB system tablespace, changes to some tablespace characteristics require setting up a whole new instance. This includes the file name of the first file in the system tablespace and the number of undo logs. If you do not want to use the default values, make sure that the settings for the innodb_data_file_path and innodb_log_file_size configuration parameters are in place in the MySQL configuration file before running mysqld. Also make sure to specify as necessary other parameters that affect the creation and location of InnoDB files, such as innodb_data_home_dir and innodb_log_group_home_dir.

    If those options are in your configuration file but that file is not in a location that MySQL reads by default, specify the file location using the --defaults-extra-file option when you run mysqld.

  4. The server creates a 'root'@'localhost' superuser account. The server's action with respect to a password for this account depends on how you invoke it:

    • With --initialize but not --initialize-insecure, the server generates a random password, marks it as expired, and writes a message displaying the password:

      [Warning] A temporary password is generated for root@localhost:
      iTag*AfrH5ej
      
    • With --initialize-insecure, (either with or without --initialize because --initialize-insecure implies --initialize), the server does not generate a password or mark it expired, and writes a warning message:

      Warning] root@localhost is created with an empty password ! Please
      consider switching off the --initialize-insecure option.
      
  5. The server populates the server-side help tables if content is available (in the fill_help_tables.sql file). The server does not populate the time zone tables; to do so, see MySQL Server Time Zone Support.

  6. If the --init-file option was given to name a file of SQL statements, the server executes the statements in the file. This option enables you to perform custom bootstrapping sequences.

    When the server operates in bootstrap mode, some functionality is unavailable that limits the statements permitted in the file. These include statements that relate to account management (such as CREATE USER or GRANT), replication, and global transaction identifiers.

  7. The server exits.

After you initialize the data directory by starting the server with --initialize or --initialize-insecure, start the server normally (that is, without either of those options) and assign the 'root'@'localhost' account a new password:

  1. Start the server. For instructions, see Section 3.2, “Starting the Server”.

  2. Connect to the server:

    • If you used --initialize but not --initialize-insecure to initialize the data directory, connect to the server as root using the random password that the server generated during the initialization sequence:

      shell> mysql -u root -p
      Enter password: (enter the random root password here)
      

      Look in the server error log if you do not know this password.

    • If you used --initialize-insecure to initialize the data directory, connect to the server as root without a password:

      shell> mysql -u root --skip-password
      
  3. After connecting, assign a new root password:

    mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
    
Note

The data directory initialization sequence performed by the server does not substitute for the actions performed by mysql_secure_installation or mysql_ssl_rsa_setup. See mysql_secure_installation — Improve MySQL Installation Security, and mysql_ssl_rsa_setup — Create SSL/RSA Files.

3.1.2 Initializing the Data Directory Manually Using mysql_install_db

This section describes how to initialize the data directory using mysql_install_db.

Note

The procedure described here is used on Unix and Unix-like systems prior to MySQL 5.7.6. (For Windows, MySQL distributions include a data directory with prebuilt tables in the mysql database.) As of MySQL 5.7.6, mysql_install_db is deprecated. To initialize the data directory, use the procedure described at Section 3.1.1, “Initializing the Data Directory Manually Using mysqld”.

The following instructions assume that your current location is the MySQL installation directory, represented here by BASEDIR:

shell> cd BASEDIR

To initialize the data directory, invoke mysql_install_db. This program might be located under the base directory in either bin or scripts, depending on your version of MySQL. If it is in scripts, adjust the following commands appropriately.

shell> bin/mysql_install_db --user=mysql

It is important to make sure that the database directories and files are owned by the mysql login account so that the server has read and write access to them when you run it later. To ensure this if you run mysql_install_db as root, include the --user option as shown. Otherwise, execute the program while logged in as mysql, in which case you can omit the --user option from the command.

The mysql_install_db command creates the server's data directory. Under the data directory, it creates directories for the mysql database that holds the grant tables and (prior to MySQL 5.7.4) a test database that you can use to test MySQL. The program also creates privilege table entries for the initial account or accounts. For a complete listing and description of the grant tables, see Chapter 4, The MySQL Access Privilege System.

It might be necessary to specify other options such as --basedir or --datadir if mysql_install_db does not identify the correct locations for the installation directory or data directory. For example:

shell> bin/mysql_install_db --user=mysql \
         --basedir=/opt/mysql/mysql \
         --datadir=/opt/mysql/mysql/data

If mysql_install_db generates a random password for the root account, start the server and assign a new password:

  1. Start the server (use the first command if your installation includes mysqld_safe, the second it if includes systemd support):

    shell> bin/mysqld_safe --user=mysql &
    shell> systemctl start mysqld
    

    Substitute the appropriate service name if it differs from mysqld; for example, mysql on SLES systems.

  2. Look in the $HOME/.mysql_secret file to find the random password that mysql_install_db wrote there. Then connect to the server as root using that password:

    shell> mysql -u root -h 127.0.0.1 -p
    Enter password: (enter the random password here)
    
  3. After connecting, assign a new root password:

    mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
    

    After resetting the password, remove the .mysql_secret file; otherwise, if you run mysql_secure_installation, that command may see the file and expire the root password again as part of ensuring secure deployment.

If mysql_install_db did not generate a random password, you should still assign one. For instructions, see Section 3.4, “Securing the Initial MySQL Accounts”. That section also describes how to remove the test database, if mysql_install_db created one and you do not want it.

If you have trouble with mysql_install_db at this point, see Section 3.1.3, “Problems Running mysql_install_db”.

3.1.3 Problems Running mysql_install_db

The purpose of the mysql_install_db program is to initialize the data directory, including the tables in the mysql system database. It does not overwrite existing MySQL privilege tables, and it does not affect any other data.

To re-create your privilege tables, first stop the mysqld server if it is running. Then rename the mysql directory under the data directory to save it, and run mysql_install_db. Suppose that your current directory is the MySQL installation directory and that mysql_install_db is located in the bin directory and the data directory is named data. To rename the mysql database and re-run mysql_install_db, use these commands.

shell> mv data/mysql data/mysql.old
shell> bin/mysql_install_db --user=mysql

When you run mysql_install_db, you might encounter the following problems:

  • mysql_install_db fails to install the grant tables

    You may find that mysql_install_db fails to install the grant tables and terminates after displaying the following messages:

    Starting mysqld daemon with databases from XXXXXX
    mysqld ended
    

    In this case, you should examine the error log file very carefully. The log should be located in the directory XXXXXX named by the error message and should indicate why mysqld did not start. If you do not understand what happened, include the log when you post a bug report. See How to Report Bugs or Problems.

  • There is a mysqld process running

    This indicates that the server is running, in which case the grant tables have probably been created already. If so, there is no need to run mysql_install_db at all because it needs to be run only once, when you first install MySQL.

  • Installing a second mysqld server does not work when one server is running

    This can happen when you have an existing MySQL installation, but want to put a new installation in a different location. For example, you might have a production installation, but you want to create a second installation for testing purposes. Generally the problem that occurs when you try to run a second server is that it tries to use a network interface that is in use by the first server. In this case, you should see one of the following error messages:

    Can't start server: Bind on TCP/IP port:
    Address already in use
    Can't start server: Bind on unix socket...
    

    For instructions on setting up multiple servers, see Running Multiple MySQL Instances on One Machine.

  • You do not have write access to the /tmp directory

    If you do not have write access to create temporary files or a Unix socket file in the default location (the /tmp directory) or the TMPDIR environment variable, if it has been set, an error occurs when you run mysql_install_db or the mysqld server.

    You can specify different locations for the temporary directory and Unix socket file by executing these commands prior to starting mysql_install_db or mysqld, where some_tmp_dir is the full path name to some directory for which you have write permission:

    shell> TMPDIR=/some_tmp_dir/
    shell> MYSQL_UNIX_PORT=/some_tmp_dir/mysql.sock
    shell> export TMPDIR MYSQL_UNIX_PORT
    

    Then you should be able to run mysql_install_db and start the server with these commands:

    shell> bin/mysql_install_db --user=mysql
    shell> bin/mysqld_safe --user=mysql &
    

    See How to Protect or Change the MySQL Unix Socket File, and Environment Variables.

There are some alternatives to running the mysql_install_db program provided in the MySQL distribution:

  • If you want the initial privileges to be different from the standard defaults, use account-management statements such as CREATE USER, GRANT, and REVOKE to change the privileges after the grant tables have been set up. In other words, run mysql_install_db, and then use mysql -u root mysql to connect to the server as the MySQL root user so that you can issue the necessary statements. (See Account Management Statements.)

    To install MySQL on several machines with the same privileges, put the CREATE USER, GRANT, and REVOKE statements in a file and execute the file as a script using mysql after running mysql_install_db. For example:

    shell> bin/mysql_install_db --user=mysql
    shell> bin/mysql -u root < your_script_file
    

    This enables you to avoid issuing the statements manually on each machine.

  • It is possible to re-create the grant tables completely after they have previously been created. You might want to do this if you are just learning how to use CREATE USER, GRANT, and REVOKE and have made so many modifications after running mysql_install_db that you want to wipe out the tables and start over.

    To re-create the grant tables, stop the server if it is running and remove the mysql database directory. Then run mysql_install_db again.

3.2 Starting the Server

This section describes how start the server on Unix and Unix-like systems. (For Windows, see Starting the Server for the First Time.) For some suggested commands that you can use to test whether the server is accessible and working properly, see Section 3.3, “Testing the Server”.

Start the MySQL server like this if your installation includes mysqld_safe:

shell> bin/mysqld_safe --user=mysql &

Start the server like this if your installation includes systemd support:

shell> systemctl start mysqld

Substitute the appropriate service name if it differs from mysqld; for example, mysql on SLES systems.

It is important that the MySQL server be run using an unprivileged (non-root) login account. To ensure this if you run mysqld_safe as root, include the --user option as shown. Otherwise, you should execute the program while logged in as mysql, in which case you can omit the --user option from the command.

For further instructions for running MySQL as an unprivileged user, see Section 2.5, “How to Run MySQL as a Normal User”.

If the command fails immediately and prints mysqld ended, look for information in the error log (which by default is the host_name.err file in the data directory).

If the server is unable to access the data directory it starts or read the grant tables in the mysql database, it writes a message to its error log. Such problems can occur if you neglected to create the grant tables by initializing the data directory before proceeding to this step, or if you ran the command that initializes the data directory without the --user option. Remove the data directory and run the command with the --user option.

If you have other problems starting the server, see Section 3.2.1, “Troubleshooting Problems Starting the MySQL Server”. For more information about mysqld_safe, see mysqld_safe — MySQL Server Startup Script. For more information about systemd support, see Managing MySQL Server with systemd.

3.2.1 Troubleshooting Problems Starting the MySQL Server

This section provides troubleshooting suggestions for problems starting the server. For additional suggestions for Windows systems, see Troubleshooting a Microsoft Windows MySQL Server Installation.

If you have problems starting the server, here are some things to try:

  • Check the error log to see why the server does not start. Log files are located in the data directory (typically C:\Program Files\MySQL\MySQL Server 5.7\data on Windows, /usr/local/mysql/data for a Unix/Linux binary distribution, and /usr/local/var for a Unix/Linux source distribution). Look in the data directory for files with names of the form host_name.err and host_name.log, where host_name is the name of your server host. Then examine the last few lines of these files. Use tail to display them:

    shell> tail host_name.err
    shell> tail host_name.log
    
  • Specify any special options needed by the storage engines you are using. You can create a my.cnf file and specify startup options for the engines that you plan to use. If you are going to use storage engines that support transactional tables (InnoDB, NDB), be sure that you have them configured the way you want before starting the server. If you are using InnoDB tables, see InnoDB Configuration for guidelines and InnoDB Startup Options and System Variables for option syntax.

    Although storage engines use default values for options that you omit, Oracle recommends that you review the available options and specify explicit values for any options whose defaults are not appropriate for your installation.

  • Make sure that the server knows where to find the data directory. The mysqld server uses this directory as its current directory. This is where it expects to find databases and where it expects to write log files. The server also writes the pid (process ID) file in the data directory.

    The default data directory location is hardcoded when the server is compiled. To determine what the default path settings are, invoke mysqld with the --verbose and --help options. If the data directory is located somewhere else on your system, specify that location with the --datadir option to mysqld or mysqld_safe, on the command line or in an option file. Otherwise, the server will not work properly. As an alternative to the --datadir option, you can specify mysqld the location of the base directory under which MySQL is installed with the --basedir, and mysqld looks for the data directory there.

    To check the effect of specifying path options, invoke mysqld with those options followed by the --verbose and --help options. For example, if you change location into the directory where mysqld is installed and then run the following command, it shows the effect of starting the server with a base directory of /usr/local:

    shell> ./mysqld --basedir=/usr/local --verbose --help
    

    You can specify other options such as --datadir as well, but --verbose and --help must be the last options.

    Once you determine the path settings you want, start the server without --verbose and --help.

    If mysqld is currently running, you can find out what path settings it is using by executing this command:

    shell> mysqladmin variables
    

    Or:

    shell> mysqladmin -h host_name variables
    

    host_name is the name of the MySQL server host.

  • Make sure that the server can access the data directory. The ownership and permissions of the data directory and its contents must allow the server to read and modify them.

    If you get Errcode 13 (which means Permission denied) when starting mysqld, this means that the privileges of the data directory or its contents do not permit server access. In this case, you change the permissions for the involved files and directories so that the server has the right to use them. You can also start the server as root, but this raises security issues and should be avoided.

    Change location into the data directory and check the ownership of the data directory and its contents to make sure the server has access. For example, if the data directory is /usr/local/mysql/var, use this command:

    shell> ls -la /usr/local/mysql/var
    

    If the data directory or its files or subdirectories are not owned by the login account that you use for running the server, change their ownership to that account. If the account is named mysql, use these commands:

    shell> chown -R mysql /usr/local/mysql/var
    shell> chgrp -R mysql /usr/local/mysql/var
    

    Even with correct ownership, MySQL might fail to start up if there is other security software running on your system that manages application access to various parts of the file system. In this case, reconfigure that software to enable mysqld to access the directories it uses during normal operation.

  • Verify that the network interfaces the server wants to use are available.

    If either of the following errors occur, it means that some other program (perhaps another mysqld server) is using the TCP/IP port or Unix socket file that mysqld is trying to use:

    Can't start server: Bind on TCP/IP port: Address already in use
    Can't start server: Bind on unix socket...
    

    Use ps to determine whether you have another mysqld server running. If so, shut down the server before starting mysqld again. (If another server is running, and you really want to run multiple servers, you can find information about how to do so in Running Multiple MySQL Instances on One Machine.)

    If no other server is running, execute the command telnet your_host_name tcp_ip_port_number. (The default MySQL port number is 3306.) Then press Enter a couple of times. If you do not get an error message like telnet: Unable to connect to remote host: Connection refused, some other program is using the TCP/IP port that mysqld is trying to use. Track down what program this is and disable it, or tell mysqld to listen to a different port with the --port option. In this case, specify the same non-default port number for client programs when connecting to the server using TCP/IP.

    Another reason the port might be inaccessible is that you have a firewall running that blocks connections to it. If so, modify the firewall settings to permit access to the port.

    If the server starts but you cannot connect to it, make sure that you have an entry in /etc/hosts that looks like this:

    127.0.0.1       localhost
    
  • If you cannot get mysqld to start, try to make a trace file to find the problem by using the --debug option. See The DBUG Package.

3.3 Testing the Server

After the data directory is initialized and you have started the server, perform some simple tests to make sure that it works satisfactorily. This section assumes that your current location is the MySQL installation directory and that it has a bin subdirectory containing the MySQL programs used here. If that is not true, adjust the command path names accordingly.

Alternatively, add the bin directory to your PATH environment variable setting. That enables your shell (command interpreter) to find MySQL programs properly, so that you can run a program by typing only its name, not its path name. See Setting Environment Variables.

Use mysqladmin to verify that the server is running. The following commands provide simple tests to check whether the server is up and responding to connections:

shell> bin/mysqladmin version
shell> bin/mysqladmin variables

If you cannot connect to the server, specify a -u root option to connect as root. If you have assigned a password for the root account already, you'll also need to specify -p on the command line and enter the password when prompted. For example:

shell> bin/mysqladmin -u root -p version
Enter password: (enter root password here)

The output from mysqladmin version varies slightly depending on your platform and version of MySQL, but should be similar to that shown here:

shell> bin/mysqladmin version
mysqladmin  Ver 14.12 Distrib 5.7.14, for pc-linux-gnu on i686
...
Server version          5.7.14
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 14 days 5 hours 5 min 21 sec
Threads: 1  Questions: 366  Slow queries: 0
Opens: 0  Flush tables: 1  Open tables: 19
Queries per second avg: 0.000

To see what else you can do with mysqladmin, invoke it with the --help option.

Verify that you can shut down the server (include a -p option if the root account has a password already):

shell> bin/mysqladmin -u root shutdown

Verify that you can start the server again. Do this by using mysqld_safe or by invoking mysqld directly. For example:

shell> bin/mysqld_safe --user=mysql &

If mysqld_safe fails, see Section 3.2.1, “Troubleshooting Problems Starting the MySQL Server”.

Run some simple tests to verify that you can retrieve information from the server. The output should be similar to that shown here.

Use mysqlshow to see what databases exist:

shell> bin/mysqlshow
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

The list of installed databases may vary, but will always include the minimum of mysql and information_schema.

If you specify a database name, mysqlshow displays a list of the tables within the database:

shell> bin/mysqlshow mysql
Database: mysql
+---------------------------+
|          Tables           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
| general_log               |
| gtid_executed             |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| server_cost               |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+

Use the mysql program to select information from a table in the mysql database:

shell> bin/mysql -e "SELECT User, Host, plugin FROM mysql.user" mysql
+------+-----------+-----------------------+
| User | Host      | plugin                |
+------+-----------+-----------------------+
| root | localhost | mysql_native_password |
+------+-----------+-----------------------+

At this point, your server is running and you can access it. To tighten security if you have not yet assigned a password to the initial account, follow the instructions in Section 3.4, “Securing the Initial MySQL Accounts”.

For more information about mysql, mysqladmin, and mysqlshow, see mysql — The MySQL Command-Line Tool, mysqladmin — Client for Administering a MySQL Server, and mysqlshow — Display Database, Table, and Column Information.

3.4 Securing the Initial MySQL Accounts

The MySQL installation process involves initializing the data directory, including the mysql database containing the grant tables that define MySQL accounts. For details, see Chapter 3, Postinstallation Setup and Testing.

This section describes how to assign passwords to the initial accounts created during the MySQL installation procedure, if you have not already done so.

Note

On Windows, you can also perform the process described in this section during installation with MySQL Installer (see Installing MySQL on Microsoft Windows Using MySQL Installer). On all platforms, the MySQL distribution includes mysql_secure_installation, a command-line utility that automates much of the process of securing a MySQL installation. MySQL Workbench is available on all platforms, and also offers the ability to manage user accounts (see MySQL Workbench ).

Passwords may have already been assigned under these circumstances:

The mysql.user grant table defines the initial MySQL user accounts and their access privileges. Current versions of MySQL 5.7 create only a 'root'@'localhost' account, but for earlier versions, there might be multiple accounts such as described here:

  • Some accounts have the user name root. These are superuser accounts that have all privileges and can do anything. If these root accounts have empty passwords, anyone can connect to the MySQL server as root without a password and be granted all privileges.

    • On Windows, root accounts are created that permit connections from the local host only. Connections can be made by specifying the host name localhost, the IP address 127.0.0.1, or the IPv6 address ::1. If the user selects the Enable root access from remote machines option during installation, the Windows installer creates another root account that permits connections from any host.

    • On Unix, each root account permits connections from the local host. Connections can be made by specifying the host name localhost, the IP address 127.0.0.1, the IPv6 address ::1, or the actual host name or IP address.

    • The 'root'@'localhost' account also has a row in the mysql.proxies_priv table that enables granting the PROXY privilege for ''@'', that is, for all users and all hosts. This enables root to set up proxy users, as well as to delegate to other accounts the authority to set up proxy users. See Section 5.9, “Proxy Users”.

  • If accounts for anonymous users were created, these have an empty user name. The anonymous accounts have no password, so anyone can use them to connect to the MySQL server.

    • On Windows, there is one anonymous account that permits connections from the local host. Connections can be made by specifying a host name of localhost.

    • On Unix, each anonymous account permits connections from the local host. Connections can be made by specifying a host name of localhost for one of the accounts, or the actual host name or IP address for the other.

Checking Which Accounts Exist

Start the server if it is not running. For instructions, see Section 3.2, “Starting the Server”.

Assuming that no root password has been assigned, you should be able to connect to the server as root without one:

shell> mysql -u root

Once connected, determine which accounts exist in the mysql.user table and whether their passwords are empty:

  • As of MySQL 5.7.6, use this statement:

    mysql> SELECT User, Host, HEX(authentication_string) FROM mysql.user;
    

    The statement uses HEX() because passwords stored in the authentication_string column might contain binary data that does not display well.

  • Before MySQL 5.7.6, use this statement:

    mysql> SELECT User, Host, Password FROM mysql.user;
    

The SELECT statement results can vary depending on your version of MySQL and installation method. The following example output includes several root and anonymous-user accounts, none of which have passwords:

+------+--------------------+----------+
| User | Host               | Password |
+------+--------------------+----------+
| root | localhost          |          |
| root | myhost.example.com |          |
| root | 127.0.0.1          |          |
| root | ::1                |          |
|      | localhost          |          |
|      | myhost.example.com |          |
+------+--------------------+----------+

If the output on your system shows any accounts with empty passwords, your MySQL installation is unprotected until you do something about it:

  • Assign a password to each MySQL root account that does not have one.

  • To prevent clients from connecting as anonymous users without a password, either assign a password to each anonymous account or remove the accounts.

In addition, some installation methods create a test database and add rows to the mysql.db table that permit all accounts to access that database and other databases with names that start with test_. This is true even for accounts that otherwise have no special privileges such as the default anonymous accounts. This is convenient for testing but inadvisable on production servers. Administrators who want database access restricted only to accounts that have permissions granted explicitly for that purpose should remove these mysql.db table rows.

The following instructions describe how to set up passwords for the initial MySQL accounts, first for any root accounts, then for anonymous accounts. The instructions also cover how to remove anonymous accounts, should you prefer not to permit anonymous access at all, and describe how to remove permissive access to test databases.

Replace new_password in the examples with the password that you want to use. Replace host_name with the name of the server host. You can determine this name from the output of the SELECT statement shown earlier. For the output shown, host_name is myhost.example.com.

Note

For additional information about setting passwords, see Section 5.5, “Assigning Account Passwords”. If you forget your root password after setting it, see How to Reset the Root Password.

To set up additional accounts, see Section 5.2, “Adding User Accounts”.

You might want to defer setting the passwords until later, to avoid the need to specify them while you perform additional setup or testing. However, be sure to set them before using your installation for production purposes.

Assigning root Account Passwords

To assign a password to an account, connect to the server as root using the mysql client and issue the appropriate SQL statement:

  • As of MySQL 5.7.6, use ALTER USER:

    mysql> ALTER USER user IDENTIFIED BY 'new_password';
    
  • Before 5.7.6, use SET PASSWORD:

    mysql> SET PASSWORD FOR user = PASSWORD('new_password');
    

The following instructions use ALTER USER. If your version of MySQL is older than 5.7.6, substitute equivalent SET PASSWORD statements.

To assign the 'root'@'localhost' account a password, connect to the server as root:

shell> mysql -u root

Then issue an ALTER USER statement:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Issue a similar ALTER USER statement for any other root account present in your mysql.user table that has no password. (Vary the host name appropriately.)

After an account has been assigned a password, you must supply that password whenever you connect to the server using the account. For example, to shut down the server with mysqladmin, use this command:

shell> mysqladmin -u root -p shutdown
Enter password: (enter root password here)

The mysql commands in the following instructions include a -p option based on the assumption that you have assigned the root account password using the preceding instructions and must specify that password when connecting to the server.

Assigning Anonymous Account Passwords

In MySQL 5.7, installation methods that create anonymous accounts tend to be for early versions for which ALTER USER cannot be used to assign passwords. Consequently, the instructions in this section use SET PASSWORD.

To assign the ''@'localhost' anonymous account a password, connect to the server as root:

shell> mysql -u root -p
Enter password: (enter root password here)

Then issue a SET PASSWORD statement:

mysql> SET PASSWORD FOR ''@'localhost' = PASSWORD('new_password');

Issue a similar SET PASSWORD statement for any other anonymous account present in your mysql.user table that has no password. (Vary the host name appropriately.)

Removing Anonymous Accounts

If you prefer to remove any anonymous accounts rather than assigning them passwords, use DROP USER. To drop the ''@'localhost' account, connect to the server as root:

shell> mysql -u root -p
Enter password: (enter root password here)

Then issue a DROP USER statement:

mysql> DROP USER ''@'localhost';

Issue a similar DROP USER statement for any other anonymous account that you want to drop. (Vary the host name appropriately.)

Securing Test Databases

Some installation methods create a test database and set up privileges for accessing it. If that is true on your system, the mysql.db table will contain rows that permit access by any user to the test database and other databases with names that start with test_. (These rows have an empty User column value, which for access-checking purposes matches any user name.) This means that such databases can be used even by accounts that otherwise possess no privileges. If you want to remove any-user access to test databases, do so as follows:

shell> mysql -u root -p
Enter password: (enter root password here)
mysql> DELETE FROM mysql.db WHERE Db LIKE 'test%';
mysql> FLUSH PRIVILEGES;

The FLUSH statement causes the server to reread the grant tables. Without it, the privilege change remains unnoticed by the server until you restart it.

With the preceding change, only users who have global database privileges or privileges granted explicitly for the test database can use it. However, if you prefer that the database not exist at all, drop it:

mysql> DROP DATABASE test;

3.5 Starting and Stopping MySQL Automatically

This section discusses methods for starting and stopping the MySQL server.

Generally, you start the mysqld server in one of these ways:

  • Invoke mysqld directly. This works on any platform.

  • On Windows, you can set up a MySQL service that runs automatically when Windows starts. See Starting MySQL as a Windows Service.

  • On Unix and Unix-like systems, you can invoke mysqld_safe, which tries to determine the proper options for mysqld and then runs it with those options. See mysqld_safe — MySQL Server Startup Script.

  • On Linux systems that support systemd, you can use it to control the server. See Managing MySQL Server with systemd.

  • On systems that use System V-style run directories (that is, /etc/init.d and run-level specific directories), invoke mysql.server. This script is used primarily at system startup and shutdown. It usually is installed under the name mysql. The mysql.server script starts the server by invoking mysqld_safe. See mysql.server — MySQL Server Startup Script.

  • On OS X, install a launchd daemon to enable automatic MySQL startup at system startup. The daemon starts the server by invoking mysqld_safe. For details, see Installing a MySQL Launch Daemon. A MySQL Preference Pane also provides control for starting and stopping MySQL through the System Preferences. See Installing and Using the MySQL Preference Pane.

  • On Solaris/OpenSolaris, use the service management framework (SMF) system to initiate and control MySQL startup. For more information, see Installing MySQL on OpenSolaris Using IPS.

systemd, the mysqld_safe and mysql.server scripts, Solaris/OpenSolaris SMF, and the OS X Startup Item (or MySQL Preference Pane) can be used to start the server manually, or automatically at system startup time. systemd, mysql.server, and the Startup Item also can be used to stop the server.

The following table shows which option groups the server and startup scripts read from option files.

Table 3.1 MySQL Startup Scripts and Supported Server Option Groups

ScriptOption Groups
mysqld[mysqld], [server], [mysqld-major_version]
mysqld_safe[mysqld], [server], [mysqld_safe]
mysql.server[mysqld], [mysql.server], [server]

[mysqld-major_version] means that groups with names like [mysqld-5.6] and [mysqld-5.7] are read by servers having versions 5.6.x, 5.7.x, and so forth. This feature can be used to specify options that can be read only by servers within a given release series.

For backward compatibility, mysql.server also reads the [mysql_server] group and mysqld_safe also reads the [safe_mysqld] group. To be current, you should update your option files to use the [mysql.server] and [mysqld_safe] groups instead.

For more information on MySQL configuration files and their structure and contents, see Using Option Files.