大网数据广告活动
服务器运维问答

Docker: correct way to restrict access to certain IP addresses

· 52CE 我爱测

I have a Docker container exposing port 3306 to the Internet. I would like to restrict access to certain public IP addresses. As an example, let's use 1.2.3.4. As an additional condition, I want the rules to survive restarting th…

问题原文

原帖链接 · Peter Thomassen · CC BY-SA 3.0

I have a Docker container exposing port 3306 to the Internet. I would like to restrict access to certain public IP addresses. As an example, let's use 1.2.3.4.

As an additional condition, I want the rules to survive restarting the Docker daemon and rebooting the server. This allows me to use iptables-persistent (iptables-save/iptables-restore) to restore the rules when the server is rebooted, without having the dockerd startup interfering with it.

I tried the following:

  1. Modifying the FORWARD chain:

    iptables -I FORWARD -p tcp --dport 3306 -j REJECT
    iptables -I FORWARD -p tcp --dport 3306 -s 1.2.3.4 -j ACCEPT
    

    This works when done after starting the Docker daemon. When restarting the daemon, Docker inserts additional rules at the top of the chain, and my custom rules end up being ignored.

  2. Modifying the DOCKER chain:

    iptables -N DOCKER # if chain does not yet exist
    iptables -I DOCKER -p tcp --dport 3306 -j REJECT
    iptables -I DOCKER -p tcp --dport 3306 -s 1.2.3.4 -j ACCEPT
    

    This works until dockerd is restarted. It looks like dockerd clears the DOCKER chain upon restart, and all the custom rules are gone.

  3. Use --iptables=false. While this works in principle, this solution breaks the standard Docker forwarding features, and requires setting up the forwarding rules manually.

I would be surprised if there is no proper way to do this. Any ideas?

PS: I did some reading, to no avail (e.g. Steps for limiting outside connections to docker container with iptables?, Docker - Exposed ports accessible from outside - iptables rules ignored, but these questions don't seem to deal with the restarting issue.)

社区高分解答

原帖链接 · yoga_johnny · CC BY-SA 4.0

I have found https://serverfault.com/a/933803/592497 to be most valuable information to be able to expose certain ports among your internal network but block to the outside. For example a database container.

The main point is that you have to use the DOCKER-USER chain as this one will not be overwritten by Docker.

This will also solve your problem to have these rules persistent after reboot or serive restart.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-11-24)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。