skip to Main Content

When I run my .NET Core API locally in VS, I can hit it at localhost:5000. I added a Dockerfile to containerize it, but it’s not clear to me how to figure out what port to expose and use?

Here is my Dockerfile:

FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine as build
WORKDIR /app
COPY . .
RUN dotnet restore
RUN dotnet publish -o /app/published-app
EXPOSE 5000
ENV ASPNETCORE_URLS=http://*:5000

FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine as runtime
WORKDIR /app
COPY --from=build /app/published-app /app
ENTRYPOINT [ "dotnet", "/app/Api.dll" ]

The image builds, and I run it with this command:

docker run -p 5000:5000 --name my-api -d my-api

I can see it running on port 5000 in my Docker Client, but navigating to localhost:5000 yields no results ("localhost didn’t send any data").

2

Answers


  1. Move the ASPNETCORE_URLS and EXPOSE to the runtime image section as shown below also try changing

    http://*:5000
    

    to

    http://+:5000
    

    Dockerfile

    FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine as build
    WORKDIR /app
    COPY . .
    RUN dotnet restore
    RUN dotnet publish -o /app/published-app
    
    FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine as runtime
    WORKDIR /app
    COPY --from=build /app/published-app /app
    EXPOSE 5000
    ENV ASPNETCORE_URLS=http://+:5000
    ENTRYPOINT [ "dotnet", "/app/Api.dll" ]
    
    Login or Signup to reply.
  2. Rakesh’s answer works, but I just want to give you another option. I prefer to let the container listen on port 80 as it’s the default. If you want to do that, you can remove the EXPOSE and ASPNETCORE_URLS statements, so your Dockerfile becomes

    FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine as build
    WORKDIR /app
    COPY . .
    RUN dotnet restore
    RUN dotnet publish -o /app/published-app
    
    FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine as runtime
    WORKDIR /app
    COPY --from=build /app/published-app /app
    ENTRYPOINT [ "dotnet", "/app/Api.dll" ]
    

    Then you need to map port 80 to the port you want, when you run it

    docker run -p 5000:80 --name my-api -d my-api
    

    Now you can reach it on http://localhost:5000/

    The reason .NET apps based on the aspnet images listen on port 80 by default is that Microsoft set the ASPNETCORE_URLS environment variable to http://+:80 in it and that overrides any port configuration you have in your appsettings.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search