Bhav
Bhav

Reputation: 2207

How to run a .net core web api locally on Docker?

I've created a web api that I can run locally in Visual Studio on localhost and I can access Swagger via. http://localhost:5000/swagger/index.html.

I've created a Dockerfile and executed docker build -t test . and I can see the image created in Docker Desktop. When running it, I don't get any error and I get these logs:

=info: Microsoft.Hosting.Lifetime[14]

      Now listening on: http://[::]:80

info: Microsoft.Hosting.Lifetime[0]

      Application started. Press Ctrl+C to shut down.

info: Microsoft.Hosting.Lifetime[0]

      Hosting environment: Production

info: Microsoft.Hosting.Lifetime[0]

      Content root path: /app

What do I need to do to make the web api accessible via. a browser?

Upvotes: 2

Views: 3916

Answers (3)

Hans Kilian
Hans Kilian

Reputation: 25632

Microsoft set the environment variable ASPNETCORE_URLS to http://+:80 in their base images, so your app is listening on port 80 when it runs in a container.

Update 2025-01-19: As of .NET 8, MS set ASPNETCORE_HTTP_PORTS to 8080 making the container listen on port 8080 by default.

You should also be aware that Swagger normally isn't available in a container, because Swagger by default only is available when running in development environments. A container is not considered development by default.

So to run your container and have access to Swagger, you should run your container using a command that looks something like

docker run --rm -d -e ASPNETCORE_ENVIRONMENT=Development -p 5000:80 test

You should then be able to access your webapi on http://localhost:5000/ and have Swagger available.

Upvotes: 4

Krishna Sonune
Krishna Sonune

Reputation: 21

I See what's the issue, you must be missing ASPNETCORE_URLS argument in your Docker file that's why your external requests are not able to hit to the container port, refer the below docker file steps for your project

FROM mcr.microsoft.com/dotnet/sdk:8.0 as base

COPY . /home

RUN dotnet restore /home/gemini.csproj
RUN dotnet publish /home/gemini.csproj -o publish

FROM mcr.microsoft.com/dotnet/sdk:8.0
WORKDIR /app
COPY --from=base /publish /app/

EXPOSE 55002
ENV ASPNETCORE_URLS=http://+:5000
CMD [ "dotnet", "gemini.dll" ]

Upvotes: 0

T M
T M

Reputation: 1139

For me ASPNETCORE_URLS was not working and the reason was that it was overriden by UseUrls that was getting the url from my appsettings: "Urls": "http://localhost:5000"

Even when i commented out the UseUrls() in the Program.cs it was still picking up the url from the appsettings.json automatically!

I changed the value in my appsettings.json from: "Urls": "http://localhost:5000" to "Urls": "http://+:5000" and now my app is accessible to any port i forward it to,

Assuming we run a new container publishing the port: -p 5001:5000 then the api will be accessible at localhost:5001 from my browser

Upvotes: 0

Related Questions