Current Location: Home> Latest Articles> Practical Guide: Running PHP Projects Efficiently with Docker

Practical Guide: Running PHP Projects Efficiently with Docker

gitbox 2025-07-21

Advantages of Running PHP in Docker

As container technology becomes mainstream, Docker has become an essential tool in modern software development. For PHP developers, Docker not only eliminates the 'it works on my machine' issue but also improves deployment efficiency and ensures consistent environments.

Using Docker to run PHP applications offers several key benefits:

Environment Consistency: Ensures uniform environments across development, testing, and production.

Fast Deployment: Build once and run anywhere across different platforms.

Easy Maintenance: Container isolation simplifies updates and rollbacks.

Creating a Basic PHP Dockerfile

A Dockerfile defines the runtime environment for your container. Below is a basic example for PHP projects:

FROM php:8.0-apache
# Copy PHP source code into the container
COPY src/ /var/www/html/
# Enable Apache mod_rewrite module
RUN a2enmod rewrite

This Dockerfile uses the official PHP 8.0 with Apache image, copies the source code into the web root inside the container, and enables the URL rewrite module—commonly used in many PHP frameworks.

Building the Image and Running the Container

After creating the Dockerfile, use the following commands to build the image and run the container:

# Build the image
docker build -t my-php-app .

# Run the container
docker run -d -p 80:80 my-php-app

This builds an image named my-php-app and starts a container in the background, mapping port 80 of the container to the host.

Managing Multi-Container PHP Apps with Docker Compose

For projects that require multiple services (like a database), Docker Compose is an excellent tool. Here is a typical PHP + MySQL Compose setup:

version: '3.8'
services:
  web:
    image: php:8.0-apache
    volumes:
      - ./src:/var/www/html/
    ports:
      - "80:80"
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: my_db

This configuration defines two services:

web: PHP application container, mapping the local code directory and exposing port 80.

db: MySQL service, setting the root password and default database.

Using the docker-compose up command, you can launch all services in one step, greatly improving development efficiency.

Conclusion

Containerizing PHP applications is a powerful way to build portable and maintainable systems. By writing a proper Dockerfile and utilizing Docker Compose, you can easily set up consistent development and production environments.

Mastering these Docker + PHP techniques will bring greater flexibility and convenience to your development workflow.