Building a PHP 8.5 base image from source, with a cached GitHub workflow
Last week's php2shell scramble came down to one question for every team: how fast can we ship a patched PHP? If your base image comes from someone else, the answer is "whenever they publish". If you build it yourself, it's "as soon as the tarball is out".
This post builds a PHP 8.5 base image from source: a multi-stage Dockerfile, plus a GitHub workflow that builds and pushes it to GitHub's container registry, cached so a normal push doesn't recompile PHP from scratch.
Why compile it yourself?
The official php images are good, and for most projects they're the right
choice. Building your own is worth it when you want:
- Control over the build: exactly the extensions and
configureflags you need, nothing you don't. - Patch speed: a new release is one variable change away, with no waiting for an upstream image.
- One known base: every service starts from the same audited image, with your settings baked in.
- A smaller runtime: the compiler and headers stay in the build stage. The final image only carries PHP and the libraries it actually links.
The layout
docker/php/
├── Dockerfile
└── conf.d/
└── zz-hardening.ini
.github/workflows/php-base.yml
The Dockerfile
Two stages. build installs the toolchain, downloads and verifies the release, and compiles it. runtime
starts from a fresh debian:trixie-slim, copies /usr/local across and installs only the runtime libraries.
# syntax=docker/dockerfile:1
#
# PHP 8.5 base image, compiled from source.
# docker build --build-arg PHP_SHA256=<from php.net/downloads> -t php:8.5 docker/php
ARG DEBIAN_VERSION=trixie
############################ build: compile PHP ############################
FROM debian:${DEBIAN_VERSION}-slim AS build
ARG PHP_VERSION=8.5.12
ARG PHP_SHA256
# Build dependencies. Cache mounts keep apt downloads between local builds.
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
rm -f /etc/apt/apt.conf.d/docker-clean \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
autoconf bison build-essential ca-certificates curl pkg-config re2c xz-utils \
libargon2-dev libcurl4-openssl-dev libicu-dev libonig-dev libpq-dev \
libsodium-dev libsqlite3-dev libssl-dev libxml2-dev libzip-dev zlib1g-dev
# Download and verify the release. No checksum, no build.
WORKDIR /usr/src
RUN test -n "$PHP_SHA256" || { echo "Pass --build-arg PHP_SHA256 (see php.net/downloads)" >&2; exit 1; } \
&& curl -fsSL -o php.tar.xz "https://www.php.net/distributions/php-${PHP_VERSION}.tar.xz" \
&& echo "${PHP_SHA256} php.tar.xz" | sha256sum -c - \
&& mkdir php && tar -xJf php.tar.xz -C php --strip-components=1
# Configure, compile, install. OPcache is part of the core build from PHP 8.5.
WORKDIR /usr/src/php
RUN ./configure \
--prefix=/usr/local \
--with-config-file-path=/usr/local/etc/php \
--with-config-file-scan-dir=/usr/local/etc/php/conf.d \
--enable-fpm --with-fpm-user=www-data --with-fpm-group=www-data \
--disable-cgi --disable-phpdbg \
--enable-bcmath --enable-intl --enable-mbstring --enable-pcntl --enable-sockets \
--with-curl --with-openssl --with-password-argon2 --with-sodium --with-zip --with-zlib \
--with-pdo-mysql=mysqlnd --with-pdo-pgsql --with-pdo-sqlite \
&& make -j"$(nproc)" \
&& make install \
&& strip --strip-all /usr/local/bin/php /usr/local/sbin/php-fpm \
&& mkdir -p /usr/local/etc/php/conf.d \
&& cp php.ini-production /usr/local/etc/php/php.ini \
&& cp /usr/local/etc/php-fpm.conf.default /usr/local/etc/php-fpm.conf \
&& cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's|^listen = .*|listen = 9000|' /usr/local/etc/php-fpm.d/www.conf
# Work out which Debian packages the binaries need at runtime, from the
# libraries they actually link, so the final stage installs exactly those.
RUN ldd /usr/local/bin/php /usr/local/sbin/php-fpm \
| awk '/=> \// { print $3 }' | sort -u \
| xargs -r realpath | xargs -r dpkg-query --search \
| cut -d: -f1 | sort -u > /usr/local/runtime-packages.txt
########################### runtime: PHP + its libs ###########################
FROM debian:${DEBIAN_VERSION}-slim
COPY --from=build /usr/local /usr/local
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
rm -f /etc/apt/apt.conf.d/docker-clean \
&& apt-get update \
&& xargs -a /usr/local/runtime-packages.txt \
apt-get install -y --no-install-recommends ca-certificates \
&& rm /usr/local/runtime-packages.txt \
&& php -v && php -m
# Site-wide settings, e.g. the php2shell hardening.
COPY conf.d/ /usr/local/etc/php/conf.d/
WORKDIR /var/www/html
EXPOSE 9000
STOPSIGNAL SIGQUIT
CMD ["php-fpm", "--nodaemonize"]
A few details worth calling out:
- The checksum is mandatory. The build refuses to run without
PHP_SHA256, andsha256sum -cfails the build if the download doesn't match. Copy the value for the exact.tar.xzfrom php.net/downloads; never paste one from a blog post, including this one. - Runtime dependencies are computed, not guessed. The last build step asks
lddwhich shared librariesphpandphp-fpmlink, maps each file back to its Debian package withdpkg-query --search, and writes the list to a file. The runtime stage installs exactly that list. Add an extension, and its library comes along without editing a package list by hand. --with-config-file-scan-dirmakes PHP read every.iniinconf.d/, so services can add settings without touchingphp.ini. The image starts fromphp.ini-production.- OPcache. From PHP 8.5 it's part of the core build, so there's no
--enable-opcache. On 8.4 or older you'd still need the flag. php -v && php -mat the end of the runtime stage is a cheap smoke test. If a library is missing, the image fails to build instead of failing in production.
The conf.d folder carries the settings every service should get, including the php2shell hardening:
; docker/php/conf.d/zz-hardening.ini
; Loaded last (zz-) from the conf.d scan directory.
expose_php = Off
session.upload_progress.enabled = Off ; php2shell: removes the main remote trigger
fatal_error_backtraces = Off ; php2shell on PHP 8.5
Building it locally, with Podman
I build images locally with Podman rather than Docker. The Dockerfile doesn't change:
Podman builds the same file, RUN --mount=type=cache included. This one was built and smoke-tested with Podman
on Apple Silicon.
podman build --build-arg PHP_SHA256=<sha256 from php.net> -t php:8.5 docker/php
podman run --rm php:8.5 php -v
# Both architectures into one multi-arch image (the second one is emulated)
podman build --platform linux/amd64,linux/arm64 --manifest php:8.5 \
--build-arg PHP_SHA256=<sha256 from php.net> docker/php
Why Podman over Docker:
- No daemon. Podman runs each build or container as an ordinary process. There's no always-on root
service, and no
docker.sockthat quietly gives root to anything allowed to talk to it. - Rootless by default. Containers run as your user, mapped through user namespaces. If something breaks out of a container, it lands as you, not as root.
- A drop-in replacement. Same Dockerfiles, same OCI images, same registries, and nearly the same CLI
(
alias docker=podmancovers most daily use). - No Docker Desktop licence. Podman and Podman Desktop are open source. Docker Desktop needs a paid subscription in larger companies.
- Kubernetes-shaped. Pods are a native concept, and
podman kube generate/podman kube playmove between local containers and Kubernetes YAML.
The trade-offs:
- Podman ignores the
# syntax=line, which only matters for BuildKit-specific Dockerfile features. - On macOS, Podman still runs a Linux VM (
podman machine), just like Docker Desktop does. - In CI the workflow below sticks with Docker Buildx, because its GitHub Actions cache backend (
type=gha) is a BuildKit feature. The image it produces is the same OCI image either way.
The workflow
name: php-base
on:
push:
branches: [main]
paths: ['docker/php/**', '.github/workflows/php-base.yml']
pull_request:
paths: ['docker/php/**', '.github/workflows/php-base.yml']
schedule:
- cron: '17 4 * * 1' # weekly, to pick up Debian security updates
workflow_dispatch:
permissions:
contents: read
packages: write
concurrency:
group: php-base-${{ github.ref }}
cancel-in-progress: true
env:
IMAGE: ghcr.io/${{ github.repository_owner }}/php
PHP_VERSION: 8.5.12
# sha256 of php-8.5.12.tar.xz from php.net/downloads, stored as a repository variable
PHP_SHA256: ${{ vars.PHP_SHA256 }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: docker/setup-qemu-action@v3 # emulation for the arm64 build
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
if: github.event_name != 'pull_request'
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE }}
tags: |
type=raw,value=${{ env.PHP_VERSION }}
type=raw,value=8.5
type=sha,prefix=${{ env.PHP_VERSION }}-
- uses: docker/build-push-action@v6
with:
context: docker/php
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
pull: true # always start from the latest debian:trixie-slim
no-cache: ${{ github.event_name == 'schedule' }} # weekly full rebuild
build-args: |
PHP_VERSION=${{ env.PHP_VERSION }}
PHP_SHA256=${{ env.PHP_SHA256 }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
# mode=max also caches the build stage, which isn't part of the final image
cache-from: type=gha,scope=php-${{ env.PHP_VERSION }}
cache-to: type=gha,scope=php-${{ env.PHP_VERSION }},mode=max
It runs when the Dockerfile or the workflow changes, on pull requests (build only, no push), weekly on a
schedule, and on demand. Images go to ghcr.io/<owner>/php tagged 8.5.12, 8.5 and 8.5.12-<sha>, so you can
pin exactly or follow the minor line. The checksum lives in a repository variable (vars.PHP_SHA256), so
bumping PHP is two small edits: the version in the workflow and the variable.
Caching it properly
Compiling PHP takes minutes, and much longer for arm64 under emulation. Without a cache, every push pays that in full. Five things make the difference:
- Order the layers by how often they change. System packages first, then the download, then
configureandmake. Editingconf.d/only rebuilds the last few layers of the runtime stage. BumpingPHP_VERSIONre-runs the download and compile but keeps the apt layer. mode=maxoncache-to. The default (mode=min) only caches layers that end up in the final image. The expensive part here, the compile, happens in the build stage, which isn't in the final image. Withoutmode=max, every build recompiles PHP.- One cache scope per PHP version. The GitHub Actions cache is limited per repository and evicts the oldest
entries first.
scope=php-8.5.12keeps two versions, or two images in one repo, from overwriting each other's cache. - Know what isn't cached. The
--mount=type=cachemounts for apt speed up builds on your machine, but thetype=ghaexporter only saves layers, not cache mounts. In CI they start empty every run, and that's fine, because the layer cache does the heavy lifting. - Rebuild without cache on a schedule. A cache is great until it stops you getting updates. With layers
cached forever, the
apt-get installlayer would keep last month's packages. The weekly run setsno-cache: trueandpull: true, so the image picks up Debian security fixes and a fresh base image even when PHP hasn't changed.
If the GitHub cache limit gets in the way, or several repositories should share one cache, switch to a registry cache:
cache-from: type=registry,ref=ghcr.io/acme/php:buildcache
cache-to: type=registry,ref=ghcr.io/acme/php:buildcache,mode=max
arm64 without the wait
QEMU emulation keeps the workflow to one job, but compiling PHP under emulation is slow. If arm64 build time
matters, run each platform on a native runner (ubuntu-24.04-arm for arm64) as a matrix, push each by digest,
and combine them into one multi-arch tag with docker buildx imagetools create. It's more YAML, and much
less waiting.
Using the base image
Application images then start from it and only add their own code:
FROM ghcr.io/acme/php:8.5
COPY --chown=www-data:www-data . /var/www/html
USER www-data
When the next PHP release lands, it's two edits, one build, and every service picks it up on its next deploy.