Publishing aspnet core web app to linux

Step 1 : Publish your project to a proper directory

On researching a subfolder under /var seems to be a good candidate. So, create a suitable subfolder and copy the published app files to it. For future reference lets assume we have copied the app to /var/myproject folder.

Step 2: Configure reverse proxy

> sudo apt-get install nginx
> sudo service nginx start

update /etc/nginx/sites-available/default to

server {
    listen 80;
    location / {
        proxy_pass http://localhost:<port_number>;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

the <port_number> is by default 5000 for kestrel, which you could have set a custom port as part of configuration.

>sudo nginx -t  # verify config syntax
>sudo nginx -s reload  # reload the config

Step 3 : Configure web app as a service for automatic startup and failure recovery

create service definition file

>sudo nano /var/myproject/web-myproject.service
[Unit]
Description=MyProject web app

[Service]
WorkingDirectory=/var/myproject
ExecStart=/usr/bin/dotnet /var/myproject/myproject.dll
Restart=always
RestartSec=10  # Restart after 10 seconds if it crashes
SyslogIdentifier=dotnet-web-myproject
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

Manage the service

>sudo systemctl enable /var/myproject/web-myproject.service
# the above command will automatically create the symbolic link  /etc/systemd/system/web-myproject.service

# Start the service and verify that it is running
>sudo systemctl start web-myproject.service
>sudo systemctl status web-myproject.service
# above command should report Active: active (running)

# Tail the service log
>sudo journalctl --unit web-myproject.service --follow

Stopping and Starting Service

# Stop service
>sudo systemctl stop web-myproject.service
>sudo systemctl status web-myproject.service

# Restart the service
>sudo systemctl start web-myproject.service
>sudo systemctl status web-myproject.service

Thats it! make sure you are able to browse your app, and have a nice time.

References

  1. Host ASP.NET Core on Linux with Nginx | Microsoft Docs
  2. NGINX for ASP.NET Core In-Depth - Muhammad Rehan Saeed
  3. Publishing an ASP.NET Core website to a cheap Linux VM host - Scott Hanselman
comments powered by Disqus