Running PHP 8.4 in Docker with Local File Mounting

Author

Kritim Yantra

Apr 13, 2025

Running PHP 8.4 in Docker with Local File Mounting

In this guide, we’ll walk through how to:

Run PHP 8.4 in a Docker container
Mount local PHP files for real-time development
Set up Apache to serve PHP files


Step 1: Set Up Your Project

Create a project folder with the following files:

1. index.php

<?php
echo "Hello PHP World!";
?>

2. Dockerfile

FROM php:8.4-apache
COPY index.php /var/www/html/
EXPOSE 80

Step 2: Build & Run the Docker Container

1. Build the Docker Image

docker build -t php-app .

2. Run the Container with Volume Mounting

1. For Windows (CMD/PowerShell)

docker run -d -p 8000:80 -v "%cd%":/var/www/html php-app
  • %cd% (CMD) or ${PWD} (PowerShell) represents the current directory.

2. For macOS/Linux (Bash/Zsh)

docker run -d -p 8000:80 -v $(pwd):/var/www/html php-app
  • $(pwd) automatically resolves to the current working directory.

3. For Windows (WSL2 - Best for Docker)

If using WSL2 (Windows Subsystem for Linux):

docker run -d -p 8000:80 -v $(pwd):/var/www/html php-app
  • Works just like Linux/macOS.

  • -d → Run in detached mode (background).
  • -p 8000:80 → Map host port 8000 to container port 80.
  • -v ${PWD}:/var/www/html → Mount the current directory to Apache’s web root.

Step 3: Verify It Works

  1. Open your browser and visit:

    http://localhost:8000
    

    You should see:

    Hello PHP World!
    
  2. Test Live Reloading:

    • Modify index.php on your local machine.
    • Refresh the browser → Changes appear instantly!

Step 4: Debugging (If Needed)

1. Check Running Containers

docker ps

2. View Logs

docker logs <container_id>

3. Enter the Container (For Debugging)

docker exec -it <container_id> bash

Why This Setup?

Fast Development – Changes reflect instantly due to volume mounting.
Consistent Environment – No "works on my machine" issues.
Easy Deployment – Same image works in production.


Bonus: Using Docker Compose

For better management, create a docker-compose.yml:

version: "3.8"
services:
  php:
    build: .
    ports:
      - "8000:80"
    volumes:
      - ./:/var/www/html

Then run:

docker-compose up -d

Final Thoughts

This setup is perfect for:

  • PHP developers who want a portable environment.
  • Teams needing consistent dev/prod parity.
  • Learning Docker with a real-world use case.

Try modifying index.php and see the changes live! 🚀


Need help? Drop a comment below! 😊

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts