'Docker ufw connect to host machine

I tried out Docker with UFW and i read a lot of this.

My goal was to connect to an mariadb database on the host machine from an docker image.

Host (running ufw) -> docker container 1 - mediawiki -> Database (onHost)
                   -> docker container 2 - phpwebserver -> Database (onHost)
                   -> docker container 3 - nextcloud -> Database (onHost)
                   -> .......

I

By default docker uses iptables which can be disabled.

/etc/docker/daemon.json 
{
  "iptables": false
}

then set

/etc/default/ufw
DEFAULT_FORWARD_POLICY to ACCEPT

finally add this lines in the after.rules file

/etc/ufw/after.rules

*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING ! -o docker0 -s 172.17.0.0/16 -j MASQUERADE
COMMIT

Back to Docker: Now i add the localhost:port mapping and the database host in the docker-compose.yml file

ports:
  - "127.0.0.1:8080:8080"
MEDIAWIKI_DB_HOST: 172.17.0.1 <- this was the docker0 interface

I see with docker ps, that docker runs as localhost:

CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                                NAMES
cffb491c84b2        db_mediawiki   "/docker-entrypoint.…"   22     minutes ago      Up 22 minutes       127.0.0.1:8080->8080/tcp, 9000/tcp     mediawiki_wiki

Now i can connect with an reverse nginx on the host system to this docker image. Or simply using curl localhost:8080/wiki/Main_Page

Without UFW all seems working, but with enabled UFW all connections are blocked from the bridge to docker0 interface?

[UFW BLOCK] IN=br-9da71acf3f9f OUT= MAC=02:42:f2:7b:35:7b:02:42:ac:12:00:02:08:00 SRC=172.18.0.2 DST=172.17.0.1 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=53146 DF PROTO=TCP SPT=36126 DPT=3306 WINDOW=29200 RES=0x00 SYN URGP=0

Can anyone provide some help to get this step working?

Many thanks,

David



Solution 1:[1]

You don't need to change /etc/ufw/after.rules.

Just add this rule to ufw:

sudo ufw allow in on docker0 from 172.17.0.0/16 to 172.17.0.0/16

This will allow all packets on the docker0 interface with 172.17.0.0 network.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marvo