Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 44 ยท Releases and Deployment

Deploying to Servers, Containers and Static Hosting

Deploy from a pipeline to a server over SSH, a container host, GitHub Pages or Kubernetes, authenticate to clouds with OIDC and meet the GitOps idea.

Building and testing are only half of continuous delivery. The other half is getting the result onto something that runs it. In practice, "deploy" means one of a handful of patterns: copy files to a server, run a new container image on a host, publish a static site, or tell a cluster what you want running. Each needs a way for the pipeline to prove who it is, and each can be done well or badly.

This lesson shows the common patterns with read-only GitHub Actions examples, explains how OpenID Connect (OIDC) lets a pipeline authenticate to a cloud without a stored password, and introduces GitOps, where a controller continuously reconciles a cluster with a Git repository. The strategies behind rollouts are in Deployment Strategies.

None of the servers, registries or clusters below exist on this site, so all configuration is read-only. The TryIt blocks are stand-ins in JavaScript: a reconcile loop that makes "actual" state match "desired" state (the heart of Kubernetes and GitOps), and a checker for an OIDC trust rule.

Pattern 1: deploy to a server over SSH

The oldest approach: the pipeline logs in to a server and updates the application. It works for a single virtual machine and teaches the ideas clearly.

YAML
name: deploy
on:
  push:
    branches: [main]

concurrency:
  group: deploy-production
  cancel-in-progress: false      # never cancel a deploy halfway

permissions:
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm run build

      - name: Prepare SSH
        env:
          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          KNOWN_HOSTS: ${{ vars.DEPLOY_KNOWN_HOSTS }}
        run: |
          install -m 700 -d ~/.ssh
          printf '%s\n' "$SSH_KEY" > ~/.ssh/id_deploy
          chmod 600 ~/.ssh/id_deploy
          printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts

      - name: Upload build and switch release
        env:
          HOST: ${{ vars.DEPLOY_HOST }}
        run: |
          RELEASE="/srv/app/releases/${GITHUB_SHA}"
          rsync -az --delete -e "ssh -i ~/.ssh/id_deploy" dist/ "deploy@${HOST}:${RELEASE}/"
          ssh -i ~/.ssh/id_deploy "deploy@${HOST}" \
            "ln -sfn ${RELEASE} /srv/app/current && sudo systemctl reload app"

Points worth copying:

  • concurrency with cancel-in-progress: false means only one deploy runs at a time and a newer push waits instead of killing a running deploy.
  • known_hosts is pinned, so the job cannot be fooled by a man-in-the-middle. Never disable host key checking just to make an error go away.
  • Releases live in folders named by commit SHA and current is a symbolic link. Switching the link is almost instant and atomic, and rolling back is pointing the link at the previous folder.
  • The SSH key is a deploy-only key with no other access, stored as an environment secret, so only the production environment can read it (see Environments, Approvals and Deployments).

Pattern 2: build an image, run it on a host

Modern deployments ship a container image instead of loose files. The pipeline builds the image once, pushes it to a registry under an immutable tag (the commit SHA), and the host pulls exactly that image. The build steps are covered in Building and Pushing Docker Images; the Docker basics are in the Docker tutorial.

flowchart LR
    G["Git push"] --> CI["Pipeline: test and build image"]
    CI --> R["Registry<br/>app:3f2a91c"]
    CI --> D["Deploy step"]
    D --> H["Host or cluster<br/>pulls app:3f2a91c"]

The image is built once and promoted by tag, so what you tested is what you run.

For a single Docker host, the deploy step can just run docker compose pull && docker compose up -d on the server over SSH, with the image tag injected from the pipeline:

YAML
      - name: Deploy image
        env:
          HOST: ${{ vars.DEPLOY_HOST }}
          IMAGE: ghcr.io/acme/web:${{ github.sha }}
        run: |
          ssh -i ~/.ssh/id_deploy "deploy@${HOST}" \
            "cd /srv/web && IMAGE=${IMAGE} docker compose up -d --pull always"

Managed container services (cloud container platforms) have a command or action for "update this service to use this image"; the pipeline calls it after authenticating with OIDC, which we meet next. Never deploy the mutable tag latest to production: you will not know what is running, and rollback becomes guesswork.

Pattern 3: static sites on a hosting service

For a site made only of HTML, CSS and JavaScript, deploying means uploading the built files to a static host. GitHub Pages has first-class workflow support:

YAML
name: pages
on:
  push:
    branches: [main]

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm run build
      - uses: actions/upload-pages-artifact@v3
        with:
          path: dist

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - id: deployment
        uses: actions/deploy-pages@v4

Notice the split: one job builds and uploads an artifact, a second job with the github-pages environment publishes it. Other static hosts and object stores (a bucket plus a CDN) follow the same idea: build, upload files, then invalidate the CDN cache so users see the new version.

Pattern 4: Kubernetes

For Kubernetes, the pipeline hands the cluster a description of what should run. The simplest push-style deploy updates the image and waits for the rollout:

YAML
      - name: Deploy to cluster
        run: |
          kubectl apply -f k8s/
          kubectl set image deployment/web web=ghcr.io/acme/web:${GITHUB_SHA}
          kubectl rollout status deployment/web --timeout=180s

kubectl rollout status exits non-zero if the rollout does not finish in time, which fails the job and can trigger kubectl rollout undo deployment/web. Teams often use Helm or Kustomize to produce the manifests, but the idea is the same: the manifests describe the desired state, and the cluster works to make reality match it.

Helm: packaging the manifests

Plain manifests repeat themselves across environments. Helm is a package manager for Kubernetes: a chart is a folder of templates plus a values.yaml of defaults, and a release is one installed copy of a chart in a cluster. The pipeline overrides values per environment and lets Helm work out what changed:

YAML
      - name: Deploy with Helm
        run: |
          helm upgrade --install web ./charts/web \
            --namespace production --create-namespace \
            --set image.tag=${GITHUB_SHA} \
            -f values/production.yaml \
            --atomic --timeout 5m

upgrade --install creates the release the first time and upgrades it afterwards, so one command suits every run. --atomic rolls the release back automatically if it does not become healthy in time. Modern Helm (version 3 and later) talks to the cluster directly with the credentials of whoever runs it; the old in-cluster server component, Tiller, is gone, which is one less thing to secure. Run helm lint and helm template in pull requests to catch broken charts before they deploy. Charts themselves are covered in Helm basics.

AWS-native pipelines

If you deploy to AWS you can also use its own services instead of, or next to, GitHub Actions. CodePipeline orchestrates stages (source, build, deploy), CodeBuild runs the build in a managed container from a buildspec.yml, and CodeDeploy rolls an application out to EC2 instances, on-premises servers, Lambda or ECS, following an appspec.yml.

YAML
# buildspec.yml (read-only: runs inside CodeBuild)
version: 0.2
phases:
  install:
    commands:
      - npm ci
  build:
    commands:
      - npm test
      - npm run build
artifacts:
  files:
    - 'dist/**/*'
    - appspec.yml

CodeDeploy offers two deployment types. In-place stops the old version on each instance, installs the new one and starts it, so capacity dips while it runs (you can do it a batch at a time). Blue/green brings up a fresh set of instances, shifts traffic to it and keeps the old set around for fast rollback. Compare this with Elastic Beanstalk, which is a platform that creates and runs the whole environment for you with a deploy mechanism of its own: CodeDeploy only deploys onto servers you already manage. A GitHub Actions workflow can start either one through the AWS CLI after authenticating with OIDC, as described next.

Authenticating to a cloud without stored keys: OIDC

The old way to let a pipeline deploy to a cloud was to create an access key, store it as a secret, and hope it never leaks. Such keys are long-lived and are a prime target. OIDC federation replaces them:

  1. Each workflow run can request a short-lived, signed identity token from GitHub (it needs the permission id-token: write).
  2. The token contains claims such as repo and the subject (sub), for example repo:acme/web:ref:refs/heads/main or repo:acme/web:environment:production.
  3. In your cloud account you configure a trust policy: "accept tokens from GitHub whose subject matches repo:acme/web:environment:production and give them this role".
  4. The cloud exchanges the token for temporary credentials, valid for minutes.
YAML
permissions:
  id-token: write      # allow requesting the identity token
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/deploy-web
          aws-region: eu-central-1
      - run: aws s3 sync dist/ s3://acme-web-prod --delete

Other clouds (Azure, Google Cloud) offer the same pattern with their own login actions. The account ID and role above are placeholders. There is no secret in the workflow at all, so there is nothing to leak or rotate, and the trust policy limits which repositories, branches or environments may deploy. A badly written policy (for example, accepting any repo:acme/*) lets any repository in the organization assume the production role, so keep the subject tight.

JS Check an OIDC subject against a trust policy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The feature branch and the other repository are denied, which is the whole point. The real policies are written in the cloud's own language, but they compare the same claims.

GitOps: let the cluster pull

In push-style deployment, the pipeline holds credentials to the cluster and pushes changes in. GitOps flips this. The desired state of the cluster lives in a Git repository, and a controller inside the cluster (Argo CD and Flux are the well-known ones) continuously compares Git with reality and fixes any difference. A deploy becomes "merge a change to the manifests repository".

flowchart LR
    CI["CI: test, build, push image"] --> PR["Update image tag<br/>in the config repo"]
    PR --> Git["Git: desired state"]
    Ctl["Controller in cluster"] -->|"watches"| Git
    Ctl -->|"applies the difference"| K["Cluster: actual state"]

CI never touches the cluster; the controller pulls the desired state from Git.

The benefits: the cluster credentials never leave the cluster; Git history is the audit log; rollback is a git revert; and drift (someone changing the cluster by hand) is detected and corrected. The loop underneath is simple, and the next TryIt builds it: compare desired with actual, create what is missing, update what differs, delete what is extra, and repeat.

JS A reconcile loop: desired state versus actual state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Watch round 3: the controller notices the manual change and restores four replicas without any new commit. That self-healing behavior is what people mean by a reconcile loop. Compare it with an apply-once pipeline step, which fixes the cluster only at the moment it runs.

Choosing and securing a target

Target Pipeline needs Rollback Watch out for
VM over SSH deploy key, pinned host key repoint current link shared state, manual drift
Container host registry access, SSH or API redeploy previous SHA tag never use latest
Static host publish permission redeploy old artifact CDN cache invalidation
Kubernetes (push) cluster credentials rollout undo credentials in CI
Kubernetes (GitOps) write access to config repo git revert controller setup

Across all of them: use environment-scoped secrets or OIDC, require approval for production, deploy immutable versions, and end with a smoke test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the id-token: write permission allow?

    It lets the job ask GitHub for a short-lived signed token that a cloud can trust, so no long-lived key is stored.
  2. 2. Why deploy app:3f2a91c instead of app:latest?

    The latest tag moves. A tag tied to the commit is immutable, so you always know and can redeploy the exact version.
  3. 3. In GitOps, who applies changes to the cluster?

    The controller pulls the desired state from Git and corrects drift, so CI does not need cluster credentials.
  4. 4. What is the point of concurrency: cancel-in-progress: false on a deploy job?

    Cancelling a deploy halfway can leave the target in a broken state, so later runs queue behind it.
  5. 5. Which OIDC trust policy is too broad?

    A wildcard on the whole organization lets any repository assume the role. Keep the subject as narrow as possible.

Summary

  • Deployment patterns: SSH to a server, image to a container host, static files to a hosting service, manifests to Kubernetes.
  • Build once, tag by commit SHA, and promote the same artifact; avoid latest.
  • Use OIDC instead of stored cloud keys and narrow the trust policy to specific repositories, branches or environments.
  • Serialize deploys with concurrency and never cancel one in progress.
  • GitOps stores desired state in Git; a controller reconciles the cluster and corrects drift.

Infrastructure itself can be managed from a pipeline too: continue with Infrastructure as Code in Pipelines.