How to access host port from docker container?

Better Stack Team
Updated on April 7, 2023

To access a port on the host machine from inside a Docker container, you can use the -p option when running the container to map the host port to a port in the container. For example, if you want to access port 8080 on the host machine from a container, you can use the following command:

 
docker run -p 8080:8080 my-image

This will map port 8080 on the host machine to port 8080 in the container. From inside the container, you can then access the service running on port 8080 on the host machine using the host machine's IP address or hostname. Note that the service running on the host machine must be configured to listen on the host port.

For example, if you have a web server running on port 8080 on the host machine, you can access it from inside the container using the following URL:

 
http://<host_ip_address>:8080

Note that if you are running Docker in a virtual machine, you may need to configure port forwarding or network settings in the virtual machine to allow access to the host machine's ports. Check the documentation for your virtualization software for more information.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack