使用iptables动态映射Docker容器端口
0x0. 安装telnet
telnet介绍:https://zh.wikipedia.org/wiki/Telnet
本文用于测试指定端口是否开放,命令如下:
telnet [ip] [port]
参数解释:
- ip:ip地址
- port:端口
如果指定端口开放则结果如下:
如果指定端口未开放则结果如下:
PS:可以通过快捷键ctrl+]退出连接,然后输入q退出telnet
0x1. 安装Docker
Docker官方安装文档:https://docs.docker.com/engine/install/
0x2. 实战
目标:开放js-redis容器的443端口
如下图所示,容器名称为js-redis,仅映射了6378 => 6379
使用以下命令进行动态映射Docker容器的端口
iptables -t nat -A DOCKER -p tcp --dport ${宿主机端口} -j DNAT --to-dest ${容器ip}:${容器端口}
iptables -t nat -A POSTROUTING -p tcp -s ${容器ip} -d ${容器ip} -dport ${容器端口} -j MASQUERADE
iptables -A DOCKER -p tcp -d ${容器ip} --dport ${容器端口} -j ACCEPT
我们映射js-redis容器的8081 => 8082
iptables -t nat -A DOCKER -p tcp --dport 8081 -j DNAT --to-dest 172.18.0.4:8082
iptables -t nat -A POSTROUTING -p tcp -s 172.18.0.4 -d 172.18.0.4 -dport 8082 -j MASQUERADE
iptables -A DOCKER -p tcp -d 172.18.0.4 --dport 8888 -j ACCEPT
补充:
- iptables其他常用命令:
- 列出Dcoker已设置的规则,带行号
iptables -t nat -vnL DOCKER --line-number
- 根据行号删除规则
iptables -t nat -D DOCKER 3
- 查看容器ip命令
docker inspect [容器id或者容器名称] | grep IPAddress
0x3. 参考
- iptables
- Docker and iptables
- How do I assign a port mapping to an existing Docker container?