Prevent exposing ports

Any example explaining ? That would be so helpful

Is this what you mean ?

Sure, here we go.

Create the main container and check hostname and ip:

me@host:~$ docker run --name main --tty --detach --hostname main alpine
e892748a15f2499e047acb75c526dfe6ebfe5754db5a689f6415f31b03fca8b0
me@host:~$ docker exec main ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
729957: eth0@if729958: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
me@host:~$ docker exec main hostname
main

Start a second container and use the network namespace of the main container, then check hostname and ip.

me@host:~$ docker run --name guest --tty --interactive --network container:main alpine
/ # hostname
main
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
729957: eth0@if729958: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
/ #

Exit the 2nd container and cleanup with docker rm -f guest main

Now I was able to build a firewall container, attach it to macvlan network attaching any container to it’s network directly as a hook


To add something for other topic viewers

when using docker compose you could use either service name or container name

two things to consider

  1. when the container stop the network deattach forever,
    one need to set dependancies in compose file
    docker network connect container:awall tester;
    # Error response from daemon: container sharing network namespace with another container or host cannot be connected to any other network
    
  2. would fail if firewall activated in build process as a lack of --cap-add,
    one need to add the activation command to either CMD or ENTRYPOINT not RUN
    You will need some capabilities, which is explained here :

That’s very satisfying for me,
Thanks, both of you