How to Connect to the Localhost of the Machine from inside of a Docker Container?

Better Stack Team
Updated on August 1, 2022

If you are running some kind of a server or any other service (such as a database) on localhost and the service isn’t exposing any port, you may have found yourself wondering how to connect to this service within the docker container. Here is how to do it.

Docker for Windows and Mac

If you are running Docker for Windows or Docker for Mac (version 18.03 or newer), you can use the host.docker.internal address instead of 127.0.0.1 in your connection strings.

Docker for Linux

If you are using Docker for Linux (version 20.10.0 or newer), you can also use the host.docker.internal address, if you started docker with the -add-host host.docker.internal:host-gateway option. See the example below:

 
docker run -d --add-host host.docker.internal:host-gateway <container>:latest

Another option (which works only on Linux) is to add -network="host” option in your docker run command. This will ensure that localhost will be pointing to your docker host.

 
docker run -d --network=host <container>:latest

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github