Accessing Services from Host Machine in Docker šŸ³

If youā€™re running a local development server and need to access it from within a Docker container, you can use host.docker.internal a Docker Desktop feature.

For example, if your local service is running on port 3000, you can access it inside the container using:

http://host.docker.internal:3000

This is especially useful when working with microservices, API calls, or testing Front-end applications inside a containerized environment.

Learn more in my article:

This is a documented feature of Docker Desktop (regardless of the os):
https://docs.docker.com/desktop/features/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host

I feel it should be mentioned in your post that itā€™s a Docker Desktop feature.

2 Likes

Or as @meyay pointed out, install Docker Desktop on Linux :slight_smile:

It works by default on macOS and Windows because you can run Linux containers on those operating systems only in a Linux virtual machine manually or using Docker Desktop, which runs a VM while you can still run the client on the host operating system. It should work the same way on Linux too when using Docker Desktop.

If you just use --add-host with the host-gateway alias, it will just point to the host gateway while Docker Desktopā€™s host.docker.internal domain points to the ā€œlocalhostā€ of your host machine so you donā€™t have to publish the ports on the LAN IP or any Docker network gateway IP.

If you want to access the local port without Docker Desktop, you can do it as I described here

2 Likes

Youā€™re absolutely right! host.docker.internal is a documented feature of Docker Desktop, regardless of the OS. Iā€™ll update the post to make that clearer. Thanks for pointing it out! :+1:

1 Like

Thatā€™s a great point! Installing Docker Desktop on Linux enables host.docker.internal to work out of the box, just like on macOS and Windows. Thanks for the clarification! :blush:

Docker Desktopā€™s host.docker.internal maps directly to the localhost of your host machine, making it more convenient than just using --add-host=host-gateway, which only points to the host gateway.

For those not using Docker Desktop, your alternative method for accessing local ports without it is definitely usefulā€” good explanation! :rocket:

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.