Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Create a PHP Development Environment With Docker Compose

A complete, practical Docker Compose setup for PHP development, including a multi-stage Dockerfile, Apache and PHP-FPM choices, MariaDB persistence, live source editing, Composer, PHPUnit, and troubleshooting.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The practical pattern is to put PHP in a custom Docker image and describe that image, a database, ports, health checks, mounts, and persistent storage in compose.yaml. For a small application, start with php:8.2-apache. If you need a separate web tier, use PHP-FPM behind Nginx or Apache on a private Compose network. The examples below give you development and production build targets, Composer and PHPUnit inside the container, live source editing, and a MariaDB service whose data survives container recreation.

Understand what Dockerfile and Compose each do

A PHP development environment has two complementary definitions:

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Dockerfile: builds the PHP runtime. It selects the PHP base image, installs extensions such as pdo_mysql, adds Composer, copies application files, and defines development and production targets.
  • compose.yaml: runs the application as a set of services. It declares the PHP server, database, published ports, startup dependencies, bind mounts or watch rules, networks, and named volumes.

Compose reads the YAML model, creates the network and volumes, builds images when requested, and starts the services together. The application reaches the database by its Compose service name, not by localhost. Inside the PHP container, localhost means the PHP container itself; the database host in the examples is db.

Prerequisites and a useful project layout

Install Docker Desktop, or Docker Engine with the Compose plugin, and verify that both commands work:

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
docker --version
docker compose version

Create a project directory containing the files used by the build and runtime:

php-docker-app/
├── Dockerfile
├── compose.yaml
├── composer.json
├── composer.lock
├── hello.php
├── src/
└── tests/

Commit composer.lock for an application. It makes the dependency set reproducible across developers and CI. A minimal composer.json for PHPUnit could be:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
{
  "require": {},
  "require-dev": {
    "phpunit/phpunit": "^10.0"
  }
}

Use the PHP and database versions that your application supports. The examples use the documented php:8.2-apache route and a MariaDB 11 image tag as illustrative choices. Pin a specific image tag or digest for repeatable builds; a floating tag can point to a different image later.

Build a multi-stage PHP image

Multi-stage builds let development and production use the same base decisions without shipping development-only dependencies or settings in the production image. The following Dockerfile creates separate Composer stages, a common PHP/Apache base, and two final targets.

# syntax=docker/dockerfile:1

FROM composer:lts AS composer-dev
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install 
    --prefer-dist 
    --no-interaction 
    --no-progress

FROM composer:lts AS composer-prod
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install 
    --prefer-dist 
    --no-interaction 
    --no-progress 
    --no-dev 
    --optimize-autoloader

FROM php:8.2-apache AS php-base
WORKDIR /var/www/html

# Make Composer available in the runtime container.
COPY --from=composer:lts /usr/bin/composer /usr/bin/composer

# PDO is the database abstraction; pdo_mysql is the MySQL/MariaDB driver.
RUN docker-php-ext-install pdo pdo_mysql 
    && a2enmod rewrite

COPY . .

FROM php-base AS development
COPY --from=composer-dev /app/vendor /var/www/html/vendor
COPY docker/php/php.ini-development /usr/local/etc/php/php.ini

FROM php-base AS production
COPY --from=composer-prod /app/vendor /var/www/html/vendor
COPY docker/php/php.ini-production /usr/local/etc/php/php.ini

# Keep Apache in the foreground so the container remains running.
CMD ["apache2-foreground"]

Create the two PHP configuration files if you need custom settings. Development settings normally enable useful diagnostics, while production settings disable display of errors and use a suitable error log. Do not copy development credentials or verbose error output into a production image.

docker-php-ext-install compiles extensions included in the official PHP image. Add every extension your framework requires in the same layer, for example an additional extension for image processing, but check its system-library prerequisites before adding it. The example installs pdo and pdo_mysql because the database service is MySQL-compatible.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The image copies application files for an immutable build. During development, a bind mount will cover that directory with your working tree, so source edits appear without rebuilding. The production target keeps the files and optimized, non-development Composer dependencies inside the image.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Define the PHP and database services in Compose

Create compose.yaml with a development build target, a published HTTP port, a MariaDB service, a health check, and a named data volume:

services:
  server:
    build:
      context: .
      target: development
    ports:
      - "9000:80"
    volumes:
      - .:/var/www/html
      # Keep container-installed dependencies out of the host tree.
      - /var/www/html/vendor
    depends_on:
      db:
        condition: service_healthy

  db:
    image: mariadb:11
    environment:
      MARIADB_DATABASE: app
      MARIADB_USER: app
      MARIADB_PASSWORD: app_password
      MARIADB_ROOT_PASSWORD: root_password
    volumes:
      - db-data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
      interval: 5s
      timeout: 5s
      retries: 10

volumes:
  db-data:

Open http://localhost:9000/ after startup. The host’s port 9000 maps to Apache’s port 80 inside the server container; change the left-hand number if that port is already occupied.

The depends_on health condition prevents Compose from starting the application before the database reports that it can accept connections. It does not make your application retry forever. Your PHP code should still handle a transient connection failure during a database restart.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For anything beyond local experimentation, supply credentials through an .env file that is excluded from version control or through your deployment secret mechanism. The values in this example are intentionally simple local-development credentials.

Make application edits visible immediately

Bind mounts

The .:/var/www/html bind mount maps the project directory on your host to Apache’s document root. Saving hello.php on the host changes what Apache serves without rebuilding. The anonymous /var/www/html/vendor volume prevents the bind mount from hiding the dependencies installed into the image; run Composer in the container whenever dependencies change.

Bind mounts are convenient, but filesystem performance and UID/GID permissions differ between Linux, macOS, and Windows. They are a development technique, not a production image strategy. If a framework writes cache or log files, ensure the container user can write those directories, or configure the framework to use a dedicated writable path.

Compose Watch

Current Compose implementations can declare synchronization and rebuild behavior under develop.watch. Use it instead of a broad bind mount when you want explicit rules:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
services:
  server:
    build:
      context: .
      target: development
    ports:
      - "9000:80"
    develop:
      watch:
        - action: sync
          path: ./src
          target: /var/www/html/src
        - action: rebuild
          path: ./composer.json
        - action: rebuild
          path: ./composer.lock

Start watch mode with docker compose watch. The exact watch actions available depend on your installed Compose version. Keep the rules narrow: synchronize source files, and rebuild when the dependency manifest or Dockerfile changes. Do not enable both a broad bind mount and a watch rule for the same path unless you understand which mechanism owns that path.

Choose Apache or PHP-FPM with a separate web server

Architecture Use it when Trade-offs
php:*-apache You have a small application and want the shortest local setup. Fewer services and less configuration, but PHP serving is coupled to Apache.
PHP-FPM plus Nginx or Apache You want a separate web tier or a layout close to many production stacks. More services, shared source/configuration, and proxy configuration. FPM must be reached through a private container network.

With FPM, the PHP container does not serve HTTP directly. It listens for FastCGI requests from the web server. Do not publish the FPM port to the host; put both services on the internal Compose network and publish only the proxy’s HTTP port.

Minimal FPM service arrangement

services:
  php:
    build:
      context: .
      target: development-fpm
    expose:
      - "9000"
    volumes:
      - .:/var/www/html

  nginx:
    image: nginx:stable
    ports:
      - "9000:80"
    volumes:
      - .:/var/www/html:ro
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - php

  db:
    image: mariadb:11
    # environment, healthcheck, and db-data volume as in the Apache example

A corresponding Nginx server block passes PHP scripts to the service name php:

server {
    listen 80;
    root /var/www/html;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ .php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass php:9000;
    }
}

In an FPM Dockerfile, use a PHP-FPM base image and keep the same extension installation and Composer stages:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
FROM php:8.2-fpm AS php-base
WORKDIR /var/www/html
RUN docker-php-ext-install pdo pdo_mysql
COPY . .

The proxy and FPM containers must see the same application paths so the proxy can resolve the script filename that FPM executes. This is why FPM layouts commonly use a shared bind mount in development and a coordinated application image or shared artifact in production.

Keep MariaDB data across container recreation

The db-data named volume is mounted at MariaDB’s data directory. Removing and recreating the db container does not remove that volume, so tables remain available when you run Compose again. A volume is persistent storage managed by the container engine, not a backup: explicitly export or back up important data, and remove the volume only when you intend to erase it.

Use the service name and container credentials from PHP. A PDO connection might look like this:

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
<?php
$dsn = 'mysql:host=db;dbname=app;charset=utf8mb4';
$pdo = new PDO($dsn, 'app', 'app_password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

Do not use localhost for this connection. Compose creates a network with internal DNS, so db resolves to the database container. If you rename the service, update the hostname accordingly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To inspect the volume and database service:

docker compose ps
docker compose logs db
docker volume ls

Initialization variables such as MARIADB_DATABASE are applied when the data directory is first initialized. Changing them later does not recreate an existing database. Use SQL migrations or an administrative command for changes to an already-initialized volume.

Start, inspect, and stop the environment

  1. Build the selected target and start every service in the foreground:
    docker compose up --build
  2. Open http://localhost:9000/hello.php if your project contains the sample file, or visit the route provided by your framework.
  3. In another terminal, list service state and published ports:
    docker compose ps
  4. Follow application output when debugging:
    docker compose logs -f server
  5. Open a shell in the running PHP container:
    docker compose exec server bash
  6. Stop containers while retaining the named database volume:
    docker compose down

Use docker compose down -v only when you deliberately want to remove Compose-managed volumes, including db-data and the stored database contents.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Run Composer and PHPUnit inside the container

Running tools in the PHP image avoids differences between host PHP installations and the container runtime. With the Dockerfile above, Composer is available as composer and development dependencies are installed in the development target.

# Install or refresh dependencies using the container's PHP and Composer.
docker compose exec server composer install

# Add a package; commit the resulting composer.json and composer.lock.
docker compose exec server composer require vendor/package

# Run the test suite from the development container.
docker compose exec server ./vendor/bin/phpunit

If the service is not running, use a one-off container:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker compose run --rm server composer install
docker compose run --rm server ./vendor/bin/phpunit

The official guide’s sample test output is one test and one assertion; that number describes the sample, not a guarantee for your project. Add a tests/ directory and a PHPUnit configuration suited to your framework. Keep test execution in the development or test target so production does not contain development-only packages.

When Composer reports that an extension is missing, add the required PHP extension to the Dockerfile and rebuild with docker compose up --build. Installing an extension only on the host cannot satisfy a dependency check performed inside the container.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Separate development and production builds

Use the development target for bind mounts, diagnostics, PHPUnit, and packages under require-dev. Use the production target to install only runtime dependencies, optimize the Composer autoloader, and bake application code into the image. A production Compose file can select the target explicitly:

services:
  server:
    build:
      context: .
      target: production
    ports:
      - "8080:80"
    restart: unless-stopped
    # No host source bind mount in production.

  db:
    image: mariadb:11
    # Supply production secrets through your deployment platform.
    volumes:
      - db-data:/var/lib/mysql

volumes:
  db-data:

Do not copy a development php.ini, test fixtures, local credentials, or host-generated files into a production image. Add a .dockerignore to keep unnecessary material out of the build context:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.git
.env
vendor
node_modules
.phpunit.result.cache
Dockerfile*
compose*.yaml

Adjust the ignore list if a deployment process intentionally needs a Compose file or another artifact. Pin base-image tags or immutable digests when you need to reproduce the exact runtime later; document how and when those pins are updated.

Troubleshoot the common failures

The browser cannot connect

  • Run docker compose ps and confirm that server is running and that host port 9000 is published.
  • Read docker compose logs server. Apache may have failed to start because a configuration file or module is invalid.
  • If another process owns port 9000, change the host side of the mapping, for example "9001:80", and open port 9001.

PHP files download instead of executing

Confirm that you built from the Apache image for the Apache setup, or that Nginx has a location ~ .php$ block with fastcgi_pass php:9000 for FPM. Static files being served successfully does not prove that FastCGI is configured.

The application cannot connect to MariaDB

  • Use db as the hostname, not localhost.
  • Check docker compose ps for the database health state and inspect docker compose logs db.
  • Verify that the database name, user, and password in PHP match the Compose environment variables.
  • Remember that first initialization can take longer than container creation; keep application connection retry logic.

Composer or PHPUnit is missing

Confirm that the service was built with target: development and that the image includes the Composer binary. Rebuild after changing the Dockerfile. If a bind mount hides the image’s vendor directory, use the anonymous vendor volume shown earlier or run docker compose exec server composer install.

Changes on the host are not visible

Check that the mount source is the directory containing the file you edited and that the target matches Apache’s document root. With Compose Watch, check that the watch rule’s path and target are correct and that you started docker compose watch, not only docker compose up.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Database data appears to have vanished

Inspect docker volume ls and the project name used to start Compose. A different directory or project name can create a different volume. Avoid docker compose down -v unless deleting the data is intentional.

A repeatable daily workflow

  1. Change PHP extensions, Composer manifests, or the Dockerfile, then run docker compose up --build.
  2. Change PHP source and refresh the browser; the bind mount or watch rule supplies the edit to the running container.
  3. Change dependencies with Composer inside the container and commit both manifest files.
  4. Run PHPUnit with docker compose exec server ./vendor/bin/phpunit before committing.
  5. Use docker compose logs -f and docker compose ps to diagnose startup or health issues.
  6. Stop the stack with docker compose down when finished; retain the named volume unless you are intentionally resetting the database.

This arrangement keeps the host focused on editing and Docker responsible for the PHP runtime, extensions, Composer, test tools, web server, and database. It also gives you a clear migration path: keep the simple Apache service for a small project, or split PHP-FPM and a proxy when your deployment architecture requires separate tiers.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.