Setting Up a CI/CD Pipeline for a Web Project with GitHub Actions

A web CI/CD pipeline with GitHub Actions: tests, a single build and artifact, environment approval, secrets and OIDC, deployment to a release directory over SSH, and GitLab CI equivalents.
Technical summary
Technology
GitHub Actions, YAML, OIDC, SSH, rsync, Node.js, GitLab CI/CD
Topic
Test, build and deployment automation for a web project
Level
Intermediate
Prerequisites
  • A web project hosted on GitHub
  • SSH access to the target server or a cloud account
  • Knowing the project’s test and build commands
In this article7 sections

In a web project where code is copied to the server by FTP or by hand with scp, there’s often no answer to a simple question: which commit is running in production? Tests are skipped in a hurry, local changes pile up on the server and rollbacks are done by guesswork. A CI/CD pipeline runs the same steps in the same order on every change and removes this uncertainty. Below we set up a workflow in GitHub Actions that runs tests, builds, stores an artifact and deploys over SSH; we cover secrets, environment protections and OIDC, and finally give the GitLab CI equivalents.

Stages of a CI/CD pipeline

A well-designed pipeline answers one question at each stage and stops if the answer is negative:

  1. Validation: Does the code build; do linting and type checks pass?
  2. Testing: Do unit and integration tests pass?
  3. Build and packaging: The output to be released (static files, a Docker container image) is produced once and versioned.
  4. Deployment: The same output is sent first to the test environment and, after approval, to production.
  5. Post-deployment check: Do the health endpoint and key pages respond?

The basic principle: build once, deploy the same thing everywhere. Rebuilding on the production server brings the risk that the tested output and the released output differ; if a dependency version changed in between, the error shows up for the first time in production. Setting up the test environment consistently with production is a separate topic, explained in the staging environment setup guide.

Sample workflow structure

The workflow below is for a Node.js-based web project and goes in the .github/workflows/ci-cd.yml file. On pull requests, only tests run; on a push to the main branch, the build and production deployment kick in too. The @v4 tags in the example are commonly used versions; since new major versions can be released with runtime updates to the actions, check the current major version on each action’s release page. The Node.js version in the build job must be the same as the version running on the server.

name: ci-cd

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node: [22, 24]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm test

  build:
    needs: test
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run build
      - uses: actions/upload-artifact@v4
        with:
          name: web-dist
          path: dist/
          retention-days: 7

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: production
      url: https://www.example.com
    concurrency:
      group: deploy-production
      cancel-in-progress: false
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: web-dist
          path: dist
      - name: Configure SSH
        env:
          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
        run: |
          install -m 700 -d ~/.ssh
          printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
      - name: Upload and activate
        env:
          HOST: ${{ vars.DEPLOY_HOST }}
        run: |
          RELEASE="$(date +%Y%m%d%H%M%S)-${GITHUB_SHA::7}"
          rsync -az --delete dist/ "deploy@$HOST:/var/www/app/releases/$RELEASE/"
          ssh "deploy@$HOST" "/var/www/app/bin/activate $RELEASE"
      - name: Smoke test
        run: curl -fsS --retry 5 --retry-delay 3 https://www.example.com/healthz

Three elements in this file determine order and security: needs chains the jobs in order, and a job doesn’t run if the previous one fails; the if condition disables build and deployment on pull requests; and the permissions block at the top reduces the GITHUB_TOKEN permission given to the workflow to read-only. Default token permissions depend on the repository or organization setting; narrow them explicitly in every workflow. A broadly permissioned token is a key to write to the repository in the hands of a compromised action.

Test and build steps

npm ci does an installation that matches the package-lock.json file exactly and fails if the file and package.json don’t match; that’s why it’s preferred over npm install in CI. The cache: npm option in actions/setup-node stores the npm cache directory keyed on the lock file’s hash and restores it in later runs. For other package managers or build outputs, the actions/cache action is used with the same logic; always generate the cache key from the lock file’s hash, otherwise you test with stale dependencies. A green test, with the wrong dependencies.

A matrix (strategy.matrix) runs the same tests in parallel on several runtime versions; it’s handy for seeing compatibility with a new version before upgrading the one on the server. For integration tests that need a database, a temporary PostgreSQL or MariaDB container can be added to the job definition with a services: block; every run starts with a clean database.

The build job stores the output with actions/upload-artifact, and the deployment job retrieves the same output with actions/download-artifact. That way a single build is made after the tested job, and the deployed files are exactly the product of that build. In container-based projects, a version-tagged image is pushed to a registry instead of an artifact; how to run the image on the server is covered in the Docker Compose production deployment article.

Secrets and environment protections

GitHub keeps configuration values at three levels: organization, repository and environment. vars is used for non-sensitive values (server name, URL), and secrets for passwords and keys. Secrets are masked in logs, but masking isn’t a security boundary: a command that transforms the value (base64, splitting) can get around the mask.

The real security gate for production deployment is the environment. For an environment named production, the following can be defined:

  • Required reviewers: The job doesn’t start until the specified person or team approves. Availability of this feature in private repositories depends on your GitHub plan.
  • Branch restriction: Only runs from the main branch or specific tags can deploy to this environment.
  • Environment secrets: The production key is given only to a job that uses this environment and passes approval; test jobs never see this value.

The security mistakes found most often in workflow reviews:

  • Writing user-controlled values such as ${{ github.event.pull_request.title }} directly into run:; this is open to command injection. First assign the value to an environment variable with env: and use it quoted in the shell; the SSH step in the example follows this pattern.
  • Using third-party actions with a mutable tag (@v1). Pin unofficial actions to the full commit SHA and handle updates in a controlled way with Dependabot.
  • Checking out and running the fork’s code in the pull_request_target trigger; this trigger runs with access to secrets.

Cloud identity with OIDC

For deployment to Azure, AWS or Google Cloud, OpenID Connect can be used instead of storing a long-lived access key as a secret. The workflow receives a short-lived token signed by GitHub; on the cloud side, an identity is defined that trusts the repository, branch or environment information in this token. In a job using an environment, the token’s subject field has the form repo:org/repo:environment:production; restrict the trust relationship on the cloud side to exactly this value.

permissions:
  id-token: write
  contents: read

steps:
  - uses: azure/login@v2
    with:
      client-id: ${{ vars.AZURE_CLIENT_ID }}
      tenant-id: ${{ vars.AZURE_TENANT_ID }}
      subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}

For AWS, the aws-actions/configure-aws-credentials action assumes the same role with the role-to-assume parameter. Identity identifiers aren’t secrets; they don’t need to be stored as secrets, but permissions should be granted on the cloud side according to the principle of least privilege. Details are in the GitHub Actions documentation under “security hardening”.

Methods for deploying to a server

Method When it fits Watch out for
Release directory with SSH + rsync Your own Linux server, PHP or static site Restricted user, fixed known_hosts
Image to a registry + compose pull/up over SSH Container-based deployment The image tag must match the commit
Server-pulled model (pull) SSH can’t be opened to the server from outside An agent or scheduled task on the server
Self-hosted runner The target is on an internal network Don’t use it in public repositories
Cloud service with OIDC App Service, S3, Cloud Run, etc. Restrict the trust relationship to the environment

There are two rules for deploying over SSH. First: instead of generating the known_hosts value on the fly with ssh-keyscan in the workflow, store it as a secret with a fingerprint verified in advance; otherwise you trust whatever server intercepts the first connection. Second: the deployment user should be able to write only to the application directory, and sudo rights should be limited to the single command needed (for example a PHP-FPM reload).

The releases/ directory and activate script in the example make sure each release is uploaded to a separate directory and then activated in a single step. How to make this switch without downtime, and alternatives such as blue-green and rolling, are the subject of the zero-downtime deployment guide; here we focus on the pipeline itself.

GitLab CI equivalents

When moving the same pipeline to GitLab, the concepts largely map across; the syntax and the license tier of some features differ:

GitHub Actions GitLab CI/CD
.github/workflows/*.yml .gitlab-ci.yml
jobs and needs stages and needs
runs-on image and runner tags
on: and if: rules: and workflow:rules
actions/upload-artifact artifacts: paths
actions/cache cache: key / paths
secrets / vars CI/CD variables (protected, masked)
Environment protections Protected environments, deployment approvals
concurrency resource_group
id-token: write (OIDC) id_tokens

The decisive difference in GitLab is that protected variables are given only to jobs running on protected branches and tags; marking production keys this way provides a boundary similar to environment secrets in GitHub. For details, see the GitLab documentation.

Once set up, the pipeline needs maintenance too. Monitor slowing tests, review the cache and keep action versions up to date; a pipeline that takes twenty minutes pushes the team to take shortcuts. To add CI/CD to an existing project or move manual releases to automation, see our CI/CD and web DevOps automation service page.

Frequently asked questions

Why can’t secrets be accessed in pull requests from forks?

For security reasons, GitHub doesn’t give repository secrets to pull_request workflows triggered by pull requests opened from forks, and provides GITHUB_TOKEN as read-only. This is a deliberate protection. It’s possible to bypass this limit with pull_request_target, but checking out and running the fork’s code in this trigger can lead to secrets being compromised.

Should I use an SSH key or OIDC for deployment?

If the target is a cloud provider (Azure, AWS, Google Cloud), OIDC should be preferred; no long-lived key is stored, and a short-lived identity is generated anew on every run. For deployment to your own Linux server, an SSH key is the practical choice; tie the key to a restricted user dedicated to deployment and rotate it regularly.

How do I stop two deployments from running at the same time?

Define a concurrency group on the deployment job and leave cancel-in-progress set to false. That way the second run in the same group waits until the first finishes; a new deployment doesn’t start on top of a half-finished one. Only one pending run is kept in the group at a time; if a newer one arrives, the older pending run is cancelled, which ensures the latest commit is deployed.

Should I keep tests and deployment in the same workflow or in separate files?

In small and medium projects, keeping jobs linked with needs in a single workflow is both readable and ensures the tested artifact is the same as the deployed artifact. As the project grows, common steps can be moved to a separate file with reusable workflows (workflow_call).

Support

Contact us for support or a discovery session on this topic.

Contact form
[email protected]

Eretek Web

We build and maintain corporate websites, WordPress and CMS platforms, intranet and SharePoint portals, document management, and form and approval workflows, and keep them secure and up to date.

Knowledge Center

Other articles