List IP tables in Docker Container

44,094

Capabilities

If you want have iptables access within your containers, you need to enable specific capabilities via the --cap-add=NET_ADMIN switch when running the container initially.

Example

$ docker run --cap-add=NET_ADMIN -it ubuntu:16.04

Then in the container set up iptables & sudo:

# apt update -y
# apt-get install iptables sudo -y

Then inside the container, set up a user, user1, and added it to the sudo group:

# adduser user1
# adduser user1 sudo

Then set user to user1:

# su - user1

Check user1's sudo permissions:

$ sudo -l
[sudo] password for user1:
Matching Defaults entries for user1 on 1356bf8bd61a:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User user1 may run the following commands on 1356bf8bd61a:
    (ALL : ALL) ALL

Check if they can access iptables via sudo:

$ sudo iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

References

Share:
44,094

Related videos on Youtube

northsideknight
Author by

northsideknight

Updated on September 18, 2022

Comments

  • northsideknight
    northsideknight over 1 year

    I want to run the iptables command in a Ubuntu 16.04 Docker container. I have created a user, given that user root permissions, added them to the sudo group, but I am still being told that I am not running iptables as root.

    $ groups
    stack root sudo
    
    $ sudo whoami
    root
    
    $ sudo iptables --list
    iptables v1.6.0: can't initialize iptables table `filter': Permission 
    denied (you must be root)
    Perhaps iptables or your kernel needs to be upgraded.
    

    In my /etc/sudoers file I have the line: %sudo ALL=(ALL:ALL) ALL, which I believe should allow any user in the sudo group (which I am) to run any command, but I still get the permission denied error.

    How would I successfully run the iptables command as this user?

    Please note I am doing this in a Docker container with image: ubuntu:16.04

  • northsideknight
    northsideknight almost 6 years
    That worked! Thanks for the detailed answer! Alternatively, I also found that using the --privileged flag works as well
  • Stephane
    Stephane over 4 years
    How would you do it in Compose 3 ? The doc says the cap_add: option is ignored docs.docker.com/compose/compose-file
  • Adan Rehtla
    Adan Rehtla about 4 years
    The cap_add and cap_drop options are ignored when deploying a stack in swarm mode