在Ubuntu下安装MySQL

MySQL是一个开放源代码的关系数据库管理系统,性能高、成本低、可靠性好,已经成为最流行的开源数据库。

安装MySQL

sudo apt-get install mysql-server mysql-client

安装过程中会要求输入root用户的密码,记下自己输入的密码即可

安装完后检测是否安装成功,使用root用户和刚刚输入的密码连接到mysql

mysql -uroot -p刚刚输入的密码

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.22-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

出现上述代表mysql安装成功

更改默认端口

mysql默认的端口是3306,一般情况下我们会更改默认端口,当你数据库暴露在外网时可以一定程度上防止攻击

编辑如下目录mysql的配置文件:

sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf

# * Basic Settings
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 7777   #修改自己需要的端口
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking

这里演示把默认端口修改为7777,保存修改,重启mysql即可

sudo mysql service restart

重启之后,查询端口来验证是否修改成功

netstat -nlt|grep 7777

tcp        0      0 0.0.0.0:7777            0.0.0.0:*               LISTEN

授权可以访问的客户端

默认情况下,mysql只允许本地操作,如果我们的mysql安装在服务器上,避免不了远程连接,为了方便,这里我允许所有ip远程操作mysql

首先登录到mysql,授权root用户可以从任意ip获得所有特权

mysql -uroot -p你的密码

grant all privileges on *.* to 'root'@'%' identified by '你的密码';
flush privileges;
exit;

ps:为了安全,你可以指定ip和操作权限

然后,更改mysql配置文件允许从任意ip连接

sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf

#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            = 0.0.0.0  #把127.0.0.1修改为0.0.0.0即可

sudo service mysql restart

127.0.0.1修改为0.0.0.0即可,然后保存修改,重启mysql生效

返回目录

Reference

  • http://www.jianshu.com/p/3111290b87f4