New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can we change the default kestrel port when using new dotnet cli ? #639

Closed
sirentek opened this Issue Feb 18, 2016 · 25 comments

Comments

Projects
None yet
@sirentek

sirentek commented Feb 18, 2016

Hi,

When I run "dotnet run", kestrel starts serving at http://localhost:5000
How can I change it to http://localhost:5050 ?

I added a hosting.json file to project directory with the following content:
{
"server": "Microsoft.AspNetCore.Server.Kestrel",
"server.urls": "http://localhost:5050"
}

This is part of my project.json:
"content": [
"wwwroot",
"Views",
"hosting.json"
],

Any ideas ?

Thanks!

@sirentek

This comment has been minimized.

Show comment
Hide comment
@sirentek

sirentek Feb 18, 2016

I have found it!


    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                        .UseServer("Microsoft.AspNetCore.Server.Kestrel")
                        .UseApplicationBasePath(Directory.GetCurrentDirectory())
                        .UseDefaultConfiguration(args)
                        .UseIISPlatformHandlerUrl()
                        .UseStartup<Startup>()
                        .UseUrls("http://localhost:5050")
                        .Build();

            host.Run();
        }
    }

sirentek commented Feb 18, 2016

I have found it!


    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                        .UseServer("Microsoft.AspNetCore.Server.Kestrel")
                        .UseApplicationBasePath(Directory.GetCurrentDirectory())
                        .UseDefaultConfiguration(args)
                        .UseIISPlatformHandlerUrl()
                        .UseStartup<Startup>()
                        .UseUrls("http://localhost:5050")
                        .Build();

            host.Run();
        }
    }

@sirentek sirentek closed this Feb 18, 2016

@joshcomley

This comment has been minimized.

Show comment
Hide comment
@joshcomley

joshcomley May 4, 2016

Really thanks for making sure you posted what you found, this helped me!

joshcomley commented May 4, 2016

Really thanks for making sure you posted what you found, this helped me!

@mikeharder

This comment has been minimized.

Show comment
Hide comment
@mikeharder

mikeharder May 4, 2016

Contributor

Note that this has been further changed in RC2: aspnet/Announcements#168

Contributor

mikeharder commented May 4, 2016

Note that this has been further changed in RC2: aspnet/Announcements#168

@robbpriestley

This comment has been minimized.

Show comment
Hide comment
@robbpriestley

robbpriestley May 19, 2016

@joshcomley yes, thank you. I used this info to solve my problem with Docker port forwarding. The step that lead me here was https://blog.rendle.io/asp-net-5-dnx-beta8-connection-refused-in-docker/

And in my case I needed to specify all zeros in the IP:
.UseUrls("http://0.0.0.0:5000") // Take that, Docker port forwarding!!!

robbpriestley commented May 19, 2016

@joshcomley yes, thank you. I used this info to solve my problem with Docker port forwarding. The step that lead me here was https://blog.rendle.io/asp-net-5-dnx-beta8-connection-refused-in-docker/

And in my case I needed to specify all zeros in the IP:
.UseUrls("http://0.0.0.0:5000") // Take that, Docker port forwarding!!!

@imkheong

This comment has been minimized.

Show comment
Hide comment
@imkheong

imkheong Jul 19, 2016

An alternative by passing arguments:
dotnet run --server.urls http://0.0.0.0:5000

imkheong commented Jul 19, 2016

An alternative by passing arguments:
dotnet run --server.urls http://0.0.0.0:5000

@moozzyk

This comment has been minimized.

Show comment
Hide comment
@moozzyk

moozzyk Jul 19, 2016

Contributor

You can also use the ASPNETCORE_URLS environment variable

Contributor

moozzyk commented Jul 19, 2016

You can also use the ASPNETCORE_URLS environment variable

@ghost

This comment has been minimized.

Show comment
Hide comment
@ghost

ghost Aug 5, 2016

For the record, the pure single-line command-line usage to run aspnet-core app with custom port goes like this:

dotnet new -t web
dotnet restore

# Unix:
ASPNETCORE_URLS="https://*:5123" dotnet run

# Windows PowerShell:
$env:ASPNETCORE_URLS="https://*:5123" ; dotnet run

# Windows CMD (note: no quotes):
SET ASPNETCORE_URLS=https://*:5123 && dotnet run

IMO, there should be a default, simple, standard command-line usage like ROR web servers as well: http://guides.rubyonrails.org/command_line.html (extremely sane and logical command line options)

dotnet run --environment Production --port 5123
dotnet run -e Production -p 5123

# just like:
bin/rails server --environment production --port 4000
bin/rails server -e production -p 4000

ghost commented Aug 5, 2016

For the record, the pure single-line command-line usage to run aspnet-core app with custom port goes like this:

dotnet new -t web
dotnet restore

# Unix:
ASPNETCORE_URLS="https://*:5123" dotnet run

# Windows PowerShell:
$env:ASPNETCORE_URLS="https://*:5123" ; dotnet run

# Windows CMD (note: no quotes):
SET ASPNETCORE_URLS=https://*:5123 && dotnet run

IMO, there should be a default, simple, standard command-line usage like ROR web servers as well: http://guides.rubyonrails.org/command_line.html (extremely sane and logical command line options)

dotnet run --environment Production --port 5123
dotnet run -e Production -p 5123

# just like:
bin/rails server --environment production --port 4000
bin/rails server -e production -p 4000
@josh-bradley

This comment has been minimized.

Show comment
Hide comment
@josh-bradley

josh-bradley Feb 16, 2017

If anyone is interested I've built a dotnet cli extension that provides the functionality described by ghost above you can check it out here https://github.com/josh-bradley/DotNetRunWeb

josh-bradley commented Feb 16, 2017

If anyone is interested I've built a dotnet cli extension that provides the functionality described by ghost above you can check it out here https://github.com/josh-bradley/DotNetRunWeb

@rclanan rclanan referenced this issue Feb 23, 2017

Merged

bug/readme #12

@TotzkePaul

This comment has been minimized.

Show comment
Hide comment
@TotzkePaul

TotzkePaul Apr 21, 2017

At least for Dotnet Core 1.1, dotnet run --server.urls "http://*:5000"

This only works if you include Microsoft.Extensions.Configuration.CommandLine and use .AddCommandLine(args)

public class Program
{
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var host = new WebHostBuilder()
            .UseConfiguration(config)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .Build();
        host.Run();
    }
}

TotzkePaul commented Apr 21, 2017

At least for Dotnet Core 1.1, dotnet run --server.urls "http://*:5000"

This only works if you include Microsoft.Extensions.Configuration.CommandLine and use .AddCommandLine(args)

public class Program
{
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var host = new WebHostBuilder()
            .UseConfiguration(config)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .Build();
        host.Run();
    }
}
@mbpakalin

This comment has been minimized.

Show comment
Hide comment
@mbpakalin

mbpakalin Apr 30, 2017

Thanks so much,
.UseUrls("http://0.0.0.0:5000") is still working.

mbpakalin commented Apr 30, 2017

Thanks so much,
.UseUrls("http://0.0.0.0:5000") is still working.

@stanislavromanov

This comment has been minimized.

Show comment
Hide comment
@stanislavromanov

stanislavromanov May 3, 2017

So there is still no --port parameter when you run it?

stanislavromanov commented May 3, 2017

So there is still no --port parameter when you run it?

@TotzkePaul

This comment has been minimized.

Show comment
Hide comment
@TotzkePaul

TotzkePaul May 3, 2017

I don't think it makes much sense to specify the port without an IP.

You could write something like this in Program.cs

public static void Main(string[] args)
{
        var config = GetServerUrlsFromCommandLine(args);
        var port = config.GetValue<int?>("port")??5000;
        
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseConfiguration(config)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
}
public static IConfigurationRoot GetServerUrlsFromCommandLine(string[] args)
{
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var serverport = config.GetValue<int?>("port") ?? 5000;
        var serverurls = config.GetValue<string>("server.urls") ?? string.Format("http://*:{0}", serverport);


        var configDictionary = new Dictionary<string, string>
        {
            {"server.urls", serverurls},
            {"port", serverport.ToString()}
        };
        
        return new ConfigurationBuilder()
            .AddCommandLine(args)
            .AddInMemoryCollection(configDictionary)
            .Build(); 
}

TotzkePaul commented May 3, 2017

I don't think it makes much sense to specify the port without an IP.

You could write something like this in Program.cs

public static void Main(string[] args)
{
        var config = GetServerUrlsFromCommandLine(args);
        var port = config.GetValue<int?>("port")??5000;
        
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseConfiguration(config)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
}
public static IConfigurationRoot GetServerUrlsFromCommandLine(string[] args)
{
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var serverport = config.GetValue<int?>("port") ?? 5000;
        var serverurls = config.GetValue<string>("server.urls") ?? string.Format("http://*:{0}", serverport);


        var configDictionary = new Dictionary<string, string>
        {
            {"server.urls", serverurls},
            {"port", serverport.ToString()}
        };
        
        return new ConfigurationBuilder()
            .AddCommandLine(args)
            .AddInMemoryCollection(configDictionary)
            .Build(); 
}
@cemana

This comment has been minimized.

Show comment
Hide comment
@cemana

cemana May 15, 2017

Hello.
ASP.NET Core. Is it possible to have 3 intances of the same app running at the same time, each one running in a different port? In the program.cs the enviroment variable does not work... I am trying to use host.Development.json, host.Production.json and host.Staging.json. I have to use only one machine for the 3 enviroments...

cemana commented May 15, 2017

Hello.
ASP.NET Core. Is it possible to have 3 intances of the same app running at the same time, each one running in a different port? In the program.cs the enviroment variable does not work... I am trying to use host.Development.json, host.Production.json and host.Staging.json. I have to use only one machine for the 3 enviroments...

@TotzkePaul

This comment has been minimized.

Show comment
Hide comment
@TotzkePaul

TotzkePaul May 15, 2017

It is possible to have 3 instances using different environment variables.

A lot will depend on how you have Program.cs and Startup.cs configured. Dotnet Core by default assumes the environment is production. How to change the environment will partially depend on the OS.

TotzkePaul commented May 15, 2017

It is possible to have 3 instances using different environment variables.

A lot will depend on how you have Program.cs and Startup.cs configured. Dotnet Core by default assumes the environment is production. How to change the environment will partially depend on the OS.

@ethanliew

This comment has been minimized.

Show comment
Hide comment
@ethanliew

ethanliew Aug 17, 2017

dotnetcore 1.1

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

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseUrls("http://0.0.0.0:1234") // change your custom port
            .Build();
}

ethanliew commented Aug 17, 2017

dotnetcore 1.1

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

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseUrls("http://0.0.0.0:1234") // change your custom port
            .Build();
}
@Nezz

This comment has been minimized.

Show comment
Hide comment
@Nezz

Nezz Sep 10, 2017

How can it be changed these days using ASP.NET Core 2.0 from the command line?

Nezz commented Sep 10, 2017

How can it be changed these days using ASP.NET Core 2.0 from the command line?

@TotzkePaul

This comment has been minimized.

Show comment
Hide comment
@TotzkePaul

TotzkePaul Sep 10, 2017

if you use @ethanliew 's answer, there shouldnt be much you need to change to make Core 2.0 work.

TotzkePaul commented Sep 10, 2017

if you use @ethanliew 's answer, there shouldnt be much you need to change to make Core 2.0 work.

@Nezz

This comment has been minimized.

Show comment
Hide comment
@Nezz

Nezz Sep 10, 2017

@TotzkePaul I was referring to a command line argument. --server.urls no longer works. Neither does --environment. Would be nice to have something that's cross-platform.

Nezz commented Sep 10, 2017

@TotzkePaul I was referring to a command line argument. --server.urls no longer works. Neither does --environment. Would be nice to have something that's cross-platform.

@Tratcher

This comment has been minimized.

Show comment
Hide comment
@Tratcher
Member

Tratcher commented Sep 10, 2017

See #1998

@scionwest

This comment has been minimized.

Show comment
Hide comment
@scionwest

scionwest Sep 11, 2017

@TotzkePaul Ideally we wouldn't have to hard-code our IP/ports. This should be 100% configurable so we don't have to recompile the app if we decide to deploy the app to a different server having a different IP.

scionwest commented Sep 11, 2017

@TotzkePaul Ideally we wouldn't have to hard-code our IP/ports. This should be 100% configurable so we don't have to recompile the app if we decide to deploy the app to a different server having a different IP.

@TotzkePaul

This comment has been minimized.

Show comment
Hide comment
@TotzkePaul

TotzkePaul Oct 10, 2017

I'll get an update on this in the next couple of days. I agree that the ports should be configurable via the command line.

I think someone deleted their comment about "0.0.0.0 vs *". I think * is all handles (IPv4 and IPv6) while 0.0.0.0 is only IPv4 address. There is something else, let me know.

  1. I think there is some issues with using the custom port with CreateDefaultBuilder in your program.cs
  2. AFAIK, IIS Express doesn't pass arguments
  3. Docker can reassign ports for you.

TotzkePaul commented Oct 10, 2017

I'll get an update on this in the next couple of days. I agree that the ports should be configurable via the command line.

I think someone deleted their comment about "0.0.0.0 vs *". I think * is all handles (IPv4 and IPv6) while 0.0.0.0 is only IPv4 address. There is something else, let me know.

  1. I think there is some issues with using the custom port with CreateDefaultBuilder in your program.cs
  2. AFAIK, IIS Express doesn't pass arguments
  3. Docker can reassign ports for you.
@TotzkePaul

This comment has been minimized.

Show comment
Hide comment
@TotzkePaul

TotzkePaul Oct 13, 2017

So I am using launchSettings.json to set pass in the variables. Each config should be separated by a space and have the format of "{Key}={Value}".

{
  "iisSettings": ...,
  "profiles": ...,
    "Main.Web": {
      "commandName": "Project",
      "launchBrowser": true,
      "commandLineArgs": "arg1=value1 --port=8080",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

As far as I know, WebHost.CreateDefaultBuilder(args) will not let use args to uses command line for configs.

In the past, your StartUp constructor looked like public Startup(IHostingEnvironment env) and was responsible for the configuration but now we can we can use Program.cs (or where ever your Main(string[] args) is located) to configure the StartUp by using public Startup(IConfiguration configuration)

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


        public static IWebHost BuildWebHost(string[] args)
        {
            var bindingConfig = new ConfigurationBuilder()
                .AddCommandLine(args)
                .Build();
            var serverport = bindingConfig.GetValue<int?>("port") ?? 5000;
            //serverurls is the socket address(es) that we will bind to by using .UseUrls(serverurls)
            var serverurls = bindingConfig.GetValue<string>("server.urls") ?? string.Format("http://*:{0}", serverport);

            var configDictionary = new Dictionary<string, string>
            {
                {"server.urls", serverurls},
                {"port", serverport.ToString()}
            };

            return new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                //ConfigureAppConfiguration sets up the configuration for Startup(IConfiguration configuration)
                .ConfigureAppConfiguration((builderContext, config) =>
                {
                    IHostingEnvironment env = builderContext.HostingEnvironment;

                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                        .AddUserSecrets<Startup>(optional: false)
                        //adds all configs from command line
                        .AddCommandLine(args) 
                        //Overrides server.urls/port configs from AddCommandLine's configs
                        .AddInMemoryCollection(configDictionary); 
                })
                .UseIISIntegration()
                .UseDefaultServiceProvider((context, options) =>
                {
                    options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
                })
                .UseStartup<Startup>()
                .UseUrls(serverurls)
                .Build();
        }
    }

This is my project where I set it to use CommandLine to pass in args.
https://github.com/TotzkePaul/MainWeb/tree/master/Main.Web

TotzkePaul commented Oct 13, 2017

So I am using launchSettings.json to set pass in the variables. Each config should be separated by a space and have the format of "{Key}={Value}".

{
  "iisSettings": ...,
  "profiles": ...,
    "Main.Web": {
      "commandName": "Project",
      "launchBrowser": true,
      "commandLineArgs": "arg1=value1 --port=8080",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

As far as I know, WebHost.CreateDefaultBuilder(args) will not let use args to uses command line for configs.

In the past, your StartUp constructor looked like public Startup(IHostingEnvironment env) and was responsible for the configuration but now we can we can use Program.cs (or where ever your Main(string[] args) is located) to configure the StartUp by using public Startup(IConfiguration configuration)

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


        public static IWebHost BuildWebHost(string[] args)
        {
            var bindingConfig = new ConfigurationBuilder()
                .AddCommandLine(args)
                .Build();
            var serverport = bindingConfig.GetValue<int?>("port") ?? 5000;
            //serverurls is the socket address(es) that we will bind to by using .UseUrls(serverurls)
            var serverurls = bindingConfig.GetValue<string>("server.urls") ?? string.Format("http://*:{0}", serverport);

            var configDictionary = new Dictionary<string, string>
            {
                {"server.urls", serverurls},
                {"port", serverport.ToString()}
            };

            return new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                //ConfigureAppConfiguration sets up the configuration for Startup(IConfiguration configuration)
                .ConfigureAppConfiguration((builderContext, config) =>
                {
                    IHostingEnvironment env = builderContext.HostingEnvironment;

                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                        .AddUserSecrets<Startup>(optional: false)
                        //adds all configs from command line
                        .AddCommandLine(args) 
                        //Overrides server.urls/port configs from AddCommandLine's configs
                        .AddInMemoryCollection(configDictionary); 
                })
                .UseIISIntegration()
                .UseDefaultServiceProvider((context, options) =>
                {
                    options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
                })
                .UseStartup<Startup>()
                .UseUrls(serverurls)
                .Build();
        }
    }

This is my project where I set it to use CommandLine to pass in args.
https://github.com/TotzkePaul/MainWeb/tree/master/Main.Web

@bidianqing

This comment has been minimized.

Show comment
Hide comment
@bidianqing

bidianqing Mar 8, 2018

install package Microsoft.Extensions.Configuration.CommandLine

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        BuildWebHost(args, configuration).Run();
    }

    public static IWebHost BuildWebHost(string[] args, IConfiguration configuration) =>
        WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(configuration)
            .UseStartup<Startup>()
            .Build();
}

dotnet WebApplication1.dll --server.urls "http://localhost:5101;http://*:5102"

firewall-cmd --permanent --zone=public --add-port=5102/tcp

firewall-cmd --reload

image

bidianqing commented Mar 8, 2018

install package Microsoft.Extensions.Configuration.CommandLine

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        BuildWebHost(args, configuration).Run();
    }

    public static IWebHost BuildWebHost(string[] args, IConfiguration configuration) =>
        WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(configuration)
            .UseStartup<Startup>()
            .Build();
}

dotnet WebApplication1.dll --server.urls "http://localhost:5101;http://*:5102"

firewall-cmd --permanent --zone=public --add-port=5102/tcp

firewall-cmd --reload

image

@ysris

This comment has been minimized.

Show comment
Hide comment
@ysris

ysris Mar 28, 2018

Solution provided by @bidianqing is still valid and works in Linux.
Thanks mate.

ysris commented Mar 28, 2018

Solution provided by @bidianqing is still valid and works in Linux.
Thanks mate.

@wjkhappy14

This comment has been minimized.

Show comment
Hide comment
@wjkhappy14

wjkhappy14 commented Jun 7, 2018

good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment