Running a Webhost in a Docker Container with an Exposed Port (.Net Core 2.0)

I needed to setup a webhost in a docker container with an exposed port. I wanted to be able to call the exposed port from the local machinem, but I was having an issue connecting to this port. I tried several things but none worked, including:

  • changed configuration and ports, tried different ports
  • expose ports through docker run
  • adding a new windows route, through cmd, to connect to the container IP (route /P add 172.17.0.2 MASK 255.0.0.0 10.0.75.2) <- this actually made the container ip address (172.17.0.2) pingable
  • disabling iptables on docker daemon
  • installing docker-machine but it conflicts with Hyper-V

 

But after some time and research on half the internet sites, I finally found the issue and the solution. The HTTP receiver was listening on IPAddress.Loopback (127.0.0.1), but for docker to work, it has to be changed to IPAddress.Any (0.0.0.0):

 

This is because “the Docker network bridge won’t map requests to ports opened on the loopback address (127.0.0.1, or localhost). You have to specify the 0.0.0.0 address, which means “all IP addresses on this machine”. In a Docker container, that includes the network bridge IP address, so everything works as it should.”

I uploaded a sample project of a webhost in docker for you to try out. You can find it on github at this address: https://github.com/ciappara/aspnet-docker-webhost

 

How to run the aspnet-docker-webhost application?

Whilst in the csproj folder, run the following command to publish it for the debian runtime:

dotnet publish "..\aspnet-docker-webhost\aspnet-docker-webhost.csproj" -r debian.8-x64

Build and push the docker image:

docker build -t localhost:5000/aspnet-docker-webhost:latest .
docker push localhost:5000/aspnet-docker-webhost

If the docker image already exists, use the following command to delete the existing docker image:

docker rm -f aspnet-docker-webhost

Finally run the docker image, and you should be able to successfully run the webhost. By using the -p you can expose the port set in the UseUrls portion:

docker run -it -p 35035:35035 --name aspnet-docker-webhost localhost:5000/aspnet-docker-webhost

To view all docker images available on your machine, you can use the following command:

docker ps -a

Hello, nice to meet you

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Leave a Reply