Mastering AI agents
Deploy to an Oracle Cloud Free Instance with GitHub Actions (2026): Push to main and It's Live (SSH, systemd, Caddy)
Deploy a Node.js service to an Oracle Cloud Always Free Ampere A1 instance with GitHub Actions: a dedicated SSH key, pinned known_hosts, separate releases, a systemd restart and health checks before keeping the new version, with Caddy handling HTTPS.
Kelvin Wang · · 13 min read
Key points
- For a small site, a GitHub-hosted runner that SSHes into the box is the simplest setup; a self-hosted runner suits private repos with heavy builds.
- Use a dedicated deploy key. restrict and command= limit the SSH entry point, but uploaded code still runs with the deploy user's permissions.
- Switch current only after the build succeeds, and prune releases only after the health check passes. Keep current and previous available for rollback.
- Oracle's Ubuntu images have iptables rules on the instance on top of the OCI security list. Open 80 and 443 in both, or Caddy can't get a certificate.
I have an A1 instance in Tokyo (ap-tokyo-1) that already runs Claude Code Remote Control under systemd. The example below explores another use for it: deploying a website after a push to main. It assumes a Node.js service on Ubuntu that needs a build step and runs continuously.
This deployment flow is based on the official documentation and has not been run on that instance. Replace <...>, example.com and myapp with your own values, and adapt the build command, entry point and health endpoint to your project.
GitHub-hosted runner over SSH, or a self-hosted runner on the box?
A GitHub Actions job runs on a machine called a runner. There are two common ways to deploy to your own server: use a runner GitHub provides and SSH into your server at the end, or install a runner on your server so the job runs there.
| Item | GitHub-hosted runner + SSH | Self-hosted runner on the box |
|---|---|---|
| Where the job runs | GitHub's machine, then SSH into the server | Your server |
| What the server exposes | SSH (port 22) reachable from GitHub | The runner connects to GitHub; the server needs outbound HTTPS on 443 |
| Cost | Free for public repos; private repos use the plan's included minutes, then pay per minute | Free on GitHub's side; you pay for the machine |
| Public repos | Fine | GitHub recommends private repos only |
| Maintenance | GitHub maintains the runner | You keep the OS and software updated |
| Good for | Small sites, occasional deploys | Private repos, heavy builds, or jobs that need files on the server |
This post uses the first option, so there is no runner process to maintain on the server. GitHub updates its runner IP list weekly and advises against using those ranges as an allowlist 4. This setup uses a dedicated deploy account and SSH key. Self-hosted runners are a poor fit for public repos because a pull request from a fork may run the contributor’s code on your runner 6.
Go deeper GitHub Actions Self-Hosted Runner on Oracle Cloud Free ARM (2026): arm64 CI Setup Guide If you want jobs to run on the A1 instance itself, start here.What are the moving parts?
Only a few pieces are involved:
- The
deployuser. A Linux account used only for deploys, separate from theubuntuaccount you log in with. - The deploy key. A new SSH key. The private half lives in a GitHub Actions secret; the public half goes in
deploy’sauthorized_keys. - The deploy script.
/usr/local/bin/deploy-myapp, the fixed entry point for this SSH key. - Release directories. Builds start in
/srv/myapp/stagingand move toreleaseswhen complete.currentpoints to the live release;previousretains the preceding release that passed its health check. - The systemd service.
myapp.servicestarts your app fromcurrent. - Caddy. Listens on 80 and 443, gets HTTPS certificates automatically and forwards requests to
localhost:3000.
The build runs on the server, not on GitHub’s machine. A1 is ARM, while GitHub’s default ubuntu-latest is x64 4; if your dependencies include native modules, building on the server gives you the right architecture.
How do you create a deploy-only account on the server?
This is a dedicated deployment account with a restricted SSH entry point and limited sudo permissions. Builds and application code still run as that user; the account is not a sandbox.
-
Create the
deployuser and directories:sudo adduser --disabled-password --gecos "" deploy sudo mkdir -p /srv/myapp/releases /srv/myapp/staging /srv/myapp/shared sudo chown -R deploy:deploy /srv/myapp sudo -u deploy touch /srv/myapp/shared/.env sudo chmod 600 /srv/myapp/shared/.envsharedholds what every release needs, such as.env. It lives outside the release directories, so switching releases doesn’t lose it. Create an empty.enveven if you have no variables yet; the systemd service reads it. -
Generate a deploy key on your own computer. Don’t reuse the key you log in with:
ssh-keygen -t ed25519 -f deploy_key -N "" -C "github-actions-deploy"This creates
deploy_key(private) anddeploy_key.pub(public). -
Add the public key to
deploy’sauthorized_keyswith restrictions in front:sudo -u deploy mkdir -p -m 700 /home/deploy/.ssh sudo -u deploy tee /home/deploy/.ssh/authorized_keys > /dev/null <<'EOF' restrict,command="/usr/local/bin/deploy-myapp" ssh-ed25519 AAAA...(contents of deploy_key.pub) github-actions-deploy EOF sudo chmod 600 /home/deploy/.ssh/authorized_keysrestrictturns off port, agent and X11 forwarding and PTY allocation.command=fixes the command run after login; the client’s command is passed inSSH_ORIGINAL_COMMAND8. This does not make a leaked key harmless. The script accepts uploaded code, and bothnpm ciandnpm run buildexecute package scripts 18. Anyone holding the key can run code asdeploy, read.envand even change the account’s ownauthorized_keys. Protect it as a credential for that account. -
Allow
deployto restart and stop this one service. Stopping is needed if the first deployment fails and there is no old release to restore. Create a sudoers file withvisudo, keeping dots out of its name because sudo skips files whose names contain.10:sudo visudo -f /etc/sudoers.d/deploy-myappAdd these two lines. Listing the arguments limits each permission to that exact command and argument list 10:
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp.service deploy ALL=(root) NOPASSWD: /usr/bin/systemctl stop myapp.service
How do you write a deploy script you can always roll back?
The workflow packs the commit into a tar stream, sends it over SSH and passes the SHA as the “command”. Because of command=, the SHA goes into SSH_ORIGINAL_COMMAND instead of being executed by the shell. The script checks its format; it does not verify that the uploaded archive matches that commit. This setup assumes you trust the people and code allowed to deploy.
After building, the script switches releases and restarts the service. The app must return HTTP 200 from /health when it is ready to serve requests. Each request has a 2-second timeout, with at most 10 attempts and a 2-second pause after each failure 22. If the new release fails, the script attempts to restore the old one and reports the deployment as failed. flock prevents two deploys from changing releases at once 23.
#!/usr/bin/env bash
set -euo pipefail
APP=/srv/myapp
SHA=${SSH_ORIGINAL_COMMAND:-}
[[ $SHA =~ ^[0-9a-f]{40}$ ]] || { echo "expected a commit SHA" >&2; exit 2; }
exec 9>"$APP/deploy.lock"
flock -n 9 || { echo "another deploy is running" >&2; exit 1; }
healthy() {
local status
for attempt in {1..10}; do
if status=$(curl -sS --max-time 2 -o /dev/null -w '%{http_code}' \
http://127.0.0.1:3000/health) && [[ $status == 200 ]]; then
return 0
fi
sleep 2
done
return 1
}
BUILD=$(mktemp -d "$APP/staging/${SHA:0:7}.XXXXXX")
trap 'rm -rf -- "$BUILD"' EXIT
tar -x -f - -C "$BUILD"
cd "$BUILD"
rm -f .healthy
ln -s "$APP/shared/.env" .env
npm ci
npm run build
OLD=$(readlink -f "$APP/current" || true)
REL=$APP/releases/$(date -u +%Y%m%d%H%M%S)-${BUILD##*/}
mv "$BUILD" "$REL"
cd "$APP"
ln -sfn "$REL" "$APP/current"
if ! sudo /usr/bin/systemctl restart myapp.service || ! healthy; then
echo "new release failed; attempting recovery" >&2
if [[ -n $OLD && -f "$OLD/.healthy" ]]; then
ln -sfn "$OLD" "$APP/current"
if sudo /usr/bin/systemctl restart myapp.service && healthy; then
rm -rf -- "$REL"
echo "previous release restored" >&2
else
echo "rollback failed; inspect the service logs" >&2
fi
elif sudo /usr/bin/systemctl stop myapp.service; then
rm -f "$APP/current"
rm -rf -- "$REL"
echo "no healthy previous release; service stopped" >&2
else
echo "could not stop the failed service; inspect it manually" >&2
fi
exit 1
fi
touch "$REL/.healthy"
if [[ -n $OLD && -f "$OLD/.healthy" ]]; then
ln -sfn "$OLD" "$APP/previous"
fi
PREVIOUS=$(readlink -f "$APP/previous" || true)
kept=0
while IFS= read -r candidate; do
[[ -f "$candidate/.healthy" ]] || continue
[[ $candidate == "$REL" || $candidate == "$PREVIOUS" ]] && continue
kept=$((kept + 1))
if (( kept > 3 )); then
rm -rf -- "$candidate"
fi
done < <(find "$APP/releases" -mindepth 1 -maxdepth 1 -type d | LC_ALL=C sort -r)
echo "deployed $SHA -> $REL"
Install Node.js, npm, curl and util-linux, which provides flock, on the server first. Make sure they are available to deploy in a noninteractive shell. Save the script as deploy.sh and install it as root so deploy cannot directly edit the entry script:
sudo install -o root -g root -m 755 deploy.sh /usr/local/bin/deploy-myapp
A failed build leaves current alone and removes the staging directory; the error output remains in the Actions log. Only a release that passes the health check gets a .healthy marker. Pruning preserves current, previous and the latest 3 other marked releases. If rollback also fails, the script keeps the releases for investigation and never prints success. After a power loss or a forced process termination, check the symlinks, service and remaining directories manually. This rollback does not reverse changes to shared files or databases.
How does the systemd service follow current?
Save this as /etc/systemd/system/myapp.service:
[Unit]
Description=myapp
After=network.target
[Service]
Type=exec
User=deploy
WorkingDirectory=/srv/myapp/current
EnvironmentFile=/srv/myapp/shared/.env
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=2
TimeoutStartSec=30
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable myapp.service
WorkingDirectory follows current when the service starts. Set ExecStart to your app’s actual start command and bind it to 127.0.0.1:3000. Type=exec reports failures to execute the program, but does not mean HTTP is ready; the deployment still needs the /health check 19. This step only enables the service. The first deployment starts it.
How do you get automatic HTTPS with Caddy?
-
Point DNS at the server. At your DNS provider, set the A record for
example.comto the server’s reserved IP (<SERVER_IP>). Caddy’s automatic certificates need the domain to point at the server, ports 80 and 443 reachable from outside, and a writable data directory 13. -
Open 80 and 443 in the OCI security list. Console → Networking → Virtual Cloud Networks → your VCN → the security list your subnet uses → Add Ingress Rules: source CIDR
0.0.0.0/0, IP protocol TCP, destination port range80, then again with44311. -
Open 80 and 443 in iptables on the instance too (see the callout below).
-
Install Caddy with the official Ubuntu commands. The package starts Caddy as a systemd service named
caddy14:sudo apt install --yes debian-keyring debian-archive-keyring apt-transport-https curl curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list sudo chmod o+r /usr/share/keyrings/caddy-stable-archive-keyring.gpg sudo chmod o+r /etc/apt/sources.list.d/caddy-stable.list sudo apt update sudo apt install caddy -
Edit
/etc/caddy/Caddyfileto send the domain to your service 15:example.com { reverse_proxy localhost:3000 } -
Reload the config. Reload rather than stop, so the site doesn’t go down 16:
sudo systemctl reload caddy
By default Caddy redirects HTTP to HTTPS and renews certificates automatically 13. A static site can use root /srv/myapp/current/dist with file_server 17. Caddy runs as the caddy user, which needs read access to the output directory 16. Adapting this deployment script for static files also means removing the myapp restart and stop commands and checking a known file through Caddy. Deleting a single restart line is not enough.
How do you make GitHub trust only your server?
The first time SSH connects to a host, it asks whether to trust the host key. Nobody can answer on GitHub’s machine, and the usual shortcut is to turn the check off, which means an impostor server would go unnoticed. Store the host key as a secret instead and require a match.
-
Get the host key from the server itself, over your normal SSH session, which you already trust:
cat /etc/ssh/ssh_host_ed25519_key.pub -
Build a known_hosts line: the server IP, the key type and the key, separated by spaces 8:
<SERVER_IP> ssh-ed25519 AAAA...ssh-keyscan -t ed25519 <SERVER_IP>prints the same line, but it doesn’t verify the key, so only trust it after comparing it with the file on the server 9. -
Save three values as Actions secrets in the repo, under Settings → Secrets and variables → Actions, or with
gh secret set3:gh secret set DEPLOY_SSH_KEY < deploy_key gh secret set DEPLOY_KNOWN_HOSTS --body "<SERVER_IP> ssh-ed25519 AAAA..." gh secret set DEPLOY_HOST --body "<SERVER_IP>"Then delete
deploy_keyfrom your computer; you can always generate a new one. Workflows triggered from forks don’t receive these secrets 3.
What does the GitHub Actions workflow look like?
Save this in the repo as .github/workflows/deploy.yml:
name: Deploy
on:
push:
branches: [main]
concurrency:
group: deploy-production
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Set up SSH
env:
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
run: |
install -m 700 -d ~/.ssh
printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
- name: Ship and deploy
env:
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
run: |
git archive --format=tar HEAD | ssh -i ~/.ssh/deploy_key \
-o IdentitiesOnly=yes -o StrictHostKeyChecking=yes \
"deploy@$DEPLOY_HOST" "$GITHUB_SHA"
A few details matter:
concurrencyqueues deploys. Only one run in the group is active at a time, with at most one more pending; a newer run replaces the pending one 7.cancel-in-progress: falsekeeps a running deploy from being killed halfway through a build.StrictHostKeyChecking=yesrejects unknown hosts. If the server’s key doesn’t match the secret, SSH fails before any code is sent.- The trailing
$GITHUB_SHAis never executed. It’s an argument for the deploy script; because ofcommand=, the server only ever runsdeploy-myapp.
Once setup is complete, push a commit to main and open the run in the Actions tab. deployed <SHA> -> ... means the build, restart and local /health check passed. Open the site from outside the server as well to check DNS, HTTPS and actual pages. A passing health endpoint does not verify every feature.
How do you roll back a bad deploy?
If a problem shows up after a release goes live, there are two ways back:
-
Switch to the previous release right away. Disable the automatic deployment workflow in Actions first. Disabling it does not cancel existing runs, so also cancel pending deployments and wait for all running deployments to finish 24. Keep the workflow disabled while rolling back, checking the site and preparing the Git revert. Then log in with your normal account and check that the chosen release has a
.healthymarker before pointingcurrentback and restarting:ls -1 /srv/myapp/releases sudo -u deploy ln -sfn /srv/myapp/releases/<previous-release> /srv/myapp/current sudo systemctl restart myapp.serviceNo rebuild is needed, but check
/healthand the site after the restart. Switching code does not undo changes to shared data or databases. -
Revert the bad commit in Git. Run
git revert <bad-commit>locally and check the fix. If you disabled the workflow in the previous step, keep it disabled until the rollback checks are complete and the revert is ready to push. Then re-enable the workflow and push to main to deploy the fix through the normal process 24.
The first one only stops the bleeding. The next push to main would deploy the broken code again, so follow up with the second.
Should you add environment approvals?
GitHub environments add a gate to deploys. Once a job declares environment: production, it waits until that environment’s protection rules pass, and it can’t read the environment’s secrets until then 1. Common rules:
- Required reviewers. Up to 6 people or teams; one approval lets the deploy run, and you can stop people from approving runs they triggered themselves 1.
- Deployment branches. Only main may deploy to production.
- Wait timer. Hold the job for a few minutes before it starts.
Adding it is one line in the job:
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
Check your plan first. On GitHub Free, environments can only be configured for public repos. Pro and Team support environments and deployment branches in private repos, but required reviewers and wait timers are public-repo only on Free, Pro and Team 2. Free private repos also lack branch protection; that requires a supported paid plan 20. branches: [main] only filters the workflow trigger. It does not provide review approval or prevent someone with write access from pushing code.
FAQ
Can I add from= to the deploy key to allow only GitHub’s IPs?
from= can restrict the source address 8, but GitHub updates its runner IP list weekly and advises against using the standard hosted runner ranges as an allowlist 4. If you need a fixed source address, consider a larger runner with a static IP or a self-hosted runner. restrict and command= do not remove the risk of a leaked deploy key being used to run arbitrary application code.
Can I build on GitHub’s machine and ship only the output?
Yes. Remove the two build lines from the deploy script and have the workflow build first, then send the packed output. Mind the architecture: ubuntu-latest is x64, and GitHub also offers an arm64 ubuntu-24.04-arm runner 4; if the output contains native code, build on the same architecture as the server.
What if current doesn’t exist on the first deploy?
ln -sfn creates current. In this setup, the service is enabled first and started by the initial deployment. If its health check fails, there is no old release to restore, so the script attempts to stop the service and remove current, then exits with a failure status.
What if the server’s IP changes?
Update DNS, DEPLOY_HOST and DEPLOY_KNOWN_HOSTS together. An OCI reserved public IP can be kept and reassigned to a rebuilt instance 21, but it does not preserve the SSH host key. If that key changes, verify the new public key through a trusted channel before updating DEPLOY_KNOWN_HOSTS. Do not disable verification just to make the workflow pass 89.
Sources
- 1. Managing environments for deployment
- 2. Deployments and environments
- 3. Using secrets in GitHub Actions
- 4. GitHub-hosted runners reference
- 5. Self-hosted runners
- 6. Adding self-hosted runners
- 7. Control the concurrency of workflows and jobs
- 8. sshd(8)
- 9. ssh-keyscan(1)
- 10. Sudoers Manual
- 11. Install Apache and PHP on an Ubuntu Instance
- 12. Best Practices for Your Compute Instance
- 13. Automatic HTTPS
- 14. Install
- 15. reverse_proxy (Caddyfile directive)
- 16. Keep Caddy Running
- 17. file_server (Caddyfile directive)
- 18. Scripts
- 19. systemd.service
- 20. About protected branches
- 21. Public IP Addresses
- 22. curl man page
- 23. flock manual
- 24. Disabling and enabling a workflow
Kelvin Wang
Electrical engineer building tools with AI agents, sharing hands-on notes on engineering and investing.
More about me