Blog

Deploy ASP.NET Core 10 to Magalu Cloud with GitHub Actions

  • aspnet-core
  • dotnet-10
  • magalu-cloud
  • postgresql
  • github-actions
  • ef-core
Abstract illustration of a row of pipeline stages sending small packets into a server rack, which connects over a dashed private link to a database cylinder, on a dark blue grid.

This tutorial takes a small ASP.NET Core 10 API from a GitHub repository to a Magalu Cloud virtual machine, with its data in Magalu’s managed PostgreSQL (DBaaS). Every push to main builds a self-contained release, applies pending EF Core migrations, restarts the app under systemd behind nginx, and fails the run if /healthz can’t reach the database. The connection string lives in GitHub Secrets and lands on the VM in a root-only file. It never touches the repository or a command line.

Architecture diagram. In GitHub, a production environment holds the secrets VM_SSH_PRIVATE_KEY, VM_SSH_KNOWN_HOSTS and DB_CONNECTION_STRING plus the variables VM_HOST, VM_USER and HEALTHCHECK_URL, which feed an ubuntu-24.04 runner. The runner publishes the app, builds a migration bundle, connects to the VM over SSH on port 22, and finally calls /healthz over HTTP on port 80. Inside Magalu Cloud region br-se1, the VM notes-vm (public 203.0.113.10, private 10.0.0.15, security group allowing inbound 22 and 80) runs nginx on port 80 proxying to Kestrel on 127.0.0.1:5000, managed by the systemd unit notes-api.service, which loads /etc/notes-api/notes-api.env with mode 600. The efbundle reads the same file. Both connect on port 5432 to DBaaS PostgreSQL 17 at private address 10.0.0.40, whose security group only allows 5432 from 10.0.0.15/32. Internet clients reach the VM at http://203.0.113.10/.

What was tested, and what wasn’t. I ran the app, the migration bundle, the deploy script and the nginx site (nginx 1.26.3) locally against PostgreSQL 17.11 on a Linux box, with the SSH hop simulated and systemctl stubbed out. The unit file passes systemd-analyze verify, but I didn’t run it under a real systemd. The workflow passes actionlint and the scripts pass shellcheck. The mgc commands were checked against the Magalu Cloud documentation and the parser of mgc 0.67.0 as of 2026-10-29, but I did not run them against a Magalu account. Places where Magalu’s docs are silent are marked Not covered by Magalu’s docs. All IPs, IDs and passwords below are placeholders.

The complete sample (app, migrations, unit file, nginx site, scripts and workflow) is in magalu-deploy-sample.zip.

Goal and prerequisites

You’ll end up with http://203.0.113.10/healthz returning Healthy after each deploy. You need:

  • A Magalu Cloud account and the mgc CLI (tested parser: 0.67.0), logged in with mgc auth login. The default region is br-se1.
  • .NET SDK 10.0.402 locally (runtime 10.0.14), EF Core 10.0.14, Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3, and the dotnet-ef 10.0.14 local tool.
  • A GitHub repository where you can create environments, secrets and variables.
  • PostgreSQL on DBaaS supports versions 15, 16 and 17; this post uses 17. The VM runs Ubuntu 24.04 LTS.

Step 1: Create a deploy key and register it

Create a dedicated key pair that only the workflow uses, then register the public half in your Magalu profile (names are limited to 45 characters):

ssh-keygen -t ed25519 -N "" -C notes-deploy -f ./notes-deploy
mgc profile ssh-keys create --name notes-deploy --key "$(cat ./notes-deploy.pub)"

The private key goes into a GitHub secret in step 7. Don’t reuse a personal key: you want to be able to revoke this one without locking yourself out.

Step 2: Security groups for the VM

Security groups deny anything without a matching rule, and Magalu’s security group guide warns that a custom group with no egress rule to 0.0.0.0/0 stops the instance from booting. The docs don’t list what the default rules contain, so I create the group with --skip-default-rules (CLI reference) and add every rule explicitly with rules create:

mgc network security-groups create --name notes-vm-sg --skip-default-rules
VM_SG=<vm-sg-id>   # ID printed by the previous command

mgc network security-groups rules create --security-group-id "$VM_SG" \
  --direction egress --ethertype IPv4 --remote-ip-prefix 0.0.0.0/0
for port in 22 80; do
  mgc network security-groups rules create --security-group-id "$VM_SG" \
    --direction ingress --ethertype IPv4 --protocol tcp \
    --port-range-min "$port" --port-range-max "$port" --remote-ip-prefix 0.0.0.0/0
done
mgc network security-groups rules list --security-group-id "$VM_SG"

Not covered by Magalu’s docs: the CLI marks --protocol as optional, but the docs don’t say that omitting it means “all protocols”. Check the egress rule in the console or the list output before you create the VM.

Port 22 is open to the world because GitHub-hosted runners use too many IP ranges for an allowlist, and GitHub itself advises against relying on them. The default Magalu images disable password and root login, so only the key works. If that trade-off bothers you, see the next steps.

Step 3: Create the VM

List the images and machine types in your region first; cloud-ubuntu-24.04 LTS and BV2-2-20 are the names used in Magalu’s own Terraform examples, but availability can change:

mgc virtual-machine images list --name "cloud-ubuntu-24.04 LTS"
mgc virtual-machine instances create --name notes-vm \
  --image.name "cloud-ubuntu-24.04 LTS" --machine-type.name BV2-2-20 \
  --ssh-key-name notes-deploy --network.associate-public-ip=true \
  --network.interface.security-groups "[{\"id\":\"$VM_SG\"}]"
mgc virtual-machine instances get --id <vm-id>

The instances create reference documents these flags. From the get output, note the public IPv4 (here 203.0.113.10) and the private IPv4 (here 10.0.0.15). The SSH user on Ubuntu images is ubuntu.

Step 4: Create the database and allow only the VM

DBaaS instances get a private IP only, so only resources in the same account and region can reach them. Security groups for an instance can only be set at creation; dbaas instances update has no flag for them. Create the group first:

mgc network security-groups create --name notes-db-sg --skip-default-rules
DB_SG=<db-sg-id>
mgc network security-groups rules create --security-group-id "$DB_SG" \
  --direction ingress --ethertype IPv4 --protocol tcp \
  --port-range-min 5432 --port-range-max 5432 --remote-ip-prefix 10.0.0.15/32
mgc network security-groups rules create --security-group-id "$DB_SG" \
  --direction egress --ethertype IPv4 --remote-ip-prefix 0.0.0.0/0

mgc dbaas engines list --status=ACTIVE
mgc dbaas instance-types list --status=ACTIVE --engine-id=<postgres-17-engine-id>
mgc dbaas instances create --name notes-db --user notesadmin \
  --password '<your-admin-password>' --engine-id <postgres-17-engine-id> \
  --instance-type-id <instance-type-id> --volume.size 20 --volume.type CLOUD_NVME15K \
  --security-groups "[\"$DB_SG\"]"

Not covered by Magalu’s docs: whether a DBaaS security group needs an egress rule. I added one to mirror the VM’s group; delete it if your connection tests pass without it. The admin password also lands in your shell history here, so clear it or type the command with a leading space if your shell ignores those.

When mgc dbaas instances get --instance-id <id> shows the instance as active, note its private address (here 10.0.0.40). Magalu doesn’t create an application database for you. After the VM bootstrap in step 6 installs psql, run from the VM:

psql -h 10.0.0.40 -U notesadmin -d postgres -c 'CREATE DATABASE notes;'

Not covered by Magalu’s docs: how TLS is configured on DBaaS. Npgsql’s default SSL Mode is Prefer, which uses TLS only if the server offers it. Run SHOW ssl; in that psql session; if it says on, add SSL Mode=Require to the connection string so a downgrade fails loudly.

Step 5: Read the connection string from the environment

ASP.NET Core maps __ in environment variable names to : (configuration docs), so ConnectionStrings__Default becomes GetConnectionString("Default"). appsettings.json carries no secrets; the app refuses to start without the variable:

var connectionString = builder.Configuration.GetConnectionString("Default")
    ?? throw new InvalidOperationException("ConnectionStrings__Default is not set.");

builder.Services.AddDbContext<NotesDb>(o => o.UseNpgsql(connectionString));
builder.Services.AddHealthChecks()
    .AddDbContextCheck<NotesDb>("postgres", tags: ["ready"]);
builder.Services.Configure<ForwardedHeadersOptions>(o =>
{
    o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    // nginx runs on the same VM; the default KnownProxies list already trusts loopback.
});

var app = builder.Build();
app.UseForwardedHeaders();
app.MapHealthChecks("/healthz");

AddDbContextCheck calls CanConnectAsync, so /healthz returns 503 when PostgreSQL is unreachable (health checks docs). UseForwardedHeaders goes first, as the proxy guidance requires; nginx on loopback is trusted by default.

The sample also has an IDesignTimeDbContextFactory that reads the same variable, so dotnet ef and the bundle never need a real database at build time. The csproj sets <RuntimeIdentifiers>linux-x64</RuntimeIdentifiers>, without which the bundle build fails with NETSDK1047.

Step 6: Bootstrap the VM with systemd and nginx

Run deploy/bootstrap-vm.sh once. It installs nginx and postgresql-client, creates a notes-api system user with no shell, creates /opt/notes-api/releases and a root-only /etc/notes-api, and installs the two files below. The unit follows Microsoft’s nginx guide, plus some sandboxing (excerpt; [Unit] and [Install] are in the sample):

[Service]
Type=exec
User=notes-api
Group=notes-api
WorkingDirectory=/opt/notes-api/current
ExecStart=/opt/notes-api/current/Notes.Api
# Read by systemd as root before switching to User=; file is root:root 600.
EnvironmentFile=/etc/notes-api/notes-api.env
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://127.0.0.1:5000
Restart=always
RestartSec=5
KillSignal=SIGINT
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true

Kestrel only listens on loopback; nginx is the public face:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    location / {
        proxy_pass         http://127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection $connection_upgrade;
        proxy_set_header   Host $host;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

(The $connection_upgrade map is in the sample file.) Because systemd reads EnvironmentFile= as root, the service user can’t read the file back from disk.

Step 7: Secrets and variables in a GitHub environment

Create an environment named production and add secrets for things that grant access, variables for things that don’t:

Name Kind Example
VM_SSH_PRIVATE_KEY secret contents of ./notes-deploy
VM_SSH_KNOWN_HOSTS secret output of ssh-keyscan -t ed25519 203.0.113.10
DB_CONNECTION_STRING secret see below
VM_HOST variable 203.0.113.10
VM_USER variable ubuntu
HEALTHCHECK_URL variable http://203.0.113.10/healthz

The connection string uses the database’s private address:

Host=10.0.0.40;Port=5432;Database=notes;Username=notesadmin;Password=<your-admin-password>

Pinning known_hosts stops the runner from trusting whatever answers on that IP. Compare the scanned key’s fingerprint with the one you accepted on your first manual SSH login. Required reviewers on the environment are available on Free, Pro and Team plans for public repositories only.

Step 8: The workflow

Actions are pinned to commit SHAs, as GitHub’s security guide recommends. The build half:

on:
  push:
    branches: [main]
  workflow_dispatch:
concurrency:
  group: deploy-production
  cancel-in-progress: false
permissions:
  contents: read
jobs:
  deploy:
    runs-on: ubuntu-24.04
    environment: production
    env:
      RELEASE: ${{ github.sha }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
        with:
          dotnet-version: '10.0.x'
      - name: Publish app and build migration bundle
        run: |
          dotnet tool restore
          dotnet publish src/Notes.Api -c Release -r linux-x64 --self-contained -o out
          dotnet ef migrations bundle --project src/Notes.Api -r linux-x64 \
            --self-contained --configuration Release -o out/efbundle --force
          tar -czf "notes-api-$RELEASE.tgz" -C out .

The deploy half writes the environment file through stdin, so the connection string never appears in a command line or in the VM’s shell history:

      - name: Configure SSH
        env:
          SSH_KEY: ${{ secrets.VM_SSH_PRIVATE_KEY }}
          KNOWN_HOSTS: ${{ secrets.VM_SSH_KNOWN_HOSTS }}
        run: |
          install -d -m 700 ~/.ssh
          printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
      - name: Write environment file on the VM
        env:
          TARGET: ${{ vars.VM_USER }}@${{ vars.VM_HOST }}
          DB_CONNECTION_STRING: ${{ secrets.DB_CONNECTION_STRING }}
        run: |
          printf 'ConnectionStrings__Default=%s\n' "$DB_CONNECTION_STRING" |
            ssh "$TARGET" 'sudo install -o root -g root -m 600 /dev/stdin /etc/notes-api/notes-api.env'
      - name: Upload release and run deploy script
        env:
          TARGET: ${{ vars.VM_USER }}@${{ vars.VM_HOST }}
        run: |
          scp "notes-api-$RELEASE.tgz" deploy/deploy.sh "$TARGET:/tmp/"
          # shellcheck disable=SC2029  # RELEASE should expand on the runner
          ssh "$TARGET" bash /tmp/deploy.sh "$RELEASE"
      - name: Health check
        env:
          HEALTHCHECK_URL: ${{ vars.HEALTHCHECK_URL }}
        run: |
          curl --fail --silent --show-error --retry 10 --retry-delay 3 \
            --retry-all-errors "$HEALTHCHECK_URL"

Step 9: Run migrations with a bundle

A migration bundle is a single executable that applies pending migrations. On the VM it beats the alternatives: no SDK or source code on the server (unlike dotnet ef database update), no race between instances or schema changes hidden in app startup (unlike Database.Migrate()), and it runs under the deploy script, so a failed migration stops the release before traffic moves. The heart of deploy.sh, which also turns on invariant globalization for the bundle to match the app’s InvariantGlobalization csproj setting:

sudo bash -c '
  set -euo pipefail
  while IFS= read -r line; do if [[ -n "$line" ]]; then export "$line"; fi; done < "$1"
  export DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
  DOTNET_BUNDLE_EXTRACT_BASE_DIR="$(runuser -u notes-api -- mktemp -d)"
  export DOTNET_BUNDLE_EXTRACT_BASE_DIR
  trap "rm -rf \"$DOTNET_BUNDLE_EXTRACT_BASE_DIR\"" EXIT
  runuser -u notes-api -- "$2/efbundle"
' _ "$envfile" "$dir"

sudo ln -sfn "$dir" "$base/current"
sudo systemctl restart notes-api.service

Each release is extracted to /opt/notes-api/releases/<sha>; current is a symlink, and the script keeps the five newest releases so a rollback is one ln -sfn and a restart, as long as the older build still works with the newer schema. Running the bundle a second time prints No migrations were applied. The database is already up to date.

Verify it

After the first green run:

curl -i http://203.0.113.10/healthz          # HTTP/1.1 200 OK ... Healthy
curl -X POST http://203.0.113.10/notes -H 'Content-Type: application/json' -d '{"text":"hi"}'
ssh ubuntu@203.0.113.10 'sudo journalctl -u notes-api -n 20 --no-pager'

Locally, stopping PostgreSQL flipped /healthz to 503 Unhealthy and the workflow’s curl --fail exited with code 22, which is the behavior you want from the last step.

Troubleshooting

  • No DbContext named 'Release' was found. In dotnet ef, -c means --context. Use --configuration Release.
  • DOTNET_BUNDLE_EXTRACT_BASE_DIR is not set. Self-contained single-file apps extract to a home-based directory, and notes-api has no home. The script sets a temporary one.
  • Failed executing DbCommand on the first migration. EF looks for __EFMigrationsHistory before creating it; the error is logged and then handled. Later runs don’t show it.
  • The VM never finishes booting. Check that its security group has the IPv4 egress rule to 0.0.0.0/0.
  • /healthz returns 503 or the bundle times out. Confirm the DB rule allows the VM’s private IP, that Host= is the DB’s private address, and follow Magalu’s connection troubleshooting page. If /healthz is slow under load rather than failing, check for sync database calls, as in the Npgsql thread-pool starvation post.
  • The app fails to parse the connection string. EnvironmentFile= treats quotes and backslashes specially; pick a password without them.

Trade-offs and next steps

  • systemd’s own docs discourage environment variables for secrets, because child processes inherit them. LoadCredential= plus AddKeyPerFile configuration is the stricter option.
  • Close port 22 to the internet with a self-hosted runner or a larger GitHub runner with a static IP, then tighten the ingress rule to that address.
  • Put TLS in front of nginx before real traffic arrives, and add UseHsts once HTTPS works.
  • Replace the admin user in the connection string with a role that owns only the notes database. Magalu’s DBaaS docs don’t cover role management, so check what your admin user is allowed to grant.