Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 111 ยท Networking

DNS, Proxies and Firewalls

Customize Docker container DNS with --dns and --add-host, reach the host via host.docker.internal, configure corporate proxies for builds and runs, and understand iptables.

Most Docker networking just works until you land in a real company network. Then you meet a custom DNS server that only knows internal names, a proxy that every outgoing request must pass through, a firewall that appears to ignore your rules, or a service that lives on your laptop instead of in a container. All of these are about the edges of Docker's network: the places where container traffic meets the rest of the world.

In this lesson you will learn how container DNS is configured and overridden, how to add fixed host entries, how a container reaches services on the host, how to make builds and containers use an HTTP proxy, and how Docker's firewall rules interact with the one you already have. Local examples were run for real; items that need a corporate network or Linux firewall are marked as read-only examples.

Where a container's DNS settings come from

Every container gets its own /etc/resolv.conf, generated by Docker when the container starts. What it contains depends on the network:

CONSOLE
$ docker run --rm --network app-net alpine:3 grep -v '^#' /etc/resolv.conf
nameserver 127.0.0.11
options ndots:0

On a user-defined network, the nameserver is 127.0.0.11, Docker's embedded DNS server (see User-Defined Bridge Networks). It answers names of containers and aliases on the container's networks itself, and forwards every other question to the upstream resolvers Docker copied from the host. The generated file even documents them in comments:

CONSOLE
$ docker run --rm --network app-net alpine:3 grep -E 'Ext|Overrides' /etc/resolv.conf
# ExtServers: [host(192.168.65.7)]
# Overrides: []

(The address is where Docker found its upstream; it differs per machine.) On the default bridge network there is no embedded server: the container just gets a copy of the host's resolver settings, and 127.0.0.1 entries from the host (common with systemd-resolved) are replaced by public DNS servers, which can break corporate setups.

Overriding DNS per container

Three flags change what the container uses:

Flag Effect
--dns <ip> Upstream DNS server(s) for names that are not containers (repeatable)
--dns-search <domain> Adds a search domain, so db is also tried as db.corp.local
--dns-option <opt> Adds a resolver option such as ndots:2

Here is the effect on the default bridge:

CONSOLE
$ docker run --rm --dns 1.1.1.1 --dns-search corp.local alpine:3 grep -E '^(nameserver|search)' /etc/resolv.conf
nameserver 1.1.1.1
search corp.local

On a user-defined network the container keeps talking to 127.0.0.11, and the --dns value becomes its upstream. That separation has a nice consequence: container names keep working even if the upstream is broken. We pointed --dns at an address that does not answer (192.0.2.1 is a documentation-only address) and compared:

CONSOLE
$ docker run --rm --network app-net --dns 192.0.2.1 alpine:3 sh -c 'nslookup redis | tail -2; nslookup -timeout=2 example.com 2>&1 | tail -2'
Name:	redis
Address: 172.21.0.2

;; connection timed out; no servers could be reached

The container name resolved instantly; the external name timed out. When "everything outside Docker is unreachable by name but IPs work", suspect the upstream DNS.

Setting DNS for every container

If your company DNS must be used everywhere, set it once in the daemon configuration instead of on every docker run. This is a read-only example (on Linux the file is /etc/docker/daemon.json; in Docker Desktop use Settings, Docker Engine):

JSON
{
  "dns": ["10.20.0.2", "10.20.0.3"],
  "dns-search": ["corp.local"]
}

Restart the daemon afterwards; running containers keep their old settings until they are recreated.

In Compose the same options are keys on the service: dns:, dns_search: and dns_opt:. See Services in Compose.

Fixed host entries: --add-host

Sometimes a name should map to a fixed address, for example an internal API you want to test against a staging IP. --add-host name:ip writes a line to the container's /etc/hosts, and the system resolver consults that file before DNS:

CONSOLE
$ docker run --rm --add-host api.internal:10.1.2.3 alpine:3 sh -c 'grep api.internal /etc/hosts; getent hosts api.internal'
10.1.2.3	api.internal
10.1.2.3          api.internal  api.internal

Use it for temporary overrides, tests, or services that have no DNS name. The Compose equivalent is extra_hosts:. Related: --hostname box sets the container's own hostname, which is also added to /etc/hosts:

CONSOLE
$ docker run --rm --hostname box alpine:3 sh -c 'hostname; tail -1 /etc/hosts | cut -f2'
box
box

Reaching the host from a container

A container's localhost is itself, so how does it call a development server running on your own machine (a database installed natively, an API started from your IDE)? Docker provides a special name, host.docker.internal, that points to the host. On Docker Desktop it exists automatically:

CONSOLE
$ docker run --rm alpine:3 getent hosts host.docker.internal
192.168.65.254    host.docker.internal  host.docker.internal

The address is the host as seen from the VM, and may be an IPv6 address too. A container can then use http://host.docker.internal:3000 in its config.

On a native Linux engine the name does not exist by default. Add it with the special value host-gateway, which Docker replaces by the address of the host on the bridge:

Terminal
# read-only example for Linux engines
docker run --rm --add-host host.docker.internal:host-gateway alpine:3 getent hosts host.docker.internal

(We ran this on Docker Desktop, where it simply added the same Desktop-provided entry, so the output is not a Linux demonstration.) In Compose: extra_hosts: ["host.docker.internal:host-gateway"].

Two cautions:

  • The service on the host must listen on an address the container can reach. A server bound to the host's 127.0.0.1 accepts connections only from the host; bind it to 0.0.0.0 or the bridge address. On Linux, the host firewall may also block traffic from the bridge.
  • Coupling a container to services on the host reduces portability. Prefer running the dependency as another container on the same network when you can.

Corporate proxies

If your office forces web traffic through an HTTP proxy, Docker needs to know in three separate places, because three different programs make requests:

  1. The Docker daemon, when it pulls and pushes images.
  2. Builds, when RUN apt-get update, npm install or pip install fetch packages.
  3. Running containers, when your app calls external APIs.

1. The daemon (image pulls)

The daemon needs its own proxy settings, separate from your shell's. On Docker Desktop, set them in Settings, Resources, Proxies. On a Linux server with systemd, use a drop-in file (read-only example):

INI
# /etc/systemd/system/docker.service.d/http-proxy.conf
[Service]
Environment="HTTP_PROXY=http://proxy.corp.local:3128"
Environment="HTTPS_PROXY=http://proxy.corp.local:3128"
Environment="NO_PROXY=localhost,127.0.0.1,.corp.local"

Reload systemd and restart Docker. If docker pull fails with a timeout or a certificate error while your browser works, this is the usual reason.

2. Builds

Proxy variables are predefined build arguments: you can pass them with --build-arg without declaring ARG in the Dockerfile. We built a Dockerfile that just prints proxy variables:

DOCKERFILE
FROM alpine:3
RUN env | grep -i _proxy || echo "no proxy variables"
CONSOLE
$ docker build --no-cache --progress=plain -t px .
#5 [2/2] RUN env | grep -i _proxy || echo "no proxy variables"
#5 0.285 no proxy variables
$ docker build --no-cache --progress=plain --build-arg HTTP_PROXY=http://proxy.example:3128 --build-arg NO_PROXY=localhost,.corp.local -t px .
#5 [2/2] RUN env | grep -i _proxy || echo "no proxy variables"
#5 0.357 no_proxy=localhost,.corp.local
#5 0.358 NO_PROXY=localhost,.corp.local
#5 0.358 http_proxy=http://proxy.example:3128
#5 0.358 HTTP_PROXY=http://proxy.example:3128

Docker sets both the upper-case and lower-case variants, because tools disagree on which they read. The proxy values are visible during the build only. Unlike a normal ARG, the predefined proxy arguments are excluded from the image history by design:

CONSOLE
$ docker history px --no-trunc --format '{{.CreatedBy}}' | head -2 | cut -c1-120
RUN /bin/sh -c env | grep -i _proxy || echo "no proxy variables" # buildkit
CMD ["/bin/sh"]

Still, never put a proxy URL with credentials in a build argument or a Dockerfile; other settings do end up in the image metadata (see ENV and ARG).

3. Running containers

For containers, pass the same variables with -e:

CONSOLE
$ docker run --rm -e HTTP_PROXY=http://proxy.example:3128 -e NO_PROXY=redis,.corp.local alpine:3 sh -c 'env | grep -i proxy | sort'
HTTP_PROXY=http://proxy.example:3128
NO_PROXY=redis,.corp.local

Note the NO_PROXY list: it must include the names of your other containers (redis, db, api) and internal domains. Otherwise container-to-container traffic is sent to the corporate proxy, which cannot resolve your private names and answers with an error.

Setting it once for the client

Instead of repeating the flags, you can configure the Docker CLI to inject them into every build and container. This is a read-only example for ~/.docker/config.json (on Windows, %USERPROFILE%\.docker\config.json):

JSON
{
  "proxies": {
    "default": {
      "httpProxy": "http://proxy.corp.local:3128",
      "httpsProxy": "http://proxy.corp.local:3128",
      "noProxy": "localhost,127.0.0.1,.corp.local"
    }
  }
}

The CLI then adds HTTP_PROXY, HTTPS_PROXY, NO_PROXY (and lower-case variants) to the containers it starts and to builds. Containers created by Compose through the same CLI configuration get them too. Because the variables sit in the container's environment, anyone who can docker inspect the container can read them.

TLS-inspecting proxies

Many corporate proxies re-sign HTTPS traffic with a company certificate authority. Inside a container that CA is not trusted, so curl and pip fail with certificate errors. The fix is to add the company CA certificate to the image (copy it in and run update-ca-certificates), not to disable verification with -k or --trusted-host, which hides real attacks.

Docker and your firewall

On Linux, Docker publishes ports and routes bridge traffic by writing its own iptables (or nftables) rules, and it does this when the container starts. This has a surprising consequence for people who use a friendly front-end such as ufw or firewalld:

  • A published port (-p 8080:80, which means 0.0.0.0:8080) is opened to the network by Docker's rules.
  • Those rules are evaluated before the ones your front-end manages for the host's own services, so ufw deny 8080 may have no effect on a container's published port.

Ways to stay safe (read-only examples; syntax varies by distribution):

Terminal
# 1. Bind published ports to the loopback address and put a reverse proxy in front
docker run -d -p 127.0.0.1:8080:80 nginx:alpine

# 2. Restrict who may reach published ports, in the DOCKER-USER chain
#    (Docker never touches this chain, so your rules survive restarts)
iptables -I DOCKER-USER -i eth0 ! -s 203.0.113.0/24 -j DROP

The first approach is simple and works everywhere. The second is for hosts that really must publish on a public interface; see Publishing Ports. Rules in DOCKER-USER apply to traffic that is routed to containers, so be careful with the inverse patterns, and test from outside the host.

Other firewall facts worth knowing:

  • Docker enables IP forwarding and masquerading (NAT) so containers can reach the internet. If you disable that in the daemon ("iptables": false), you take over all of this yourself, and published ports stop working until you do.
  • Windows and macOS (Docker Desktop) forward published ports from the VM to the host; the Windows or macOS firewall then decides whether other machines can connect.
  • If a published port works from the host but not from another computer, check the bind address in docker port, then the host firewall.

Putting it together: a diagnosis table

Symptom Likely cause Fix
Container names resolve, internet names do not Bad upstream DNS --dns or daemon dns; check host DNS
Internet works by IP, names fail only in containers Host uses a local stub resolver (127.0.0.x) Set explicit dns servers
Internal company names fail only in containers Missing search domain or corporate DNS --dns and --dns-search
docker pull times out but the browser works Daemon has no proxy settings Configure the daemon's proxy
pip install fails in a build with SSL errors TLS-inspecting proxy Add the company CA to the image
App calls to other containers go to the proxy NO_PROXY missing container names Add service names to NO_PROXY
ufw deny does not block a published port Docker's rules take precedence Bind to 127.0.0.1 or use DOCKER-USER
host.docker.internal unknown on Linux Not defined by default --add-host host.docker.internal:host-gateway

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On a user-defined network, which nameserver does a container's /etc/resolv.conf list?

    The embedded DNS answers container names and aliases itself, and forwards other queries to the upstream resolvers (set with --dns or inherited from the host).
  2. 2. You run a container on a user-defined network with --dns 192.0.2.1, an address that does not answer. What happens?

    --dns only changes the upstream used for external names. Container names are answered by the embedded server, so they keep working.
  3. 3. How can a Linux-engine container reach a service on the host by the name host.docker.internal?

    Docker Desktop defines the name itself; native Linux engines need the explicit host-gateway mapping (or Compose extra_hosts).
  4. 4. Why must NO_PROXY list your container names (like redis and db) when you run behind a corporate proxy?

    HTTP clients that honor HTTP_PROXY send everything to the proxy unless the destination matches NO_PROXY. Internal names and domains must be exempt.
  5. 5. On a Linux host with ufw, you deny port 8080, yet a container published with -p 8080:80 stays reachable. What is the recommended fix?

    Docker's own iptables rules are evaluated before ufw's, so ufw cannot easily block published ports. Binding to loopback or filtering in DOCKER-USER does.

Summary

  • User-defined networks give containers 127.0.0.11, which answers container names and forwards the rest to upstream DNS; --dns, --dns-search and --dns-option override the upstream settings.
  • --add-host name:ip writes fixed entries to /etc/hosts; --hostname sets the container's own name.
  • Use host.docker.internal to reach services on the host: automatic on Docker Desktop, host-gateway on Linux.
  • Proxies must be configured for the daemon (pulls), for builds (predefined HTTP_PROXY build args) and for containers (-e or ~/.docker/config.json); keep container names in NO_PROXY.
  • Docker's iptables rules can bypass ufw; bind ports to 127.0.0.1 or filter in DOCKER-USER.
  • Add company CA certificates to images instead of disabling TLS verification.

Next: Introduction to Docker Compose