How to Access Host Port from a Docker Container

When working with Docker containers, it’s common to need access to services running on your host machine — such as a local database, API, or web server. However, containers are isolated from the host by design, making this slightly less straightforward than in traditional environments.

In this blog, we’ll cover how to access a host port from inside a Docker container, platform-specific considerations, and best practices.


⚙️ Why This Matters

Imagine you’re running a PostgreSQL server or a REST API on your host machine, and you want a Docker container (e.g., a web app) to connect to it. To do that, the container must reach the host network and port (e.g., localhost:5432).

But here’s the catch…

Inside a Docker container, localhost refers to the container itself — not the host.


✅ Solution: Use Host’s Special DNS Name

🐧 On Linux (Docker Default Network)

You can use host.docker.internal starting from Docker v20.10 on Linux:

ping host.docker.internal

Or connect using:

curl http://host.docker.internal:8000

If that doesn’t work (older versions), use the host’s gateway IP:

  1. Get the gateway IP:
ip route | grep default

Typically returns something like default via 172.17.0.1.

  1. Use this IP in the container:
curl http://172.17.0.1:8000

🪟 On Windows / 🧑‍💻 macOS

On Docker Desktop, host.docker.internal works out of the box:

curl http://host.docker.internal:8000

This is the recommended and supported way.


🔄 Option: Use --network="host" (Linux Only)

If you’re on Linux and need the container to share the host’s network stack completely, use the host network:

docker run --network="host" your-image

This gives the container direct access to all host ports as if it’s part of the host OS.

⚠️ Not available on macOS/Windows due to Docker VM isolation.


🛠️ For Docker Compose

You can configure the container to access the host via host.docker.internal:

services:
  app:
    image: your-image
    extra_hosts:
      - "host.docker.internal:host-gateway"

The host-gateway automatically resolves the correct IP.

Requires Docker Compose v1.28+.


🧪 Test Example

If you’re running a Python Flask app on your host:

python app.py  # Runs on localhost:5000

Inside the container, access it like:

curl http://host.docker.internal:5000

🧭 Summary

PlatformAccess Host Using
Windowshost.docker.internal
macOShost.docker.internal
Linux (modern)host.docker.internal or gateway IP
Linux (alternative)--network=host

✅ Best Practices

  • Avoid hardcoding host IPs; use host.docker.internal where possible.
  • Ensure the host service binds to all interfaces (0.0.0.0), not just localhost.
  • Use docker inspect or ip route if unsure about IP routing.

🔒 Security Note

Granting containers access to host ports can open up security risks. Use it only when necessary and avoid in production unless you’re certain of the implications.

Sharing Is Caring:

Leave a Comment