4

I am trying to set specific iptables rules inside a container but so far i have no luck. So far i tried to enter (exec bash) the container and add manually the rules, then, export the running container to a new image.

When i import the image and start the new container the iptable rules are still not there.

How can i have specific iptables rules when the container is created without having to set them automatically?

I am using docker-CE 19.03.1

The image is a custom debian-strech created using debootstrap.

2 Answers 2

3

I managed to implement this by:

1) adding all iptables rules i wish to apply on a bash script .

2) Copy the bash to the container using the Dockerfile

3) Use again Dockerfile to run the iptables bash script within the container.

For example:

iptables script

#!/bin/bash
iptables -I FORWARD -i tun+ -j ACCEPT
iptables -I OUTPUT -o tun+ -j ACCEPT
iptables -I FORWARD -i tun+ -s 10.88.0.0/24  -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I FORWARD -s 10.88.0.0/24  -o tun+ -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

echo "iptables executed " > /root/iptables_echo

Dockerfile

FROM "openvpn-server:ready"

WORKDIR /etc/openvpn
USER root

COPY iptables.sh /usr/local/bin/iptables.sh
RUN chmod +x /usr/local/bin/iptables.sh && apt-get install iptables
CMD iptables.sh

EXPOSE 443:443/tcp
0

iptables rules are not persistent across reboots. You should try something like the iptables-persistent package in Ubuntu.

apt install iptables-persistent 
mkdir -p /etc/iptables
iptables-save > /etc/iptables/rules.v4 
ip6tables-save > /etc/iptables/rules.v6
service iptables-persistent start

Here is an handy how-to: http://www.microhowto.info/howto/make_the_configuration_of_iptables_persistent_on_debian.html

If the distro you use doesn't have such tool you can just put the rules in a script and then let systemd or init inovke it at boot time.

1
  • i need persistency inside the container, i did tried with iptables-persistent but still didnt work, there isnt a systemd present in the container so i can enable iptables-persistent
    – giomanda
    Aug 5, 2019 at 7:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .