docker.net-coredockerfile

Change dotnet core port in docker container


I'm very new to Dockers and I've been reading documentation and been doing some experiment's but there are few things I'm not getting. The Case is I've two application one is dotnet core web application and the other one is dotnetcore web Api. I'm running dotnet core web application inside a container. Below is the docker file:

WORKDIR /source

COPY . ./DockerTest/
WORKDIR /source/DockerTest

RUN dotnet publish -c release -o /app

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
EXPOSE 50/TCP
EXPOSE 50/UDP
COPY --from=build /app ./
ENTRYPOINT ["dotnet", "DockerTest.dll","--environment=development"]

and the command I execute to run this image is: docker run -d -p 90:50 myapp

Now here I'm trying to map 50 on which my dotnetcore application should be running to port 90 on my host machine. But unfortunately what ever port I give in EXPOSE my application always run on port 80 inside the container I want to know why is that so and how can I change that. Second thing is from inside the container I'm trying to access my web api which is running on host machine:

public async Task<string> GetData()
    {
        var data = "";
        var request = new HttpRequestMessage(HttpMethod.Get,
        "http://localhost:51468/weatherforecast");
        
        
        using (var context = ClientFactory.CreateClient()){
            var response = await context.GetAsync(request.RequestUri);

            if (response.IsSuccessStatusCode)
            {
                data = await response.Content.ReadAsStringAsync();                    
            }
            else
            {
                data = "error happen";
            }
        }
        return data;
    }

This is how I'm trying to send request to my api which is outside the container but it gives this error:HttpRequestException: Cannot assign requested address. Now I'm blocked and I need help and suggestions here.


Solution

  • First about you Docker:

    The docker EXPOSE 50 is only known for docker, dotnet knows nothing about docker. So in your DockerTest.dll you must also specify the listening port.

    don't use port 50, it is too low. Anything below 1024 is seen as well-known ports or system ports and should not be used. dotnet normally listening on port 5000 - when it is not 80/443.

    Second about you access to the host:

    When using localhost inside the docker container, it will not reach the host but only the container itself. So you have to use the Host LAN ip i.e. 192.168.. or something...