DEV Community

Cover image for Deploy Laravel with GitHub Actions over SSH
devTalk
devTalk

Posted on Originally published at dev-talk.com

Deploy Laravel with GitHub Actions over SSH

Last updated: 12 November 2026. See theupdate logat the end.

The simplest GitHub Actions deploy is "SSH in, git pull, run a few commands". It works until a migration fails halfway, or a request arrives while files are half-updated, or you need to go back to yesterday's code. This final part of the series uses a releases directory instead: each deploy builds a new directory, runs migrations, warms the caches, and only then switches a current symlink. If anything before the switch fails, the live site is untouched. It builds on Part 1 (tests) and Part 2 (caching).

I ran the deploy job's shell steps and the server script locally, against a real MySQL server, with a stand-in for ssh. The SSH transport itself, the GitHub runners and the web server were not part of that test, which is spelled out at the end.

The layout on the server

/var/www/app/
  releases/
    20261112101500-abc1234/     one directory per deploy
    20261112113000-def7654/
  shared/
    .env                        production configuration
    storage/                    logs, cache, sessions, uploads
  current -> releases/20261112113000-def7654
Enter fullscreen mode Exit fullscreen mode

Point your web server's document root at /var/www/app/current/public. Everything that must survive a deploy (.env and storage) lives in shared and is linked into each release.

One-time server setup

  1. Create a deploy user and give it write access to /var/www/app.
  2. Create shared/.env with the production settings and shared/storage with the usual Laravel subfolders (app, framework/cache, framework/sessions, framework/views, logs). Make them writable by the user that runs PHP-FPM.
  3. Generate a dedicated SSH key pair for deployments, put the public key in the deploy user's ~/.ssh/authorized_keys, and use the private key as a GitHub secret. Don't reuse your personal key.
  4. Get the server's host key line, for example from your own machine with ssh-keyscan -t ed25519 your.server.example, and compare its fingerprint with the server's before trusting it. That line becomes a secret too.

GitHub setup

Create an environment named production in the repository settings and add four secrets to it: DEPLOY_HOST, DEPLOY_USER, DEPLOY_SSH_KEY and DEPLOY_KNOWN_HOSTS. GitHub's environment docs say environment secrets are available only to jobs that use that environment, and only after its protection rules pass. You can add required reviewers there if you want a human to approve each deploy, plus a wait timer and a restriction on which branches may deploy.

The deploy job

Add this job to the workflow from Parts 1 and 2 (same file, same indentation as tests). It runs only for pushes to main, and only after the tests pass:

  deploy:
    name: Deploy to production
    needs: tests
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production

    concurrency:
      group: deploy-production
      cancel-in-progress: false

    env:
      APP_DIR: /var/www/app

    steps:
      - name: Check out code
        uses: actions/checkout@v7
        with:
          persist-credentials: false

      - name: Set up PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.4'
          coverage: none

      - name: Find the Composer cache directory
        id: composer-cache
        run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"

      - name: Cache Composer downloads
        uses: actions/cache@v6
        with:
          path: ${{ steps.composer-cache.outputs.dir }}
          key: composer-${{ runner.os }}-php8.4-${{ hashFiles('composer.lock') }}
          restore-keys: |
            composer-${{ runner.os }}-php8.4-

      - name: Install production dependencies
        run: composer install --no-dev --prefer-dist --no-interaction --no-progress --optimize-autoloader

      - name: Set up Node.js
        uses: actions/setup-node@v7
        with:
          node-version: '24'
          cache: npm

      - name: Build front-end assets
        run: |
          npm ci
          npm run build

      - name: Configure SSH
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
        run: |
          set -euo pipefail
          umask 077
          mkdir -p ~/.ssh
          printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/deploy_key
          printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
          cat > ~/.ssh/config <<EOF
          Host deploy
            HostName $DEPLOY_HOST
            User $DEPLOY_USER
            IdentityFile ~/.ssh/deploy_key
            IdentitiesOnly yes
            StrictHostKeyChecking yes
          EOF

      - name: Upload the release
        run: |
          set -euo pipefail
          RELEASE="$(date -u +%Y%m%d%H%M%S)-${GITHUB_SHA::7}"
          echo "RELEASE=$RELEASE" >> "$GITHUB_ENV"
          tar --exclude=./.git --exclude=./node_modules --exclude=./tests -czf - . \
            | ssh deploy "mkdir -p '$APP_DIR/releases/$RELEASE' && tar -xzf - -C '$APP_DIR/releases/$RELEASE'"

      - name: Activate the release
        run: ssh deploy "APP_DIR='$APP_DIR' RELEASE='$RELEASE' bash -s" < deploy/activate.sh
Enter fullscreen mode Exit fullscreen mode

Points worth knowing:

  • needs: tests and the if condition mean pull requests never deploy and a failing test job blocks the deploy.
  • The job-level concurrency group has cancel-in-progress: false. Per GitHub's docs a group has at most one running and one pending run, so two quick merges queue instead of fighting over the server, and a deploy that is running is never cancelled halfway.
  • Secrets are passed through env and read as shell variables, not pasted into the script text with ${{ }}. That keeps secret values out of the generated script.
  • The workflow builds on the runner (composer install --no-dev, npm run build) and ships the result, so the server needs PHP and Composer's output, not Node or build tools.
  • StrictHostKeyChecking yes together with the pinned known_hosts secret means the job fails if the server's key changes, instead of silently trusting a new one.
  • The upload is tar piped through ssh, so it needs nothing beyond what the runner and server already have. The release name is a UTC timestamp plus the short commit SHA, which sorts by time and tells you which commit it is.
  • set -euo pipefail is written explicitly so a failing tar in the pipe fails the step.

The activation script

Commit this as deploy/activate.sh. The job pipes it into bash -s on the server, so the script text is versioned with the code but nothing needs to be installed on the server beforehand:

#!/usr/bin/env bash
# Runs on the server. Expects APP_DIR and RELEASE in the environment.
set -euo pipefail

: "${APP_DIR:?APP_DIR is required}"
: "${RELEASE:?RELEASE is required}"

release_dir="$APP_DIR/releases/$RELEASE"
cd "$release_dir"

# Shared state lives outside the release.
ln -sfn "$APP_DIR/shared/.env" .env
rm -rf storage
ln -sfn "$APP_DIR/shared/storage" storage

# If either command fails, set -e stops here and "current" still points at the old release.
php artisan migrate --force
php artisan optimize

# Atomic switch: build the new link beside "current", then rename it over the old one.
ln -sfn "$release_dir" "$APP_DIR/current.tmp"
mv -Tf "$APP_DIR/current.tmp" "$APP_DIR/current"

php artisan reload

# Keep the five newest releases.
ls -1dt "$APP_DIR"/releases/*/ | tail -n +6 | xargs -r rm -rf
Enter fullscreen mode Exit fullscreen mode

The order is the point. Migrations and cache building happen before the switch. The switch is a rename: ln -sfn creates current.tmp beside the old link, and mv -Tf renames it over current. A bare ln -sfn target current would remove and recreate the link, leaving a brief gap. The .env link is created before php artisan optimize, because the Laravel deployment docs say that once configuration is cached the .env file is no longer loaded, so the cache has to be built with the real production values.

php artisan reload is the single reload command that the Laravel deployment docs (master branch) recommend. In Laravel 13.40 its source runs queue:restart and schedule:interrupt plus any commands that packages register, such as Octane or Reverb. On Laravel 12 and older, which don't have it, replace the line with php artisan queue:restart. Your queue workers must be run by a process monitor (Supervisor or systemd) that restarts them after they exit.

What happened when I ran it

I took the run: scripts straight out of the workflow YAML and ran them with a stand-in ssh that executes the remote command locally. The "server" was a directory with a shared .env pointing at a local MySQL database.

First deploy: migrations ran, caches were built, the link was created, and a PHP server pointed at current/public answered with the new release:

INFO  Preparing database.
Creating migration table ...................................... DONE
INFO  Running migrations.
0001_01_01_000000_create_users_table .......................... DONE
0001_01_01_000001_create_cache_table .......................... DONE
0001_01_01_000002_create_jobs_table ........................... DONE
2026_11_08_000001_add_is_admin_to_users ....................... DONE
INFO  Caching framework bootstrap, configuration, and metadata.
activate exit code: 0
current -> <ts>-abc1234
release dir has: 3 of vendor/artisan/public; tests dir: 0; .env -> app/shared/.env
storage -> app/shared/storage
tables in app_prod: 9
Enter fullscreen mode Exit fullscreen mode

A request to the PHP server started in current/public then returned:

{"app":"Laravel","users":0,"release":"<release>"}
Enter fullscreen mode Exit fullscreen mode

Second deploy with a new migration applied it and moved current to the new release:

2026_11_12_000001_add_nickname_to_users ....................... DONE
config ......................................................... DONE
events ......................................................... DONE
routes ......................................................... DONE
views ......................................................... DONE
INFO  Reloading services.
activate exit code: 0
current -> <ts>-def7654
nickname column: nickname
Enter fullscreen mode Exit fullscreen mode

A broken migration (one that throws an exception) stopped the script before the switch:

INFO  Running migrations.
boom
activate exit code: 1
current unchanged: still <ts>-def7654
releases on disk: 3 (failed release left in place)
Enter fullscreen mode Exit fullscreen mode

The site kept serving the previous release, and the job failed, which is what you want. The failed release directory stays on disk until the pruning step removes it.

Pruning: after five more deploys, only five release directories remained.

Rolling back

Rolling back is the same atomic switch, pointed at an older release. On the server (or through ssh), with the release name you want:

cd /var/www/app
ln -sfn releases/20261112101500-abc1234 current.tmp
mv -Tf current.tmp current
cd current && php artisan reload
Enter fullscreen mode Exit fullscreen mode

I ran exactly this in the test and current moved back to the first release, with the reload reporting DONE for the queue and schedule tasks:

INFO  Reloading services.
queue ......................................................... DONE
schedule ...................................................... DONE
current -> <ts>-abc1234
Enter fullscreen mode Exit fullscreen mode

Two things a rollback does not do. It doesn't undo database migrations: in my test the nickname column from the second deploy stayed in place after rolling back. And it only works while the old release still exists, which is why pruning keeps five. Treat that as a design rule: write migrations so that the previous release's code still works with the new schema (add columns before using them, remove them a release later).

Production considerations

  • PHP-FPM and OPcache. After a symlink switch, PHP-FPM may keep serving cached file paths or compiled scripts from the old release depending on your OPcache settings. Many setups reload PHP-FPM as the last deploy step (for example sudo systemctl reload php8.4-fpm with a narrow sudoers rule for that single command). I did not test this, and it depends on your opcache and realpath_cache settings, so verify it on your server.
  • Permissions. The deploy user writes the release, but PHP-FPM must be able to read it and write to shared/storage and bootstrap/cache inside the release. A release extracted by one user and served by another is a common source of 500 errors after a deploy.
  • Health check. The test app answered through the symlink. In production, add a final workflow step that requests a URL (a fresh Laravel app registers a health route at /up) and fails if it doesn't answer, so a broken release is noticed in the job and not by a user.
  • Migrations at scale. Running migrate --force before the switch means old code runs against the new schema for a moment. Long-locking migrations on big tables need separate planning.
  • Don't put secrets in the release. The tarball contains the workspace. Keep .env out of the repository, as the starter's .gitignore does.

Common mistakes

  • Building the config cache before linking .env, so production runs with the wrong values.
  • Using ln -sfn directly on current and calling it atomic.
  • Calling env() outside config files; with a cached config it returns null for .env values (the Laravel deployment docs warn about this).
  • Letting a pull request deploy because the if condition is missing.
  • Skipping host key pinning and accepting any host key.
  • Forgetting to restart queue workers, so they keep running the old code.

Alternatives

  • Deployer (a PHP deployment tool) or a hosted service such as Envoyer implement the same releases-and-symlink idea with more features. I did not test any of them here.
  • Managed platforms. The Laravel docs say that Laravel Cloud handles reloading services automatically, so the reload step isn't needed there.
  • Containers. If you deploy Docker images, the release directory idea is replaced by image tags and a rolling update. That is a different pipeline, not a variation of this one.

Related Dev Talk articles

Frequently asked questions

Why build on the runner and not on the server?

The server then needs no Node, no build tools and no access to package registries, and the code that was tested is the code that is shipped. The trade-off is uploading vendor with every release.

Do I need downtime or maintenance mode?

Not for the switch itself, which is a rename. If a particular migration can't safely run while old code is serving traffic, put the app in maintenance mode around that deploy.

How do I deploy from a tag instead of a branch?

Change the on: trigger and the if condition to match the tag, and keep the rest. An environment's deployment branch and tag rules can restrict which refs may deploy.

Where does the first release get its database?

From shared/.env. Create the database and user once; migrate --force creates the tables.

Update log

  • 12 November 2026: first version.
  • To recheck on each update: the Laravel deployment page (optimize, reload), the major versions of checkout, setup-php, cache and setup-node, and GitHub's environment protection rules.

Sources


Originally published on DEV Talk.

Top comments (0)