Docker Container Connection Refused
I’ve been playing with .NET Core CLI recently and came across cli-samples on Github. The projects in this repository show working examples using the dotnet CLI and ASP.NET 5. Everything runs well on Mac OS. Then I decided to make a docker image from the HelloMvc project.
The Dockerfile is quite simple
FROM microsoft/dotnet-preview
RUN mkdir /src
WORKDIR /src
ADD . /src
RUN dotnet restore
RUN dotnet build
CMD dotnet run
Built and runned with port 5000 exposed
docker run --rm -v $(pwd):/src -p 5000:5000 -w /src HelloMvc
The application started and was listening on port 5000. Looks good.
Project HelloMvc (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified
Compiling HelloMvc for .NETCoreApp,Version=v1.0
/src/HelloMvc/project.json(6,26): warning DOTNET1015: The 'compilationOptions' option is deprecated. Use 'buildOptions' instead.
Compilation succeeded.
1 Warning(s)
0 Error(s)
Time elapsed 00:00:07.9852201
dbug: Microsoft.AspNetCore.Hosting.Internal.WebHost[3]
Hosting starting
dbug: Microsoft.AspNetCore.Hosting.Internal.WebHost[4]
Hosting started
Hosting environment: Production
Content root path: /src/HelloMvc
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
The IP address of docker machine is
docker-machine ip default
192.168.99.100
However, when I opened a browser and typed in http://192.168.99.100:5000, I saw this
This site can’t be reached
192.168.99.100 refused to connect.
What is going on? It worked well without container, and port 5000 is exposed to outside access. When listing the active containers, I can see that the port binding is from 0.0.0.0:5000 to 5000, which allows inbound access from all network interfaces.
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
c94a021995d9 HelloMvc "dotnet run" 12 seconds ago Up 11 seconds 0.0.0.0:5000->5000/tcp
However, the MVC application listens to 127.0.0.1:5000 by default, which is a loopback IP address. As a result, it only acceps connection requets within the current host. Connections from outside the container will be simply refused. I need to make it listen to all network interface by listening to 0.0.0.0. All that need to be changed was the program.cs
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5000")
.Build();
host.Run();
}
}
Hope this may save someone a few hours of time.