How to Port Forward Docker-Machine to Localhost
Port forwarding allows you to expose services running inside a virtual machine, such as Docker-Machine, to your local machine. In this example, we’ll use VirtualBox and Docker-Machine to forward port 8080 from the virtual machine to localhost.
Prerequisites
Before you begin, make sure you have the following:
- Docker-Machine installed.
- VirtualBox installed.
- The virtual machine you want to configure, e.g.,
boot2docker-vm
.
Step 1: Open a Terminal
Open a terminal on your local machine. You’ll use this terminal to run commands to configure port forwarding.
Step 2: List Virtual Machines
Run the following command to list the virtual machines managed by Docker-Machine:
|
|
This command will display a list of virtual machines, including their names and status. Make a note of the name of the virtual machine you want to configure for port forwarding.
Step 3: Configure Port Forwarding
Use the VBoxManage
command to configure port forwarding for your virtual machine. There are two variations of the command you provided in your question:
-
To forward port 8080 from the virtual machine to port 8080 on your local machine:
1
VBoxManage controlvm <your-vm-name> natpf1 "nginx,tcp,,8080,,8080"
-
To forward port 8080 from the virtual machine to port 8080 on
127.0.0.1
(localhost) on your local machine:1
VBoxManage controlvm <your-vm-name> natpf1 "nginx,tcp,127.0.0.1,8080,,8080"
Replace <your-vm-name>
with the actual name of your virtual machine obtained from the docker-machine ls
command.
Step 4: Verify Port Forwarding
To ensure that the port forwarding is configured correctly, you can run the following command to check the port forwarding rules for your virtual machine:
|
|
Look for the section that begins with "Forwarding(0)"
. It should display the port forwarding rule you’ve just added.
Step 5: Access the Service
Now that you’ve configured port forwarding, you can access the service running inside your Docker-Machine virtual machine by accessing http://localhost:8080
in your web browser.
That’s it! You’ve successfully set up port forwarding from your Docker-Machine virtual machine to your local machine, allowing you to access services running in the virtual machine as if they were running locally.