Specify the port of an ASP.NET 5 app when launching from Systemctl service

Published on

Systemctl is a tool for controlling the state of services running on your server.

We can use Systemctl to automatically launch a .NET application when our Linux server boots. Or even to restart the application after a predetermined time if it crashes.

I recently wanted to start my ASP.NET 5 application on a specific port. Doing this via the command line can be easily achieved with a command like

dotnet /var/www/myapp/myapp.dll urls=http://localhost:5002

My assumption was that we could just do the same thing in Systemctl, with a line like

ExecStart=/usr/bin/dotnet /var/www/myapp/myapp.dll urls=http://localhost:5002

However this did not work. And instead, you will likely receive an error message.

The correct way

The correct way to start an ASP.NET 5 app on a custom port with Systemctl is to use the ASPNETCORE_URLS environment variable.

Start by opening your service file.

sudo nano /etc/systemd/system/myapp.service

Then set the environment variable with a line like Environment=ASPNETCORE_URLS=http://localhost:5002.

The whole file will look something like the following.

[Unit]
Description=My dotnet 5 application

[Service]
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/dotnet /var/www/myapp/myapp.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=myapp
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
# If you need to run multiple services on different ports set the ports environment variable here:
Environment=ASPNETCORE_URLS=http://localhost:5002

[Install]
WantedBy=multi-user.target

Once this is done, we will will need to enable and then start the service.

sudo systemctl enable myapp.service sudo systemctl start myapp.service

Then check to make sure that it’s running okay with the status command.

sudo systemctl status myapp.service


Article Categories: # linux # asp.net # systemctl
Date Published: Jun 27, 2021

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.

IT Asset Management

Our friends at AssetPad are building a complete online solution for managing the IT assets within your organisation. With barcodes and documentation tools.