使用Docker容器创建/删除主机iptable规则

时间:2018-05-26 11:58:34

标签: docker docker-compose

由于主机环境(resin.io),我需要从特权容器配置主机的iptables。停止容器时,应删除规则以执行清理并缓解长期问题。

1L << index看起来如下:

docker-compose.yml

使用bash脚本可以创建规则,如下所示:

version: '2'

services:
  firewall:
    build: ./firewall
    container_name: firewall
    network_mode: host
    privileged: true

问题是,如何构造iptables -A INPUT -i wlan0 -p tcp --destination-port 1883 -j DROP 和bash脚本,以便在容器停止时接收规则(接收SIGTERM)。

Conext: Mosquitto在Resin.io框架内的Raspberry Pi上作为服务运行。有两个网络接口,一个连接到互联网和一个内部网络。我想只将Mosquitto暴露给本地网络。在对previous question的回答中,我学会了如何为单个容器做到这一点,但它有以下缺点:

  • 容器中的服务以特权进行运行
  • 它不能使用Docker DNS(容器名称作为IP地址解析)
  • 单个容器为所有其他容器配置防火墙会更好

1 个答案:

答案 0 :(得分:0)

您将运行bash脚本作为主脚本,如下所示

exit_script() {
    echo "Printing something special!"
    touch /data/shutdown.txt
}

echo "Started with $@ $$ $? $0"
echo "Setting up firewall rules"
#if you use bash then below trap command will work
#trap exit_script SIGINT SIGTERM SIGHUP SIGQUIT SIGABRT SIGKILL

# if you use sh then below trap will work
trap exit_script INT TERM HUP QUIT ABRT KILL

tail -f /dev/null &
wait $!
echo "The command has ended now"

您可以看到如下所示的输出

$ docker run -it -d -v $PWD/data:/data exit
30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67

$ docker stop 30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67
30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67

$ docker logs 30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67
Started with  1 0 /tmp/run.sh
Setting up firewall rules
Printing something special!
The command has ended now

$ ls -al data/
total 0
drwxr-xr-x 1 vagrant vagrant  96 May 27  2018 .
drwxr-xr-x 1 vagrant vagrant 192 May 27  2018 ..
-rw-r--r-- 1 vagrant vagrant   0 May 27 04:13 shutdown.txt

以下docker-compose为我工作

version: "3"
services:
  firewall:
    build: .
    container_name: firewall
    network_mode: host
    privileged: true
    stdin_open: true
    stop_signal: SIGTERM
    stop_grace_period: 10s
    tty: true
    volumes:
      - ./data:/data

和测试

$ rm -rf data/

$ docker-compose up --build
Building firewall
Step 1/3 : FROM ubuntu:xenial
 ---> 0b1edfbffd27
Step 2/3 : COPY run.sh /tmp/run.sh
 ---> Using cache
 ---> c4ef587c94e1
Step 3/3 : CMD exec /tmp/run.sh
 ---> Using cache
 ---> 89a57a78369e
Successfully built 89a57a78369e
Successfully tagged exitscript_firewall:latest
Starting firewall ... done
Attaching to firewall
firewall    | Started with  1 0 /tmp/run.sh
firewall    | Setting up firewall rules
^CGracefully stopping... (press Ctrl+C again to force)
Stopping firewall ... done

$ ls -al data/
total 0
drwxr-xr-x 1 vagrant vagrant  96 May 27  2018 .
drwxr-xr-x 1 vagrant vagrant 192 May 27  2018 ..
-rw-r--r-- 1 vagrant vagrant   0 May 27 04:19 shutdown.txt

您将看不到日志中的输出,但命令将会执行,因为您可以看到shutdown.txt

的存在