原创

Ubuntu18.04 安装并配置MySQL


一、安装MySQL

在Ubuntu中,默认情况下,只有最新版本的MySQL包含在APT软件包存储库中,要安装它,只需更新服务器上的包索引并安装默认包apt-get。

sudo apt-get update    #更新包索引
sudo apt-get install mysql-server    #安装MySQL

mysql1.png

二、配置MySQL

(一)初始化配置

sudo mysql_secure_installation

配置项较多,如下所示:

# 1
VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

Press y|Y for Yes, any other key for No: N(是否设置验证密码组件,设置后能提高安全性)

# 2
Please set the password for root here.
New password: (设置密码)
Re-enter new password: (再次输入密码)

# 3
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y(移除匿名用户)
Success.

# 4
Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : N(禁止root用户远程登录)

 ... skipping.
 
 # 5
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : N(移除MySQL中的测试数据库)

 ... skipping.
 
 # 6
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y(重新加载设置)
Success.

All done!

如果执行命令出现以下错误:

Enter password for user root: 
Error: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

可以使用reboot命令重启服务器,再次运行就可以了。

(二)检查MySQL服务状态

使用以下命令:

systemctl status mysql.service

如果显示以下结果说明MySQL服务是正常的:
mysql2.png

(三)配置远程访问

在Ubuntu下MySQL缺省是只允许本地访问的,使用Workbench和Navicat等连接工具是连不上的,如果你要其他机器也能够访问的话,需要进行配置。 参见解决MySQL数据库无法远程连接问题mysql3.png 先使用以下命令登录MySQL:

sudo mysql -uroot -p

然后依次运行以下代码:

mysql> create user 'root'@'%' identified by  '431241wjw';
Query OK, 0 rows affected (0.15 sec)

mysql> grant all privileges on *.* to 'root'@'%' with grant option;
Query OK, 0 rows affected (0.11 sec)

mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '431241wjw';
Query OK, 0 rows affected (0.01 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)

三、连接数据库

可以使用Workbench、Navicat等工具远程连接。
mysql4.png

MySQL
环境配置
  • 作者:Daozhi(联系作者)
  • 发表时间:2020-02-13 23:41
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论