## Intro

Docker multi-stage builds are a powerful way to create lean, efficient images by separating build-time dependencies from runtime artifacts. However, the build process itself can introduce networking challenges that are not present in single-stage builds. During multi-stage builds, each stage may require network access to download packages, clone repositories, or communicate with services. When these operations fail, the build breaks, often with cryptic error messages. This guide provides a systematic approach to diagnosing and resolving networking issues in Docker multi-stage builds. You will learn how to check DNS resolution, verify port connectivity, analyze routing and firewall settings, and run effective connectivity tests. By following the practical examples and commands, you can minimize downtime and ensure successful builds.

## Version and Environment Inventory

Before troubleshooting, establish a clear inventory of your Docker version, build environment, and network topology. This helps identify known issues and compatibility problems. Run `docker version` to see the client and server versions. For example:

```bash
$ docker version
Client: Docker Engine - Community
 Version: 24.0.5
 API version: 1.43
 Go version: go1.20.6
 Git commit: ced0996
 Built: Fri Jul 21 19:36:05 2023
 OS/Arch: linux/amd64
 Context: default

Server: Docker Engine - Community
 Engine:
  Version: 24.0.5
  API version: 1.43 (minimum version 1.12)
  Go version: go1.20.6
  Git commit: a61e2b4
  Built: Fri Jul 21 19:34:58 2023
  OS/Arch: linux/amd64
  Experimental: false
 containerd:
  Version: v1.6.22
  GitCommit: 8165fea5f98b4f9f14d1e0e03b0f9db8e9a4a913
 runc:
  Version: 1.1.8
  GitCommit: v1.1.8-0-g82f18fe
 docker-init:
  Version: 0.19.0
  GitCommit: de40ad0
```

Also check the BuildKit version if you are using Docker BuildKit, which is the default builder in recent versions and has different networking behavior. Use `docker buildx version` if you are using Buildx. Know whether your builds run on Linux, macOS, or Windows, and whether you are using a VM (e.g., Docker Desktop). Network constraints such as proxies, VPNs, and firewalls are critical. Identify if you are building in a CI environment with restricted network access. Collect the base images used in each stage, as some minimal images may lack DNS tools or have misconfigured resolvers. Having this inventory helps narrow down the root cause quickly.

To capture environment details systematically, record the following information in a shared document or ticketing system:

- Docker client and server versions (e.g., 24.0.5)
- BuildKit version and whether it is enabled (check `DOCKER_BUILDKIT` environment variable or `docker buildx ls`)
- Host operating system and architecture (e.g., Ubuntu 22.04 on x86_64)
- Container runtime (e.g., containerd, runc)
- Network type used for builds (default bridge, custom network, host network)
- Proxy environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) and their values
- Base images and tags for each build stage (e.g., `node:18-alpine`, `golang:1.21-bullseye`)
- CI/CD platform and runner configuration (e.g., GitHub Actions hosted runner, self-hosted Jenkins agent with specific firewall rules)

An example inventory entry might look like:

```text
Environment: Development workstation
Docker version: 24.0.5 (client and server)
BuildKit: enabled (default)
OS: macOS 13.4 (Docker Desktop 4.21.0)
Network: Docker Desktop internal VM network
Proxy: not configured (direct connection)
Base images: node:18-alpine (build), alpine:3.18 (runtime)
```

Keeping this information up to date will save time when a build fails, because you can quickly compare against known issues or share details with support channels.

## Safe Configuration Path

When configuring networking for multi-stage builds, make scoped changes to minimize risk. One common issue is DNS resolution inside build containers. Build containers inherit DNS settings from the Docker daemon, but you can override them per build using the `--dns` flag on `docker build`. For example, to use a specific DNS server:

```bash
$ docker build --dns 8.8.8.8 -t myapp:latest .
```

This sets the DNS server for all `RUN` commands in the build. If your organization has an internal DNS server, use its address. To verify the setting takes effect, add a `RUN` command that queries DNS:

```dockerfile
FROM alpine:3.18
RUN nslookup example.com
```

During build, you should see output like:

```text
Step 2/2 : RUN nslookup example.com
 ---> Running in a1b2c3d4e5f6
Server: 8.8.8.8
Address: 8.8.8.8:53

Non-authoritative answer:
Name: example.com
Address: 93.184.216.34
```

Port connectivity can be tested using tools like `nc` or `curl`. However, you must ensure these tools are available in the build stage. For example, in an Alpine-based stage, install `curl` before use:

```dockerfile
FROM alpine:3.18
RUN apk add --no-cache curl
RUN curl -v http://internal-service:8080/health
```

Routing issues may require adding a custom network to the build. Use `docker network create` to create a network and then use `--network` in `docker build`:

```bash
$ docker network create build-net
$ docker build --network build-net -t myapp:latest .
```

This allows the build to communicate with other containers on the same network. Firewall rules can block access. Check host firewall settings and adjust if necessary, but be cautious not to expose unnecessary ports. Using an HTTP proxy is a common requirement. Set build args for proxy variables:

```bash
$ docker build --build-arg HTTP_PROXY=http://proxy.example.com:8080 \
  --build-arg HTTPS_PROXY=http://proxy.example.com:8080 \
  --build-arg NO_PROXY=localhost,127.0.0.1,.example.com \
  -t myapp:latest .
```

Inside the Dockerfile, reference these `ARG`s:

```dockerfile
ARG HTTP_PROXY
ARG HTTPS_PROXY
ARG NO_PROXY
ENV HTTP_PROXY=$HTTP_PROXY \
    HTTPS_PROXY=$HTTPS_PROXY \
    NO_PROXY=$NO_PROXY
RUN curl -I https://example.com
```

This scoped approach ensures changes affect only the build and not the entire host environment.

Additionally, you can set DNS, proxy, and other networking options in a BuildKit configuration file for more control. For example, create `/etc/buildkit/buildkitd.toml` with:

```toml
[registry."docker.io"]
  mirrors = ["mirror.example.com"]
```

Then restart BuildKit. This can help when the default registry is slow or blocked, but remember that it affects all builds on that host.

Another useful scoped change is to use a dedicated build network with specific DNS settings. For instance:

```bash
$ docker network create --driver bridge --subnet=172.20.0.0/16 --gateway=172.20.0.1 build-net
$ docker build --network build-net --add-host=internal-service:172.20.0.10 -t myapp:latest .
```

The `--add-host` flag adds an entry to the container's `/etc/hosts`, which can help resolve internal hostnames without DNS changes.

## Verification and Diagnostics

After applying configuration changes, verify connectivity step by step. Start with DNS resolution using `getent` or `nslookup`. For example, in a build stage:

```dockerfile
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y dnsutils
RUN getent hosts example.com
```

Expected output:

```text
93.184.216.34 example.com
```

If DNS fails, you will see no output or an error. Next, test TCP connectivity to a specific host and port. Use `nc -zv`:

```dockerfile
FROM alpine:3.18
RUN apk add --no-cache netcat-openbsd
RUN nc -zv example.com 443
```

Expected output:

```text
example.com (93.184.216.34:443) open
```

For HTTP services, use `curl -v` to see the full handshake:

```dockerfile
RUN curl -v http://example.com
```

The output shows DNS resolution, connection establishment, and HTTP response. To diagnose routing, use `traceroute` or `tracepath`. In a Debian-based stage:

```dockerfile
RUN apt-get update && apt-get install -y traceroute
RUN traceroute -n example.com
```

This shows the path packets take to reach the destination. If the traceroute stops at a certain hop, it indicates a routing or firewall issue. For firewall checks, try to connect to a known open port and a known closed port to see if the firewall is blocking. Also inspect the container's network configuration within the build using `ip addr` or `ifconfig`:

```dockerfile
FROM alpine:3.18
RUN apk add --no-cache iproute2
RUN ip addr show
```

The output shows the container's IP address and network interfaces. Compare this with the expected subnet. Finally, check the Docker daemon logs for network-related errors:

```bash
$ sudo journalctl -u docker.service | grep -i network
```

This can reveal issues like IP address allocation failures or bridge problems. Document all observations to identify patterns.

To make diagnostics more efficient, create a reusable Dockerfile snippet with common network tools. For example:

```dockerfile
FROM alpine:3.18 AS debug
RUN apk add --no-cache bind-tools curl netcat-openbsd iproute2 traceroute
```

Then, during troubleshooting, you can temporarily change the `FROM` of the failing stage to `debug` and run the tests interactively with `docker run --rm -it debug sh` to explore the network environment without waiting for a full build.

Another useful diagnostic is to check the container's DNS configuration directly:

```bash
$ docker run --rm alpine:3.18 cat /etc/resolv.conf
nameserver 192.168.65.7
```

This shows which DNS server the container will use. Compare it with the host's DNS settings. If it is incorrect, you can override it with `--dns` or by editing the Docker daemon configuration.

## Failure Modes and Recovery

Networking failures in multi-stage builds can manifest in various ways. Common failure modes include DNS resolution timeouts, connection refused, no route to host, and TLS certificate verification failures. For DNS timeouts, check if the DNS server is reachable from the build container. Use `nslookup` with a specific DNS server to isolate the issue. If the default DNS server is unreachable, override with `--dns`. Connection refused often indicates the service is not listening on the target port or a firewall is blocking. Verify the service is running and the port is correct. No route to host may mean the IP address is unreachable due to routing misconfiguration. Check the container's routing table using `ip route`:

```dockerfile
FROM alpine:3.18
RUN apk add --no-cache iproute2
RUN ip route
```

Expected output might look like:

```text
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 scope link  src 172.17.0.2
```

If the default route is missing or pointing to the wrong gateway, adjust the container network or the build's `--network` setting. TLS failures can be caused by proxy interception or missing CA certificates. Add the corporate CA certificate to the build stage:

```dockerfile
FROM alpine:3.18
COPY corporate-ca.crt /usr/local/share/ca-certificates/
RUN update-ca-certificates
```

Recovery steps may involve reverting to a previous Dockerfile configuration or using a different base image version. Keep backups of your Dockerfile and related configuration. For CI/CD pipelines, cache the base images to avoid repeated network fetches. Use `docker build --pull=false` to use locally cached images, but be aware of stale images. If a proxy is required, ensure the build environment has the correct proxy settings. Test the proxy with a simple `curl` command. Rollback can be as simple as changing the Dockerfile back to the last known good state and rebuilding. Document each change and its effect to create a knowledge base for future troubleshooting. In some cases, disabling BuildKit (if enabled) may resolve issues due to its different networking stack. Use `DOCKER_BUILDKIT=0 docker build ...` to fall back to the legacy builder. However, note that BuildKit has improved networking features; reverting should be a temporary measure.

Here is a more detailed recovery workflow for each common failure:

**DNS resolution timeout**

- Symptom: `RUN apt-get update` or `RUN npm install` hangs and eventually fails with `Could not resolve host`.
- Check: Run `nslookup deb.debian.org` inside the build stage (install `dnsutils` or `bind-tools` as needed).
- Fix:
  - Override DNS with `docker build --dns 8.8.8.8`.
  - Or add `--network host` to use the host's DNS (not recommended for security, but useful for diagnosis).
  - Ensure the Docker daemon's DNS settings are correct by editing `/etc/docker/daemon.json` and restarting Docker.

**Connection refused**

- Symptom: `curl http://internal-service:8080` returns `Failed to connect to internal-service port 8080: Connection refused`.
- Check: Verify the service is actually running and listening on port 8080 from another container.
- Fix:
  - Correct the service URL or port.
  - Ensure the service is reachable from the build container by using the correct network.
  - If the service requires authentication, add headers or credentials.

**No route to host**

- Symptom: `curl` fails with `No route to host`.
- Check: Run `ip route` inside the build container and ensure the subnet is correct.
- Fix:
  - Use a custom network with proper subnet and gateway: `docker build --network build-net`.
  - Check host firewall rules (e.g., `ufw`, `iptables`) to allow traffic.

**TLS certificate verification failure**

- Symptom: `curl https://example.com` fails with `SSL certificate problem: unable to get local issuer certificate`.
- Check: Determine if a proxy is intercepting TLS (look for `HTTP_PROXY` env var).
- Fix:
  - Add the corporate CA certificate to the build stage as shown above.
  - Or temporarily set `curl -k` for testing (not for production).

## Common Pitfalls and How to Avoid Them

Many networking issues in multi-stage builds stem from avoidable mistakes. Here are the most frequent ones, why they happen, and how to prevent or recover from them.

**1. Using floating base image tags**

- Why it happens: Convenience leads to using `latest` or unpinned tags like `node:18` instead of `node:18.17.1`.
- Consequence: The base image changes unexpectedly, potentially introducing DNS or network configuration changes.
- Fix: Always pin base image tags to a specific version or digest. For example, use `FROM node:18.17.1-alpine3.18` instead of `FROM node:18-alpine`. You can find the appropriate tag on Docker Hub.

**2. Ignoring proxy settings**

- Why it happens: Developers working on a corporate network assume the build environment automatically inherits proxy settings.
- Consequence: Package managers inside the build container cannot reach external repositories, leading to timeouts.
- Fix: Always pass `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` as build args and set them as environment variables in the Dockerfile. Document the required proxy values in your project's README or CI configuration.

**3. Assuming DNS works out of the box**

- Why it happens: On a developer laptop, DNS often works because Docker Desktop provides a local DNS resolver. In other environments, the default DNS may be different.
- Consequence: Builds fail with DNS resolution errors even though the host can resolve names.
- Fix: Explicitly test DNS in the build stage, and if needed, override with `--dns` or configure the Docker daemon's DNS. Include a `RUN getent hosts example.com` as a sanity check in your Dockerfile for critical builds.

**4. Hardcoding IP addresses**

- Why it happens: During development, a service IP is discovered and hardcoded into the Dockerfile or scripts.
- Consequence: The IP changes in a different environment, causing connection failures.
- Fix: Use DNS names or environment variables for service endpoints. For internal services, use Docker's embedded DNS with a custom network, or pass the address as a build arg.

**5. Not accounting for BuildKit differences**

- Why it happens: BuildKit is now the default builder, but some developers are used to the legacy builder's networking behavior.
- Consequence: Certain network operations (e.g., using `--network=host` or mounting to access host services) may behave differently.
- Fix: Understand BuildKit's networking model and test builds with both builders if necessary. Be aware that BuildKit has better support for advanced networking, so prefer it over the legacy builder if possible.

**6. Overlooking firewall rules in CI runners**

- Why it happens: CI runners have their own network policies that may block outbound traffic to certain ports or IP ranges.
- Consequence: Builds fail only in CI, not locally.
- Fix: Work with your infrastructure team to whitelist necessary endpoints. Document the required ports and protocols (e.g., TCP 443 for HTTPS, TCP 53 for DNS).

**7. Mixing runtime and build-time secrets in environment variables**

- Why it happens: Developers set secrets as build args for convenience, but they end up in the image history.
- Consequence: Exposed credentials or tokens, and potential network issues if secrets are invalid.
- Fix: Use BuildKit secrets (`--secret`) or runtime environment variables instead of build args for sensitive data. For network authentication, use a proxy that handles credentials securely.

**8. Failing to clean up temporary network changes**

- Why it happens: During troubleshooting, someone adds `--network host` or `--dns 8.8.8.8` to the build command and forgets to remove it.
- Consequence: The change becomes permanent in scripts or CI configs, leading to inconsistent behavior.
- Fix: Always document any temporary changes and revert them after the issue is resolved. Use version control to track modifications.

## Operations Checklist

Use this checklist for regular operations and review of multi-stage build networking. Assign each item to a specific owner (for example, the DevOps engineer or team lead), and review the checklist results on a weekly or monthly basis, depending on how frequently builds are run.

| Step | Action | Expected Result | Owner | Review Frequency |
|------|--------|-----------------|-------|------------------|
| 1 | Record Docker version and environment details | Version and OS info documented in a shared wiki | DevOps engineer | Monthly |
| 2 | Confirm base image tags are pinned | All `FROM` lines have specific tags or digests | Application team lead | Before each release |
| 3 | Test DNS resolution in the build stage | DNS query returns correct IP address | Build engineer | Weekly |
| 4 | Test connectivity to required services | Connection to internal services succeeds | Integration engineer | Weekly |
| 5 | Verify proxy settings if behind a proxy | Proxy environment variables set correctly and accessible | DevOps engineer | Monthly |
| 6 | Check firewall rules for required ports | Required ports (e.g., 443, 53) are allowed for build agents | Network administrator | Quarterly |
| 7 | Review Docker daemon logs for network errors | No critical network errors in last 30 days | System administrator | Monthly |
| 8 | Document any custom network configuration | Custom networks, DNS, and proxy settings are recorded in the runbook | DevOps engineer | As changes occur |

Perform these checks before each major release or when environment changes occur. Automate the checks where possible using build scripts or CI steps. For example, include a step in your CI pipeline that runs a DNS resolution test using a pre-built diagnostic image. Keep a log of networking changes and their impact. Regularly update base images to get security fixes and improved networking tools. Monitor build times and network usage to detect anomalies early.

To automate the checklist, you can create a script that runs the following commands and reports failures:

```bash
#!/bin/bash
# Check DNS resolution inside a build container
docker build --progress=plain -f - . <<'EOF'
FROM alpine:3.18
RUN nslookup example.com > /dev/null || exit 1
EOF
if [ $? -ne 0 ]; then
  echo "DNS resolution failed in build container"
  exit 1
fi
```

For connectivity to a specific service, use a similar approach with `nc` or `curl` and exit codes.

## Conclusion

Troubleshooting networking in Docker multi-stage builds requires a structured approach. Start by establishing a version and environment inventory. Make scoped configuration changes to DNS, ports, routing, and firewall settings. Verify each change with concrete diagnostics such as DNS lookups, connectivity tests, and route traces. Be prepared to handle common failure modes and roll back when necessary. Use the operations checklist to maintain a healthy build environment. By following the practical examples in this guide, you can reduce build failures and improve developer productivity. Next steps include setting up automated network tests in your CI pipeline and documenting your organization's specific network requirements for multi-stage builds.