How to blacklist private dns resolution inside docker?

Problem

I want to block DNS resolutions that return private range IP addresses. What I've found so far is that to do such thing you need to setup a cache/recursive DNS server. However since I want to use it inside docker that's where I stumble upon difficulties.

The simplest way I found is using dnsmasq (as explained in this other answer). On the other hand just needs to run a single process so found out about supervisord which solves that issue. Nevertheless, created a sample docker image and when I use the localhost dns server (dnsmasq) by adding the flag --dns 127.0.0.1 or replacing /etc/resolv.conf from within the container I get an error ** server can't find google.com: REFUSED , which just makes sense after the warning I get at the time of running the container :

WARNING: Localhost DNS setting (--dns=127.0.0.1) may fail in containers.

Environment

Sample docker image:

FROM ubuntu:latest

RUN apt update &&\
    apt upgrade -y

RUN apt install -y supervisor \
    dnsmasq \
    dnsutils \
    iputils-ping \
    nano

RUN echo "stop-dns-rebind" > /etc/dnsmasq.d/stop-rebinding

COPY supervisor.conf /etc/supervisor.conf

ENTRYPOINT ["/usr/bin/supervisord", "-c", "/etc/supervisor.conf"]

supervisor.conf:

[supervisord]
nodaemon=true
logfile=/dev/stdout
logfile_maxbytes=0

[program:dnsmasq]
command=dnsmasq --no-daemon
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

Build:

sudo docker build . -t samplednsmasq

Run:

sudo docker run -it --dns 127.0.0.1 --rm samplednsmasq:latest

Is it doable?

I would like to know if there is any way of making it work (without using multi-container like docker-compose) and dnsmasq, I'm also open to other alternatives that doesn't involve a dns caching server.

Solution: Changed the supervisor.conf to:

[supervisord]
nodaemon=true
logfile=/dev/stdout
logfile_maxbytes=0

[program:dnsmasq]
command=dnsmasq --no-daemon --interface=lo --stop-dns-rebind
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

Also updated the Dockerfile

FROM ubuntu:latest

RUN apt update &&\
    apt upgrade -y

RUN apt install -y supervisor \
    dnsmasq \
    dnsutils \
    iputils-ping \
    nano \
    net-tools

RUN echo "listen-address=127.0.0.1\nbind-interfaces\nstop-dns-rebind" > /etc/dnsmasq.d/stop-rebinding &&\
    echo "\nserver=8.8.8.8\nserver=8.8.4.4\nno-resolv" >> /etc/dnsmasq.conf

COPY supervisor.conf /etc/supervisor.conf

ENTRYPOINT ["/usr/bin/supervisord", "-c", "/etc/supervisor.conf"]


Solution 1:

server can't find google.com: REFUSED means that there is no DNS server listening on the specified address. By default dnsmasq won't listen on 127.0.0.1 address.