ubutu18.04设置iptables使mysql的3306端口能够被外网访问


在远程主机或这虚拟机中安装好mysql想远程访问的时候发现无法连接mysql的3306端口,在本机上可以流畅访问。经过一番摸索发现是ubuntu的iptables限制,在早期的版本中没有防火墙限制。可以手动添加防火墙规则允许远程访问即可。

查看iptables规则并查看

$ sudo iptables -L -n --line-number

Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
2 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
3 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
4 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
5 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:443
6 DROP tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306
7 ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 icmptype 8

Chain FORWARD (policy ACCEPT)
num target prot opt source destination

Chain OUTPUT (policy ACCEPT)
num target prot opt source destination

删除阻止3306访问的规则

$ sudo iptables -D INPUT 6

添加允许3306访问的规则

$ sudo iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT

查看规则是否生效

$ sudo iptables -L -n --line-number

Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
2 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
3 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
4 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
5 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:443
6 ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 icmptype 8
7 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:3306

Chain FORWARD (policy ACCEPT)
num target prot opt source destination

Chain OUTPUT (policy ACCEPT)
num target prot opt source destination

配置完成后保存。这时候需要root权限,必须是以root用户登录的,sudo是不行的。可以参考ubuntu下作为root登录。

$ iptables-save > /etc/iptables/rules.v4
$ ip6tables-save > /etc/iptables/rules.v6

重启后系统会自动加载上面两个文件的配置,无需再做额外的操作。

也可以像下面一样操作

$ iptables-save > /etc/iptables-rules
$ ip6tables-save > /etc/ip6tables-rules

最后,我们需要编辑/etc/network/interfaces文件,在最后插入下面两行:

pre-up iptables-restore < /etc/iptables-rules
pre-up ip6tables-restore < /etc/ip6tables-rules

重启计算机以后,我们可以使用sudo iptables -L看到配置已经生效了。

Archives