通过iptables或ssh本地转发实现外网访问TDSQL云数据库
腾讯云有些TDSQL,如pgsql版的不能通过外网访问。此时提供3种方案,一种是iptables, 一种是ssh本地转发,最后是nginx转发。这看起来都需要额外的服务器成本,没办法。
假设:
服务器10.0.0.100
云数据库10.0.0.200:5432
iptables转发
1 购买和云数据库同子网,且配置安全组和云数据库相同的服务器和eip(按流量计费),最便宜的配置就行了,安全组放行5432端口。
2 在服务器添加iptables规则:
iptables -t nat -A PREROUTING -d 10.0.0.100 -p tcp --dport 5432 -j DNAT --to-destination 10.0.0.200:5432
iptables -t nat -A POSTROUTING -d 10.0.0.200 -p tcp --dport 5432 -j SNAT --to-source 10.0.0.100
3 ip转发打开
sed -i 's#net.ipv4.ip_forward = 0#net.ipv4.ip_forward = 1#g' /etc/sysctl.conf
sysctl -p
4 查看iptables,会发现dnat和snat都加了规则
iptables -t nat -vnL
5 测试OK
ssh转发
前提也是需要一台云服务器。
1 开启允许转发的功能
vim /etc/ssh/sshd_config
AllowTcpForwarding yes
# 重启ssh服务
systemctl restart sshd
2 设置转发
语法:
ssh -L localport:remotehost:remotehostport sshserver
说明:
localport 本机开启的端口号
remotehost 最终连接机器的IP地址
remotehostport 最终连接机器的端口号
sshserver 转发机器的IP地址
选项:
-f 后台启用
-N 不打开远程shell,处于等待状态(不加-N则直接登录进去)
-g 启用网关功能
ssh -g -L 6543:10.0.0.200:5432 10.0.0.100 -fN
此时将会监听6543端口,连接该端口就能转发到云数据库的5432端口了(记得安全组放行6543):
[root@VM-100-12-centos ~]# ss -tnl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:6543 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 128 [::]:6543 [::]:*
那就能连接过去啦。如果不想要监听了,ps -ef |grep ssh,干掉进程就好了
[root@VM-100-12-centos ~]# ps -ef |grep ssh
root 17026 1 0 18:12 ? 00:00:00 sshd: root@pts/0
root 17204 1 0 18:13 ? 00:00:00 /usr/sbin/sshd -D
root 19362 17204 0 18:28 ? 00:00:00 sshd: root
root 19371 1 0 18:29 ? 00:00:00 ssh -g -L 6543:10.0.0.200:5432 10.0.0.100 -fN
root 20639 17033 0 18:38 pts/0 00:00:00 grep --color=auto ssh
[root@VM-100-12-centos ~]# kill 9 19371