Install a php script in PHP-FPM & Caddy via Docker

| | |

Install docker

Either regular docker install or rootless.

Create a new directory

Create a new directory where you will store your Docker Compose file and PHP/html etc files. For example, you can create a directory called “phpapp” in your home directory:

mkdir -p ./phpapp

write a docker compose file

paste the below code in a new file called docker-compose.yml.

This defines two services: “caddy” and “phpapp”. The “caddy” service uses the Caddy v2 image and mounts the Caddyfile and public directory as volumes. It also exposes ports 80 and 443. The “phpapp” service uses the PHP-FPM image from my GitHub repo (you can find other PHP versions along with other base operating systems (debian/alpine for example)) that’s updated weekly with the newest upstream code and adds many useful php extensions along with composer and mounts the public directory as a volume.

version: '3'

services:
  caddy:
    image: caddy:2-alpine
    container_name: caddy
    restart: unless-stopped
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - ./public:/srv
      - ./data:/data
      - ./caddy_config:/config
    ports:
      - "80:80"
      - "443:443"
    networks:
      - net

  phpapp:
    image: ghcr.io/kingpin/php-docker:8.1-fpm-alpine
    container_name: phpapp
    restart: unless-stopped
    volumes:
      - ./public:/srv
    networks:
      - net

networks:
  net:

write the Caddyfile

create a new file called Caddyfile in the same directory. This file defines the root directory as /srv and sets up a file server to serve files from that directory. It also sets up a FastCGI proxy to the PHP-FPM service on port 9000. This will also reach out to letsencrypt or zerossl and acquire an SSL cert for your domain example.com

example.com {
  root * /srv
  file_server
  php_fastcgi phpapp:9000
}

PHP test file

Create a new directory called “public” in the same directory as your docker-compose.yml file and add an index.php file with the following code:

<?php
phpinfo();
?>

Start the Docker container stack

Start the services by running the following command in your terminal:

docker compose up -d && docker compose logs -f

This will start the two services in your docker compose file and attach them to your terminal. You should see logs from both services.

Test in your browser

Open your web browser and navigate to http://example.com. You should see a PHP info page displayed, indicating that PHP-FPM is working correctly.

Move your code into the public folder

Remove the index.php file or rename it to phpinfo.php and put your php code in the public folder along with any html/js/css/etc files.

That’s it! You now have PHP-FPM and Caddy v2 running via Docker Compose. You can customize the Caddyfile and docker-compose.yml files to suit your needs, and add additional services as necessary.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *