Why a Dedicated CI/CD Pipeline Matters
A startup’s competitive edge often comes down to how quickly it can ship new features without compromising stability. For Laravel teams, the gap between a local dev environment and a production server can be a source of bugs, configuration drift, and security gaps. A well‑designed continuous delivery workflow eliminates most of those risks by making the build, test, and deploy steps repeatable, version‑controlled, and observable.
In this post I’ll walk through a practical setup that works for most Laravel SaaS products:
- Docker for a consistent runtime.
- GitHub Actions for automated linting, testing, static analysis, and security scanning.
- A rolling‑update deployment strategy that keeps the app available while new containers come online.
The goal isn’t to replace a full‑blown DevOps team, but to give a small engineering group a reliable foundation that scales with the business.
1. Containerising Laravel with Docker
Docker removes the “works on my machine” problem by packaging the PHP runtime, extensions, and system dependencies into a single image. Below is a minimal Dockerfile that follows Laravel’s official recommendations while staying lightweight.
# syntax=docker/dockerfile:1
FROM php:8.3-fpm-alpine AS base
# Install system extensions required by most Laravel apps
RUN apk add --no-cache \
libpng-dev \
libjpeg-turbo-dev \
freetype-dev \
zip \
unzip \
git \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install gd pdo_mysql bcmath opcache
# Composer – use the official installer for reproducibility
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
# Set working directory
WORKDIR /var/www/html
# Copy only composer files first to leverage Docker cache
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader --no-interaction
# Copy the rest of the application code
COPY . .
# Permissions for storage and cache directories
RUN chown -R www-data:www-data storage bootstrap/cache
# Use the non‑root user for runtime security
USER www-data
EXPOSE 9000
CMD ["php-fpm"]
A matching docker-compose.yml for local development keeps the database and queue workers in sync:
version: "3.9"
services:
app:
build: .
ports:
- "8000:9000"
volumes:
- .:/var/www/html
environment:
APP_ENV: local
APP_DEBUG: true
DB_HOST: db
depends_on:
- db
- redis
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: laravel
volumes:
- db_data:/var/lib/mysql
redis:
image: redis:7-alpine
volumes:
db_data:
With these files in place, docker compose up --build gives you a fully functional Laravel stack that mirrors production.
2. Building a Reliable CI Pipeline with GitHub Actions
GitHub Actions is a free‑tier friendly solution that runs in the same environment you define in Docker. The workflow below covers four essential jobs:
- Code style linting –
php-cs-fixer. - Static analysis –
PHPStan. - Unit / feature tests –
phpunit. - Security audit –
composer auditand optional Snyk scan.
name: Laravel CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
services:
mysql:
image: mysql:8.0
env:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: test
ports: [3306:3306]
options: >-
--health-cmd="mysqladmin ping --silent"
--health-interval=10s
--health-timeout=5s
--health-retries=3
steps:
- uses: actions/checkout@v3
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, intl, bcmath, pdo_mysql, gd
coverage: none
- name: Install Composer dependencies
run: composer install --prefer-dist --no-progress --no-suggest
- name: Lint code style
run: vendor/bin/php-cs-fixer fix --dry-run --diff
- name: Static analysis with PHPStan
run: vendor/bin/phpstan analyse --no-progress
- name: Run tests
env:
DB_CONNECTION: mysql
DB_HOST: 127.0.0.1
DB_PORT: 3306
DB_DATABASE: test
DB_USERNAME: root
DB_PASSWORD: secret
run: vendor/bin/phpunit --colors=always
- name: Composer security audit
run: composer audit --format=plain
# Optional: Snyk scan (requires SNYK_TOKEN secret)
- name: Snyk test
uses: snyk/actions@master
with:
command: test
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
A few practical tips:
- Cache dependencies – add
actions/cachefor thevendordirectory to speed up subsequent runs. - Parallel jobs – split linting, analysis, and tests into separate jobs if your repository grows large.
- Fail fast – order steps from cheapest to most expensive; a lint error should stop the pipeline before the test suite runs.
3. Automated Security Scanning
Beyond composer audit, consider integrating these tools into the same pipeline:
| Tool | What it does | Integration point |
|------|--------------|-------------------|
| PHPStan (level 8+) | Detect dead code, type mismatches, and potential injection points. | Static analysis job. |
| Psalm | Focuses on security‑related taint analysis. | Add as a separate step if you have custom data flows. |
| Snyk or GitHub Dependabot | Monitors third‑party packages for known CVEs. | Runs on every push; alerts appear in the repository security tab. |
| Laravel Security Checker (laravel/pint can also surface insecure patterns) | Scans for common Laravel misconfigurations (e.g., debug mode in production). | Add a custom script: php artisan security:check. |
By treating security as a build‑time gate rather than an after‑the‑fact audit, you catch regressions before they hit production.
4. Zero‑Downtime Deploys with Rolling Updates
Docker alone does not guarantee availability during a deploy. The typical pattern for Laravel apps is:
- Build a new image with the latest code.
- Push the image to a registry (Docker Hub, GitHub Packages, or a private ECR).
- In the orchestration layer (Docker Swarm, Kubernetes, or a simple
docker composeon a VPS), perform a rolling update that replaces old containers one at a time.
Below is a minimal Kubernetes Deployment that illustrates the approach. The key is the preStop hook that drains the queue worker before the pod is terminated.
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-app
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app: laravel
template:
metadata:
labels:
app: laravel
spec:
containers:
- name: php-fpm
image: ghcr.io/yourorg/laravel-app:{{ github.sha }}
ports:
- containerPort: 9000
envFrom:
- secretRef:
name: laravel-env
lifecycle:
preStop:
exec:
command: ["php", "artisan", "queue:restart"]
If you’re not on Kubernetes yet, Docker Compose v2 supports --scale and --force-recreate flags that you can script in a CI/CD job:
# Pull the newest image
docker compose pull app
# Recreate containers one at a time
docker compose up -d --no-deps --scale app=3 app
Database migrations deserve special handling. The safest pattern is to make migrations backwards compatible:
- Add new columns as nullable.
- Deploy code that writes to the new column while still supporting the old one.
- Run the migration.
- In a later release, make the column non‑nullable and remove legacy code.
This staged approach lets you run php artisan migrate as a separate step in the pipeline, without taking the app offline.
5. Takeaways & Quick Checklist
| ✅ | Action |
|---|--------|
| Dockerise | Keep a single Dockerfile that builds the production image. |
| Cache | Use Docker layer caching for composer installs; cache Composer files in CI. |
| Lint & Analyse | Run php-cs-fixer, PHPStan, and optionally Psalm on every PR. |
| Test | Execute unit and feature tests in a clean MySQL container. |
| Security | Run composer audit, Dependabot, and optionally Snyk on each push. |
| CI | Encode the full workflow in GitHub Actions (or GitLab CI) and keep it version‑controlled. |
| Deploy | Use rolling updates (Kubernetes, Swarm, or scripted Compose) and ensure migrations are backward compatible. |
| Observability | Attach a log driver (e.g., Loki) and a metrics exporter (Prometheus) to the containers for real‑time alerts. |
By codifying these steps, a small team can push changes daily without fearing regressions or security slips. The pipeline becomes a safety net rather than a bottleneck, and you free up senior engineers to focus on product value instead of firefighting deployments.
Ready to try it? Clone the starter repo, replace the placeholder image name, and push the first GitHub Action run. You’ll see the build, test, and security results in the Actions tab within minutes. From there, iterate on the checklist and let the pipeline grow with your product.
- Laravel
- Security
- Devops
- Docker
- Cicd