Ubuntu18.04 LTS server 安装mysql 5.7 并开启远程连接
安装mysql
SSH登录服务器,执行如下命令安装:
sudo apt-get install mysql-server
测试是否安装成功:
sudo netstat -tap | grep mysql
修改mysql配置文件允许远程连接:
# 注意:不同 mysql 版本此配置文件位置和名字可能不同 sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf # mysql 5.7.23 # 找到将bind-address = 127.0.0.1注销 #bind-address = 127.0.0.1
修改后重启mysql服务器
sudo /etc/init.d/mysql restart
登录mysql
mysql -uroot -p ## mysql>命令 begin grant all privileges on *.* to 'root'@'%' identified by 'password'; flush privileges; ## end exit
- 第一个*是数据库,可以改成允许访问的数据库名称
- 第二个* 是数据库的表名称,*代表允许访问任意的表
- root代表远程登录使用的用户名,可以自定义
- %代表允许任意ip登录,如果你想指定特定的IP,可以把%替换掉就可以了
- password代表远程登录时使用的密码,可以自定义
mysql> select host,user from user; +-----------+------------------+ | host | user | +-----------+------------------+ | % | root | | localhost | debian-sys-maint | | localhost | mysql.session | | localhost | mysql.sys | +-----------+------------------+ 4 rows in set (0.00 sec)
如上,root 用户名的host 变成 % 就可以了。
PS:有时用这种方式会出现两个 root 用户,另一个host还是localhost
mysql> select host,user from user;
+-----------+------------------+
| host | user |
+-----------+------------------+
| % | root |
| localhost | debian-sys-maint |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------------+
5 rows in set (0.00 sec)
这时可以使用删除语句把这个本地连接用户删除。
mysql> use mysql Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed
mysql> delete from user where user='root' and host='localhost';
Query OK, 1 row affected (0.00 sec)
mysql> select host,user from user;
+-----------+------------------+
| host | user |
+-----------+------------------+
| % | root |
| localhost | debian-sys-maint |
| localhost | mysql.session |
| localhost | mysql.sys |
+-----------+------------------+
4 rows in set (0.00 sec)
检查mysql服务器占用端口
netstat -nlt|grep 3306 tcp6 0 0 :::3306 :::* LISTEN
网络监听从 127.0.0.1:3306 变成 0 ::::3306,表示MySQL已经允许远程登陆访问。
在本地远程连接:
mysql -h 服务器ip地址 -P 3306 -u root -p