How to Connect to localhost from a Docker Container
Connect to localhost from a Docker Container on Windows, Mac and Linux
Published by Carlo van Wyk on June 15, 2025 in Docker

Connecting to the host machine's localhost from inside a Docker container requires using special DNS names or networking configurations. Here are the main approaches:
1. Using host.docker.internal
On Windows and macOS, use the special DNS name host.docker.internal
to access the host machine:
# Example connection string
mysql -h host.docker.internal -u root -p
2. Using host network mode
Run the container with host network mode to share the host's network namespace:
docker run --network host your-image
3. Using Docker Compose
In docker-compose.yml, configure the host connection:
services:
web:
image: nginx
extra_hosts:
- "host.docker.internal:host-gateway"
4. Using Linux-specific configuration
For Linux systems, add the host IP manually:
docker run --add-host=host.docker.internal:host-gateway your-image
When accessing services on the host machine, use the appropriate port numbers and ensure the host services are configured to accept external connections.
Common Connection Examples
# MySQL connection
mysql -h host.docker.internal -P 3306 -u user -p
# HTTP connection
curl http://host.docker.internal:8080
# MongoDB connection
mongodb://host.docker.internal:27017
Remember to configure your host services to listen on all interfaces (0.0.0.0) instead of just localhost (127.0.0.1) to allow container access.