Fix for ASP.NET Core Docker service not being exposed on host

When attempting to Dockerize my ASP.NET Core micro-service, I ran into an interesting issue. We use Docker’s Network feature to create a virtual network for our docker containers; but for some reason I wasn’t able to issue a curl request against the ASP.NET Docker container, it simply returned:

curl: (52) Empty reply from server

Well crap.  Docker was set up correctly; and ASP.NET Core applications listen on port 5000 typically:

Complete Dockerfile:

FROM microsoft/dotnet:1.1.0-runtime
ARG source=./src/bin/Release/netcoreapp1.1/publish
WORKDIR /app
COPY $source .
EXPOSE 5000
ENTRYPOINT ["dotnet", "MyProject.dll"]

ASP.NET Core dotnet run output:

my-project
Hosting environment: Production
Content root path: /app
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Hm. It’s listening on localhost (the docker container), and I’ve exposed port 5000, right? Maybe my port settings are wrong when I spin up the container? Let’s check:

docker run -i -p 5000:5000 --name my-project -t my-project:latest

That checks out. The syntax for docker -p is HOST:CONTAINER, and I’ve made them 5000 on both sides just for testing, but I’m still not getting a response.

I found out that by default, ASP.NET Core applications only listen on the loopback interface — that’s why it showed me localhost:5000. That doesn’t allow it to be viewed externally from the host. Sort of a bonehead moment on my part; but there you are. So to fix it, I can tell Kestrel to listen using the UseUrls() method and specify interfaces to listen on:

public static void Main(string[] args)
{
  var host = new WebHostBuilder()
    .UseKestrel()
    .UseUrls("http://*:5000") //Add this line
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseStartup()
    .UseIISIntegration()
    .Build();

   host.Run();
}

Now, it will listen to all network interfaces on the local machine at port 5000, which is exactly what I want.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s