远程访问条件
mysql允许远程访问有两个必要条件
- 外部能访问到mysql开启的端口
- 用户有权限访问
配置
1、配置绑定地址
mysql配置绑定的地址是127.0.0.1,只允许本机连接。为使其他主机可以访问mysql服务,需要绑定非本地ip,或0.0.0.0即可。配置文件存在于/etc/mysql/mysql.conf.d/mysqld.cnf
,如果此文件没有相关的配置内容,可手动添加,或将以下内容复制过去即可。
#
# The MySQL database server configuration file.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
# Here is entries for some specific programs
# The following values assume you have at least 32M ram
[mysqld]
#
# * Basic Settings
#
user = mysql
# pid-file = /var/run/mysqld/mysqld.pid
# socket = /var/run/mysqld/mysqld.sock
# port = 3306
# datadir = /var/lib/mysql
# If MySQL is running as a replication slave, this should be
# changed. Ref https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_tmpdir
# tmpdir = /tmp
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 127.0.0.1
mysqlx-bind-address = 127.0.0.1
#
# * Fine Tuning
#
key_buffer_size = 16M
# max_allowed_packet = 64M
# thread_stack = 256K
# thread_cache_size = -1
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover-options = BACKUP
# max_connections = 151
# table_open_cache = 4000
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
#
# Log all queries
# Be aware that this log type is a performance killer.
# general_log_file = /var/log/mysql/query.log
# general_log = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
# slow_query_log = 1
# slow_query_log_file = /var/log/mysql/mysql-slow.log
# long_query_time = 2
# log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
# server-id = 1
# log_bin = /var/log/mysql/mysql-bin.log
# binlog_expire_logs_seconds = 2592000
max_binlog_size = 100M
# binlog_do_db = include_database_name
# binlog_ignore_db = include_database_name
2、授权用户
用户访问信息在mysql数据库的user中设定,可通过修改user表,来授权用户访问。
改表
- 修改已有用户的host字段
修改mysql的user表,host字段为指定ip即可。如果想任意主机都可以连接,可以使用%
update user set host = '%' where user = 'root';
- 新建远程连接用户
grant all on *.* to admin@'%' identified by '123456' with grant option;
授权
修改表后并不会生效,需要执行以下sql使用修改生效。
flush privileges;