Ever found yourself needing your Docker container to connect to a specific IP or custom hostname—just like you would on your local machine? You’re not alone! Many developers run into this while testing, debugging, or integrating with services outside the container.

Understanding how to add a host entry with Docker is essential for creating smooth, reliable development and testing environments. In this article, you’ll learn exactly how to use Docker’s host configuration feature, step-by-step, plus helpful tips to avoid common pitfalls.

Related Video

How to Use Docker’s --add-host Flag: A Complete Guide

When working with Docker containers, you might come across situations where you need your container to recognize a custom hostname or connect to local development resources by a specific name. The --add-host flag lets you modify a container’s /etc/hosts file during startup, allowing you to inject host-to-IP mappings. This feature is especially helpful for local testing, service discovery, or simulating parts of a network environment inside your containers.

In this article, you’ll learn how the --add-host flag works, why it’s useful, and how to use it effectively in your development or CI/CD workflows. We’ll also uncover best practices, potential pitfalls, and advanced use cases.


What Does the --add-host Flag Do?

The --add-host flag allows you to add custom host-to-IP address mappings directly to the container’s /etc/hosts file when running a container with the docker run command.

This means you can map a hostname (“mydb.local”) to an IP address (e.g., the host machine, or a specific container, or a local development resource). When applications inside the container try to resolve the hostname, they’ll use the mapping you’ve provided.

In short:
It lets your Docker container pretend that a particular hostname points to a specific IP—even if that’s not true elsewhere on your network.


Why and When to Use --add-host

Here are some common scenarios for using the --add-host option:

  • Connecting to local resources: Link development environments running outside Docker (such as databases or APIs) to your containers using a consistent hostname.
  • Simulating production DNS: If you want to mimic a real-world environment locally, but without changing your local DNS settings.
  • Testing failover or multi-host setups: Emulate a DNS entry that points to different services or simulate changing network conditions.
  • Resolving specific hostnames in tests: Force a certain hostname to always resolve to a test double or a mock server.

How to Use the --add-host Flag (Step-by-Step)

Let’s walk through how you actually use --add-host with Docker’s CLI.


How to Connect to Localhost Within a Docker Container - How-To Geek - docker --add host

1. Basic Syntax

The typical structure of the flag is:

docker run --add-host : 
  • “: The hostname you want the container to recognize.
  • “: The IP address that hostname should resolve to (from inside the container).
  • “: The Docker image you’re running.

Example:
You want to map the hostname mydb.local to your host machine’s IP 192.168.1.100:

docker run --add-host mydb.local:192.168.1.100 ubuntu ping mydb.local

This will let any process inside the container use mydb.local to reach 192.168.1.100.


2. Adding Multiple Host Entries

You can add as many host mappings as you need by repeating the --add-host flag:

docker run \
  --add-host db1.local:192.168.1.101 \
  --add-host db2.local:192.168.1.102 \


3. Discovering Your Host’s IP Address

You often want to connect your container to a service on your host. Here are some tips for common environments:

  • On macOS and Windows with Docker Desktop: You can use the special DNS name host.docker.internal for the host. (No need for --add-host unless you want a different arbitrary name.)
  • On Linux: Determine your local IP (e.g., with hostname -I or ip addr) and add it manually.
  • For custom hostnames: Use --add-host mycustom.local:host.docker.internal on Windows/macOS, or the correct IP on Linux.

Important Notes and Limitations

  • Works Only at Runtime: --add-host modifies /etc/hosts while launching a container, not during docker build. You cannot use this flag inside a Dockerfile to persist entries in an image.
  • Overrides or Conflicts: If a hostname appears twice in /etc/hosts, the last entry usually wins.
  • Doesn’t affect DNS: This change is local to each container’s /etc/hosts and does not propagate to other containers or any global DNS.
  • Security: Only use --add-host to map trusted resources; malicious hosts could potentially hijack traffic.

Practical Tips and Best Practices

  1. Keep entries relevant and simple: Don’t overload the container with unnecessary hosts mappings.
  2. Avoid hardcoding IP addresses when possible: If resources are always on the host, use special hostnames like host.docker.internal for portability across machines.
  3. Use environment variables for flexibility: For automated environments, parameterize host mappings using shell variables or Docker Compose configuration.
  4. Leverage Docker Compose for multi-container setups: Docker Compose lets you use the extra_hosts field to achieve the same effect for more complex stack definitions.
  5. Test before you automate: Always try new changes interactively (docker run ... ping) to verify the mapping works as expected.

Using --add-host in Docker Compose

If you use Docker Compose, you can add custom host entries in your docker-compose.yml file with the extra_hosts key.

Example:

services:
  myapp:
    image: ubuntu
    extra_hosts:
      - "dbhost:192.168.1.100"
      - "api.local:10.0.0.2"

This ensures the mapping is consistent across all containers in your stack.


Common Challenges and Solutions

1. Needing to Add to /etc/hosts During Docker Build

  • Limitation: The --add-host flag is only valid at docker run. During a docker build, Docker manages /etc/hosts automatically, and most changes you make inside a Dockerfile will be overwritten on container startup.
  • Solutions:
  • If you must reference a custom host during build (e.g., to fetch packages), use the --network flag or adjust your build context instead.
  • Save /etc/hosts changes outside the image (not recommended for most workflows).

2. Dynamically Determining Host IP Addresses

  • Tip: For dynamic environments (such as CI/CD pipelines or cloud), you may want to script the IP detection and inject it at container start.
  • Example:
    bash
    HOST_IP=$(hostname -I | awk '{print $1}')
    docker run --add-host myhost.local:$HOST_IP ubuntu

3. Connecting to Host Services in Linux

  • Unlike Windows/macOS, Linux doesn’t provide a built-in host.docker.internal DNS name by default.
  • You must use your actual external IP address (e.g., as found with ip addr or ifconfig).
  • Alternatively, add a custom route via --add-host myhost:$(hostname -I | awk '{print $1}').

Benefits of Using --add-host

  • Customization: Easily control hostname resolution inside containers for fine-tuned development and testing scenarios.
  • Isolation: Avoids global system changes; only affects the container you’re running.
  • Reproducibility: Combine static host-to-IP mappings with scripts or Compose for reliable environments across developers and CI systems.

Drawbacks and Considerations

  • Not suitable for dynamic or large-scale DNS needs: For complex service discovery, consider Docker networking, DNS-based service discovery, or orchestration solutions.
  • Values are fixed at container start: If the mapped IP changes, you need to restart the container with the new mapping.
  • Manual upkeep: Over time, you might lose track of which hostnames are mapped to what if it isn’t clearly documented.

Advanced Usage Scenarios

1. Testing with Multiple Mocks

If your application must interact with several services not available during development, use multiple --add-host entries to direct traffic to local mock servers.

2. Simulating Split DNS Environments

For troubleshooting deployments where DNS responses are different based on location, use --add-host to replicate each case and validate your application’s response to split DNS situations.


Cost Tips

While the --add-host flag itself has no direct monetary cost, efficient use can save you time and resources:

  • Avoid heavy manual reconfiguration: Automate adding host entries to minimize errors and reduce maintenance.
  • Leverage for local testing: Emulate paid networking environments (like cloud load balancers or managed DNS) in your free or local setup before deploying to production.
  • Optimize container startup: Don’t load containers with unnecessary hosts entries, which can slow down troubleshooting and management.

Summary

The --add-host flag in Docker is a powerful and straightforward way to manage hostname-to-IP address mappings inside your containers. Whether you’re targeting local resources, simulating a production environment, or running a robust multi-container test, this feature enhances your workflow without requiring global DNS changes.

By understanding best practices, limitations, and creative applications, you can tailor your development and CI pipelines to be faster, safer, and more closely aligned with production—saving valuable time and reducing bugs.


Frequently Asked Questions (FAQs)

1. What’s the main difference between --add-host and Docker’s built-in networking?
--add-host injects static hostname-to-IP mappings into a container’s local /etc/hosts file and is set at runtime. Docker networking provides dynamic DNS-based service discovery and works best for communication between containers on the same network.

2. Can I use --add-host in a Dockerfile?
No. The --add-host flag only works during docker run (or via extra_hosts in Docker Compose). Docker images can’t store fixed /etc/hosts entries because the file is rewritten at container startup.

3. How do I determine the correct IP address to use with --add-host?
If you want your container to connect back to your Docker host, on macOS/Windows use host.docker.internal. On Linux, use your actual network interface’s IP, found via hostname -I or similar.

4. Is it possible to update the /etc/hosts file after a container is running?
You can’t update the /etc/hosts file directly via Docker commands on a running container. You would need to stop the container and start a new one with updated --add-host flags.

5. Should I use --add-host for production environments?
It’s generally not recommended for production setups, as it requires manual management and does not scale well. For service discovery or production DNS needs, use reliable DNS configurations and Docker networking features.