Setting Up Traefik for a PHP Application

Introduction 

Traefik is a modern reverse proxy and load balancer ideal for containerized PHP applications. This guide will walk you through setting up Traefik for a PHP application using Docker Compose.

Prerequisites

  • Docker and Docker Compose installed.
  • Basic knowledge of PHP and Docker.

Project Structure

Create a project structure as shown below:

.
├── docker-compose.yml
├── traefik.yml
├── php
│   └── Dockerfile
└── public
    └── index.php

Step 1: Create the docker-compose.yml

version: '3.8'

services:
  traefik:
    image: traefik:v2.9
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "./traefik.yml:/traefik.yml"

  php:
    build:
      context: ./php
    labels:
      - "traefik.http.routers.php.rule=Host(`localhost`)"
    volumes:
      - .:/var/www/html
    restart: always

Step 2: Create the traefik.yml

api:
  dashboard: true
  insecure: true

providers:
  docker:
    exposedByDefault: false

entryPoints:
  web:
    address: ":80"

Step 3: Create the PHP Dockerfile

FROM php:8.1-fpm
WORKDIR /var/www/html
COPY . .
CMD ["php-fpm"]

Step 4: Create a Test PHP File

// public/index.php
<?php
echo "Hello from Traefik with PHP!";

Step 5: Start the Services

docker-compose up -d
  • Access the PHP application: http://localhost
  • Access the Traefik dashboard: http://localhost:8080

Best Practices

  • Use Secure SSL Certificates: Implement Let's Encrypt with Traefik.
  • Optimize PHP Configurations: Adjust php.ini for production use.
  • Monitor Traffic: Use the Traefik dashboard for monitoring requests.

Conclusion

By following this guide, you've successfully set up Traefik as a reverse proxy for a PHP application using Docker Compose. Traefik's dynamic service discovery and load balancing make it an excellent choice for modern PHP applications.

Recent blogs
Структурные паттерны в программировании

Структурные паттерны в программировании

Порождающие паттерны в программировании

Порождающие паттерны в программировании

Генераторы и итераторы в PHP

Генераторы и итераторы в PHP

Объектно-ориентированное программирование в PHP

Объектно-ориентированное программирование в PHP

Структуры данных в PHP

Структуры данных в PHP