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?
2
Answers
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.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
You should then be able to access your webapi on http://localhost:5000/ and have Swagger available.
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