Deploy .Net App to Linux with Github Actions
In this post, I will be going over how to deploy a .Net app to a Linux server using Github Actions with a Username and password.
Please Note: This is for demo purpose/Development a better solution is to use SSH Keys which is industry standard, see Generating SSH Keys for GitHub Actions Deployment. Please checkout Setup a linux web server to deploy a blazor app from your machine.
Lets start by talking about why we would want to use Github Actions to deploy our app.
- Automation: Github Actions allows you to automate the deployment process, reducing manual effort and potential errors.
- Integration: It integrates seamlessly with your GitHub repository, allowing you to trigger deployments on code changes.
- Flexibility: You can customize the deployment workflow to suit your needs, including running tests before deployment.
1. Setting Up Your GitHub Repository
Create a new GitHub repository or use an existing one for your .NET app.
Now navigate to the settings tab and store your username, password, and host. When you do you will be asked to create an environement. We will use that name next in the ymal file.
2. Creating the GitHub Actions Workflow
In your repository, create a new directory called .github/workflows and add a new file named deploy.yml.
name: Deploy to Linux Server
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
environment: github_environment_name # Replace with your environment name
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: '8.0.x'
- name: Publish .NET app
run: dotnet publish -c Release -o ./publish
- name: Install sshpass
run: sudo apt-get update && sudo apt-get install -y sshpass
- name: Copy files to server
env:
SSHPASS: ${{ secrets.SSH_PASSWORD }}
run: sshpass -e scp -o StrictHostKeyChecking=accept-new -r ./publish/* ${{ secrets.USERNAME }}@${{ secrets.HOST }}:~/myapp
- name: Restart service
env:
SSHPASS: ${{ secrets.SSH_PASSWORD }}
run: sshpass -e ssh -o StrictHostKeyChecking=accept-new -o ${{ secrets.USERNAME }}@${{ secrets.HOST }} 'sudo systemctl restart yourapp.service'
Be sure to update the environment name under deploy job. Change the dotnet version as needed to match your project.
Now check the code into your main branch and the workflow will be automatically ran. You can now go to the Action Tab on github and see the build running.