Dotnet inside Docker giving Connection Refused error

am running an API which I made using Dotnet Core and Swagger inside a Docker container. This API connects with another API hosted in a server.

This connection works perfectly when I run my API locally in my machine, however, when i run it inside a docker container I am presented with a System.Net.Http.HttpRequestException: Connection refused when I try to make a request to the server. However, if I do the exact same request from inside the docker container´s CLI using curl the request seems to work perfectly fine, so I suppose it´s a problem either dotnet or swagger is causing.

Futhermore, if I run the docker container while connected to a VPN (to the same network at which the server is at) the exception is not thrown and it all works perfectly fine.

My Dockerfile:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1

# Set up working directory
WORKDIR /app

# copy config and application file
COPY netcoreapp3.1/publish/ app/

# expose port used by api
EXPOSE 5004
ENV ASPNETCORE_URLS=http://+:5004


ENTRYPOINT ["dotnet", "app/DigitalTwin.Api.dll"]

The exception thrown :

Microsoft.AspNetCore.Server.Kestrel[13]

digital-twin-api | Connection id "0HM316M7IU0UH", Request id "0HM316M7IU0UH:00000003": An unhandled exception was thrown by the application.

digital-twin-api | System.Net.Http.HttpRequestException: Connection refused

digital-twin-api | ---> System.Net.Sockets.SocketException (111): Connection refused

digital-twin-api | at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)

digital-twin-api | --- End of inner exception stack trace ---

dockerfile - Docker container port 6002 connection refused - Stack Overflow states:

I had to force Kestrel to listen to port 6002, by adding the below to the appsettings.json.

"Kestrel": {
  "EndPoints": {
    "Http": {
      "Url": "http://+:6002"
    }
  }
}

My settings was:

"Kestrel": {
  "EndPoints": {
    "Http": {
      "Url": "http://localhost:6002"
    }
  }
}

It worked after replacing localhost with +.

1 Like

This makes sense now:

I was able to:

  1. From host see swagger documentation @ localhost:7000 (aka containerB)
  2. I was able curl from containerA to containerB (kestrel aspnetcore) at the port that was exposed:
    "FROM mcr.microsoft.com/dotnet/aspnet:3.1-focal AS base
    WORKDIR /app
    EXPOSE 6000

ENV ASPNETCORE_URLS=http://+:6000"
3. Could not curl the port 7000 that was routed when containerB was created with -p flag.

Solution:
which ever port the environment variable: ASPNETCORE_URLS is set with use that. Maybe it was my misunderstanding in how the ports were exposed but it worked with a reverse proxy nginx config.

Thanks for posting this.