How can I change Kestrel (AspNetCore) listening port by environment variables in netcore3.1
Asked Answered
D

1

12

I have aspnetcore3.1 project, and I want to set custom port for Kestrel (other than default 5000). I can possibly do it in Program.cs by adding

Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.ConfigureKestrel(options =>
    {
        options.ListenLocalhost(80);
    });
    webBuilder.UseStartup<Startup>();
})

But this cannot be applied to my case, so wondered, how can this be done by environment variable?

Dare answered 10/2, 2020 at 13:59 Comment(0)
D
20

There are multiple ways to achieve this as documented here.

  1. ASPNETCORE_URLS environment variable.
  2. --urls command-line argument.
  3. urls host configuration key.
  4. UseUrls extension method.

To achieve this using an environment variable, simply create an environment variable called ASPNETCORE_URLS and set the value to the URL you'd like to use

Typically this would be http://+:<port> or https://+:<port>

Another method which, at the time of writing this answer, isn't described above is via the hostsettings.json file.

You can configure the URL & Port by creating a hostsettings.json configuration file and adding the urls key, then add hostsettings.json to your IConfigurationBuilder when building your WebHostBuilder.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-3.1#override-configuration

Here is the code snippet from the link, in case this link ever goes dead.

Create your hostsettings.json file containing the urls key with your value(s)

{
    urls: "http://*:5005"
}

Register hostsettings.json in your IConfigurationBuilder

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile("hostsettings.json", optional: true)
            .AddCommandLine(args)
            .Build();

        return WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:5000")
            .UseConfiguration(config)
            .UseStartup<Startup>();
    }
}
Donkey answered 10/2, 2020 at 14:26 Comment(3)
--URLs argument works for me on .NET 3.1 on Ubuntu, tnx.Soidisant
@Soren worth bearing in mind that this only works when args is passed to CreateDefaultBuilder, should you ever find yourself in a scenario where this stops working post-refactoring/cleanup.Donkey
@Donkey I'm pretty sure this little comment has saved me hours of head scratching. Thanks!Cheer

© 2022 - 2024 — McMap. All rights reserved.