一、问题
内网有一台服务器安装了MongoDB,因开发需要,要外网也能访问。查询资料后发现Haproxy可以解决。方法是,用外网的服务器代理内网TCP。
二、环境
- 外网IP:xxx.xxx.xxx.xxx
- Mongo数据库内网IP:192.168.100.3
- Mongo数据库端口27017
三、实现步骤
1.宿主机下载docker镜像
docker pull haproxy
2.宿主机添加Haproxy配置文件(用于容器挂载)
mkdir /usr/local/etc/haproxy
vim /usr/local/etc/haproxy/haproxy.cfg
#配置的haproxy.cfg文件
global
log 127.0.0.1 local2
chroot /usr/local/etc/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
#user haproxy
#group haproxy
daemon
# turn on stats unix socket
stats socket /usr/local/etc/haproxy/stats
defaults
log global
log 127.0.0.1 local3
mode http
option tcplog
option dontlognull
retries 10
option redispatch
maxconn 2000
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
listen mongo
bind xxx.xxx.xxx.xxx:27017
mode tcp
balance roundrobin
server mongo1 192.168.100.2:27017
3.创建且运行容器
docker run -d --name haproxy --net=host -v /usr/local/etc/haproxy:/usr/local/etc/haproxy haproxy
4.在宿主机测试
mongo 127.0.0.1:27017
done