GitHub Actions for an existing Laravel app · Part 2 of 3
Building the release
A production stage of the Dockerfile, an nginx image, a production Compose file, and the job that pushes both images to GitHub's registry tagged with the commit. For a classic server, the job that packs a release.
By Abhishek Fouzdar
Part 1 made every pull request prove itself. This part builds the thing that gets deployed, in a job that runs after those checks pass on main. For a Docker server that is a production image, pushed to GitHub's container registry and tagged with the commit. For a classic server it is a release: vendor/ without dev packages, the built assets, and the code, packed into one archive. Part 3 puts either one on the server.
The one idea to hold on to
Nothing is built on the server. The runner builds the release, the server receives it, and the server never runs Composer, npm or a compiler. That is what makes a deploy the same every time, makes it fast, and makes a rollback possible: a release that was built once can be put back as it was.
The Docker series built an image whose code came from a bind mount, which is right for development and wrong for production. A production image has the code inside it, and a production container has no bind mounts at all.
The Docker path
Two more stages in the Dockerfile
The Dockerfile from the Docker series ends with a dev stage. Two more go after it:
# ---------- assets: build the frontend once, in a Node stage that ships nothing.
FROM node:22-alpine AS assets
WORKDIR /build
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
COPY resources/ resources/
COPY vite.config.js ./
RUN npm run build
# ---------- prod: the code, production dependencies and built assets baked in.
# No bind mount, no entrypoint install, no Composer at runtime. Settings override the
# dev php.ini with the production one.
FROM base AS prod
COPY --chown=www-data:www-data . .
COPY --from=assets --chown=www-data:www-data /build/public/build public/build
RUN composer install --no-dev --no-interaction --prefer-dist --no-progress --optimize-autoloader \
&& composer clear-cache \
&& rm -f /usr/local/etc/php/conf.d/zz-xdebug.ini
COPY docker/php/php-prod.ini /usr/local/etc/php/conf.d/zz-app.ini
COPY --chmod=755 docker/php/entrypoint-prod.sh /usr/local/bin/app-entrypoint-prod
USER www-data
ENTRYPOINT ["app-entrypoint-prod"]
CMD ["php-fpm"]
The assets stage is a Node image that builds the frontend and is then discarded; only its public/build folder is copied into the final image, so production ships no Node, no node_modules, and no source stylesheets. The package.json files are copied before the rest so that npm ci is cached by Docker until a dependency changes.
The prod stage starts from the same base as dev, so PHP, its extensions and the user ids are identical to development. It copies the code in, copies the built assets over it, installs production dependencies, and swaps the PHP settings. --chown matters: without it the files belong to root and storage/ is unwritable once the process drops to www-data.
.dockerignore decides what COPY . . includes. The Docker series' file already excludes .git, vendor, node_modules and every .env. Add tests and deploy, the folder of server scripts from part 3; neither belongs in the image.
Production PHP settings
docker/php/php-prod.ini:
; Production settings. Errors go to the log, never to the browser; OPcache trusts the
; files it has compiled because a release never changes files in place.
memory_limit = 256M
upload_max_filesize = 25M
post_max_size = 25M
display_errors = Off
log_errors = On
expose_php = Off
opcache.enable = 1
opcache.validate_timestamps = 0
opcache.memory_consumption = 192
opcache.max_accelerated_files = 20000
realpath_cache_size = 4096K
realpath_cache_ttl = 600
The line that matters is opcache.validate_timestamps = 0. In development OPcache checks whether a file changed before using its compiled version. In production the files never change, because a release is a new image, so the check is wasted work on every request. Turn it off and PHP compiles each file once per container. The flip side is in part 3: a container must be restarted to see new code, and the deploy does exactly that.
The production entrypoint
docker/php/entrypoint-prod.sh:
#!/bin/sh
# Production entrypoint. The code and vendor/ are in the image; what is not known until
# the container starts is the environment, so the config, route and view caches are
# built here, once per container, before php-fpm, the worker or the scheduler runs.
set -e
php artisan optimize --no-interaction >/dev/null
exec docker-php-entrypoint "$@"
The development entrypoint installed vendor/ when it was missing. The production one has vendor/ already and does one thing instead: php artisan optimize, which caches the configuration, routes, views and events. That cannot happen at build time, because the config cache bakes in the environment, and the environment is only known when the container starts. Then exec hands over to the image's normal entrypoint, which runs whatever command the container was given: php-fpm, queue:work or schedule:work.
The web image
In development, nginx read public/ through the bind mount. In production there is no mount, so nginx needs its own copy of public/, taken from the app image. docker/nginx/Dockerfile:
# The production web image: nginx with the app's public/ baked in, so it can serve the
# static files itself and only pass .php to the app container.
ARG APP_IMAGE=app:prod
FROM ${APP_IMAGE} AS app
FROM nginx:stable-alpine
COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=app /var/www/html/public /var/www/html/public
A two-stage build: the first stage is the app image, named so that the second can copy from it. APP_IMAGE is a build argument because the build job in the workflow passes the exact tag it just built. nginx serves the static files in public/build itself and passes .php requests to the app container, with the same default.conf as development.
Try it locally
docker build --target prod -f docker/php/Dockerfile -t app:prod .
docker build --build-arg APP_IMAGE=app:prod -f docker/nginx/Dockerfile -t web:prod .
docker run --rm app:prod ls public/build # assets manifest.json
docker run --rm app:prod php -i | grep validate_timestamps # => Off
The app image is about 290 MB, most of it PHP and its extensions; the web image about 100 MB. Not small, but each deploy only transfers the layers that changed, and the code layer is a few megabytes.
The production Compose file
compose.prod.yaml, next to compose.yaml:
# Production. Images come from the registry; nothing is built or bind-mounted here.
# Copy this file and a production .env to the server; the deploy workflow does the rest.
#
# docker compose -f compose.prod.yaml pull
# docker compose -f compose.prod.yaml up -d --remove-orphans --wait
# docker compose -f compose.prod.yaml exec app php artisan migrate --force
name: app
x-app: &app
image: ${APP_IMAGE:?set APP_IMAGE in .env}
env_file: .env
volumes:
# The only writable state the app keeps: uploads, logs, cache files.
- storage:/var/www/html/storage
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
restart: always
logging:
driver: json-file
options: { max-size: "10m", max-file: "3" }
services:
app:
<<: *app
healthcheck:
test: ["CMD-SHELL", "php -r 'exit(file_exists(\"vendor/autoload.php\") ? 0 : 1);'"]
interval: 10s
timeout: 5s
retries: 3
queue:
<<: *app
command: php artisan queue:work --tries=3 --max-time=3600 --sleep=3
scheduler:
<<: *app
command: php artisan schedule:work
web:
image: ${WEB_IMAGE:?set WEB_IMAGE in .env}
depends_on:
- app
ports:
- "127.0.0.1:${APP_HOST_PORT:-8080}:80"
restart: always
db:
image: mysql:8.4
environment:
MYSQL_DATABASE: ${DB_DATABASE}
MYSQL_USER: ${DB_USERNAME}
MYSQL_PASSWORD: ${DB_PASSWORD}
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
volumes:
- dbdata:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "root", "-p${DB_PASSWORD}"]
interval: 5s
timeout: 5s
retries: 20
start_period: 20s
restart: always
redis:
image: redis:7-alpine
volumes:
- redisdata:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20
restart: always
volumes:
dbdata:
redisdata:
storage:
Compared with the development file: images instead of builds, one named volume for storage/ instead of a bind mount of the project, restart: always, log rotation, no node, no mailpit, no published database port, and web published on 127.0.0.1 only. The server's own nginx or Caddy sits in front of that port and handles TLS; the stack does not need to know about it.
APP_IMAGE and WEB_IMAGE come from the production .env, and the :? makes Compose refuse to start without them rather than guess. Part 3 shows how the deploy keeps them pointed at the commit it just built.
The build job
.github/workflows/deploy.yml in full. The build job is this part's subject; the deploy job is part 3's.
# Every push to main: run the CI workflow, build the production images, push them to the
# GitHub Container Registry tagged with the commit, then tell the server to pull that
# tag and restart. One deploy at a time; a second push waits rather than racing.
#
# Run it by hand with a sha to roll back (or forward) to an image that is already in
# the registry: the checks and the build are skipped and the server just switches.
name: Deploy
on:
push:
branches: [main]
workflow_dispatch:
inputs:
sha:
description: 'Commit sha (12 characters) of an earlier deploy to switch the server to. Leave empty to build and deploy main.'
required: false
default: ''
concurrency:
group: deploy-production
cancel-in-progress: false
permissions:
contents: read
packages: write
jobs:
checks:
if: ${{ !inputs.sha }}
uses: ./.github/workflows/ci.yml
build:
name: Build and push images
if: ${{ !inputs.sha }}
needs: checks
runs-on: ubuntu-latest
outputs:
sha: ${{ steps.meta.outputs.sha }}
steps:
- uses: actions/checkout@v7
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
run: echo "sha=${GITHUB_SHA::12}" >> "$GITHUB_OUTPUT"
- name: app image
uses: docker/build-push-action@v7
with:
context: .
file: docker/php/Dockerfile
target: prod
push: true
tags: |
ghcr.io/${{ github.repository }}/app:${{ steps.meta.outputs.sha }}
ghcr.io/${{ github.repository }}/app:latest
cache-from: type=gha
cache-to: type=gha,mode=max
- name: web image
uses: docker/build-push-action@v7
with:
context: .
file: docker/nginx/Dockerfile
build-args: APP_IMAGE=ghcr.io/${{ github.repository }}/app:${{ steps.meta.outputs.sha }}
push: true
tags: |
ghcr.io/${{ github.repository }}/web:${{ steps.meta.outputs.sha }}
ghcr.io/${{ github.repository }}/web:latest
deploy:
name: Deploy to the server
needs: build
# Runs after a successful build, or straight away when a sha was given by hand.
if: ${{ !cancelled() && (needs.build.result == 'success' || inputs.sha) }}
runs-on: ubuntu-latest
environment: production
env:
SHA: ${{ inputs.sha || needs.build.outputs.sha }}
steps:
- name: SSH key and pinned host key
run: |
mkdir -p ~/.ssh && chmod 700 ~/.ssh
printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy && chmod 600 ~/.ssh/deploy
printf '%s\n' "${{ vars.DEPLOY_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
- name: Pull and restart on the server
# The key is restricted to one script on the server (command= in authorized_keys).
# The run's token lets the server pull the private images; it expires with the run.
run: |
ssh -i ~/.ssh/deploy -p "${{ vars.DEPLOY_PORT }}" \
"${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }}" \
"deploy ${{ secrets.GITHUB_TOKEN }} $SHA"
It triggers on a push to main, which includes every merged pull request. The checks job is one line: it runs the whole CI workflow from part 1 as a job, through workflow_call. build needs it, so a failed check on main means no image and no deploy.
permissions is where the registry access comes from. Every run has a GITHUB_TOKEN that is created for the run and expires with it; packages: write lets that token push to the GitHub Container Registry under the repository's name. No account token, no personal access token, nothing to rotate. docker/login-action logs in with it, docker/build-push-action builds and pushes.
Two tags per image. ${{ github.repository }} expands to owner/repo, so the images land at ghcr.io/owner/repo/app and ghcr.io/owner/repo/web, next to the repository under its Packages tab. The first tag is the first twelve characters of the commit sha, computed once in the meta step and used everywhere after; the second is latest, which is there for people and never for the deploy. Part 3 explains why.
cache-from and cache-to with type=gha store the image layers in GitHub's cache between runs. A change that only touches PHP code reuses the layers with the extensions and the dependencies; the build took 52 seconds for the example app with a warm cache, and most of that is pushing.
The web image is built second with APP_IMAGE pointing at the app image that was just pushed, by its sha tag, so the two always match.
Images in a private repository are private: the registry asks for a token to pull them. That is the one wrinkle the server has to deal with, and part 3 does.
The classic path
A server with PHP, nginx and MySQL installed natively does not need an image. It needs the same things an image contains, in a folder: the code, a production vendor/, and the built assets. The job that makes that folder is the release job in .github/workflows/deploy-classic.yml; the switch job and the server side are part 3.
# The deploy for a server that runs PHP, nginx and MySQL natively, no Docker. The runner
# builds the release (production vendor/ and built assets), tars it, and streams it over
# SSH to a restricted script that unpacks it next to the previous releases, migrates,
# and switches one symlink. Same CI gate as the Docker deploy.
#
# Run it by hand with a sha to switch the server back to one of the releases it still
# has (the last five): no checks, no build, just the symlink.
name: Deploy (classic)
on:
push:
branches: [main]
workflow_dispatch:
inputs:
sha:
description: 'Commit sha (12 characters) of a release still on the server to switch to. Leave empty to build and deploy main.'
required: false
default: ''
concurrency:
group: deploy-classic
cancel-in-progress: false
permissions:
contents: read
jobs:
checks:
if: ${{ !inputs.sha }}
uses: ./.github/workflows/ci.yml
release:
name: Build and release
if: ${{ !inputs.sha }}
needs: checks
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v7
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
coverage: none
- id: composer-cache
run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"
- uses: actions/cache@v5
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: composer-${{ hashFiles('composer.lock') }}
restore-keys: composer-
- name: Production dependencies
run: composer install --no-dev --no-interaction --prefer-dist --no-progress --optimize-autoloader
- uses: actions/setup-node@v7
with:
node-version: '22'
cache: npm
- run: npm ci --no-audit --no-fund
- run: npm run build
- name: Pack the release
# Everything the server needs and nothing it must not have: no git history, no
# node_modules (assets are built), no tests, no .env of any kind.
run: |
tar -czf /tmp/release.tgz \
--exclude=.git --exclude=.github --exclude=node_modules --exclude=tests \
--exclude='.env*' --exclude='storage/logs/*' --exclude=docker --exclude=deploy \
--exclude='compose*.yaml' \
.
ls -la /tmp/release.tgz
- name: SSH key and pinned host key
run: |
mkdir -p ~/.ssh && chmod 700 ~/.ssh
printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy && chmod 600 ~/.ssh/deploy
printf '%s\n' "${{ vars.DEPLOY_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
- name: Ship it
run: |
ssh -i ~/.ssh/deploy -p "${{ vars.DEPLOY_PORT }}" \
"${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }}" \
"release ${GITHUB_SHA::12}" < /tmp/release.tgz
switch:
name: Switch to an earlier release
if: ${{ inputs.sha }}
runs-on: ubuntu-latest
environment: production
steps:
- name: SSH key and pinned host key
run: |
mkdir -p ~/.ssh && chmod 700 ~/.ssh
printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy && chmod 600 ~/.ssh/deploy
printf '%s\n' "${{ vars.DEPLOY_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
- name: Switch
run: |
ssh -i ~/.ssh/deploy -p "${{ vars.DEPLOY_PORT }}" \
"${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }}" \
"switch ${{ inputs.sha }}"
The release job is the lint job and the assets job from part 1, combined and pointed at production: composer install --no-dev --optimize-autoloader, npm ci, npm run build. Then tar packs the project with a list of exclusions that says what a release is not. No .git, no tests, no node_modules (the assets are built), none of the Docker files, and no .env of any kind, because the production environment lives on the server and only there. The archive for the example app is 4.9 MB.
The PHP version on the runner should match the server's. vendor/ built with PHP 8.4 contains packages that Composer selected for 8.4, and a server running 8.3 may find one it cannot load. Pin php-version to what php -v says on the server.
The last step streams the archive over SSH as standard input to the server's release script, which part 3 shows. The runner never has shell access to the server, and the server never has access to GitHub.
Checkpoint
You should have:
- for Docker: the
assetsandprodstages,php-prod.ini,entrypoint-prod.sh,docker/nginx/Dockerfile,compose.prod.yaml, and a localdocker build --target prodthat succeeds; - for a classic server: nothing new yet, apart from knowing what the release contains;
- one of the two workflow files, committed. It will fail at its last job until part 3, which is expected: there is no server to talk to yet.
Part 3 sets up the server, the key that can only deploy, the first deploy, the rollback, and the rules the team runs under.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
2 / 3