Why does aspnet core start on port 80 from within

2020-02-23 05:04发布

问题:

TL;DR: Why does an aspnet core app run on port 80 from within a Docker image, but 5000 outside a docker image.

Elaborate

I went through the aspnet core / docker tutorial found here: https://docs.microsoft.com/en-us/dotnet/core/docker/building-net-docker-images

Half way through the page, I start the application with the following as prescribed:

dotnet run

Among other things, this prints this:

Now Listening on: http://localhost:5000

Great. That is what I expected. The next thing in the tutorial is to start the exact same application from within a Docker image.

docker build -t aspnetapp .
docker run -it --rm -p 5000:80 --name aspnetcore_sample aspnetapp

This results in

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

Wait. Wat? Why is the aspnet core app running on port 80? It was running on port 5000 when I ran it directly from the machine. There were no configuration file changes.

I suspect that it has something to do with the base docker images, but am not yet skilled enough in docker to track this down.

回答1:

The microsoft/aspnetcore-build container builds on top of the microsoft/aspnetcore container. The dockerhub page for that says:

A note on ports

This image sets the ASPNETCORE_URLS environment variable to http://+:80 which means that if you have not explicity set a URL in your application, via app.UseUrl in your Program.cs for example, then your application will be listening on port 80 inside the container.

So this is the container actively setting the port to 80. You can override it, if you want, by doing this in your Dockerfile:

ENV ASPNETCORE_URLS=http://+:5000

Also, it is worth noting that because of the docker command you are using, you will still be able to access the application at http://localhost:5000 whether you are running the application directly or in a container.



回答2:

If you are using .NET Core 2.2 or higher, then you should to use another image: mcr.microsoft.com/dotnet/core/aspnet:2.2. In that case specifying ENV ASPNETCORE_URLS=http://+:5000 does not help. You still can force app to listen to port 5000 by using UseUrls("http://*:5000") in Programs.cs file.



回答3:

without dockerfile you can set any port out of the docker container. (.net core 3.1) with docker args

docker run -it --rm -p 5000:80 -p 5001:443 -e ASPNETCORE_HTTPS_PORT=https://+:5001
           -e ASPNETCORE_URLS=http://+:5000 --name aspnetcore_sample aspnetapp

more details:

https://github.com/dotnet/dotnet-docker/blob/17c1eec582e84ba9cbea5641cd9cc13fe1a41c39/samples/run-aspnetcore-https-development.md#L85

https://github.com/dotnet/dotnet-docker/blob/5926a01d44bd47b6202ba71e30f9faa08fad1aec/samples/run-in-sdk-container.md#L109