Docker가 시작 시 자체 규칙을 설정한 후 iptables 규칙을 어떻게 추가할 수 있나요?

Docker가 시작 시 자체 규칙을 설정한 후 iptables 규칙을 어떻게 추가할 수 있나요?

실행 중인 Docker 컨테이너에 대한 연결을 제한하고 싶습니다. 나는 iptables이것을 효과적으로 수행하는 일련의 규칙을 가지고 있습니다 . 그러나 규칙 세트는 DOCKER체인에 앞서 내 자신의 규칙 체인을 적용하는 것에 달려 있습니다.

기본적으로 나는 이런 결과를 원한다

Chain FORWARD (policy DROP)
target     prot opt source               destination
PRE_DOCKER  all  --  0.0.0.0/0            0.0.0.0/0            /* Insert before Docker's filtering to apply our own */
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0

Chain PRE_DOCKER (policy DROP)
target     prot opt source               destination
//My own rules go here targeting the DOCKER chain

시스템 시작 시 이러한 규칙을 설정하는 데 문제가 있습니다. systemd내용이 담긴 파일이 있어요

[Unit]
Description=Restore iptables firewall rules
Before=iptables-store.service
Requires=docker.service
After=docker.service
Conflicts=shutdown.target

[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore --noflush /var/lib/iptables/rules-save

[Install]
WantedBy=basic.target

하지만 시작할 때 오류가 발생합니다.

iptables-restore v1.4.21: Couldn't load target `DOCKER':No such file or directory

이는 Docker 서비스가 아직 규칙을 생성하지 않았음을 의미한다고 가정합니다.

iptables원하는 출력을 얻을 수 있도록 단위 파일이나 규칙을 구성하는 올바른 방법은 무엇입니까 ?

/var/lib/iptables/rules-save완전성을 위해 제가 설정한 내용은 다음과 같습니다 .

*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
:PRE_DOCKER - [0:0]

-I FORWARD -o docker0 -j PRE_DOCKER -m comment --comment "Insert before Docker's filtering to apply our own"
-A PRE_DOCKER ! -i eth0 -o docker0 -j DOCKER -m comment --comment "Anything coming from something other than the public interface send to DOCKER chain"
-A PRE_DOCKER -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -m comment --comment "Allow connections from established connections"
-A PRE_DOCKER -j DROP -m comment --comment "Drop anything else"

-A INPUT ! -i eth0 -j ACCEPT -m comment --comment "Accept anything coming from something other than the public interface"
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -m comment --comment "Allow connections from established connections"
COMMIT

답변1

나는 이것을 정말로 알 수 없었다. docker.service가 iptables DOCKER 체인을 생성하는 시점과 systemd가 이를 완료된 것으로 보는 시점에 타이밍 문제가 있는 것 같습니다.

그래서 나는 체인이 존재하는지 확인한 다음 규칙을 복원하려고 시도하는 폴링 방법을 사용했습니다.

while ! iptables -n --list DOCKER >/dev/null 2>&1
do
    sleep 1;
done

/sbin/iptables-restore --noflush /var/lib/iptables/rules-save

관련 정보