Why Use Docker? Step‑by‑Step Guide to Set Up a PHP Development Environment with Docker and Docker Compose
This article explains why Docker is useful and provides a step‑by‑step tutorial for installing Docker, creating a PHP Dockerfile, configuring Docker Compose with PHP and MySQL services, and launching the environment, enabling portable, isolated development and easy deployment.
Docker provides developers with an isolated, portable way to run applications, solving the “it doesn’t run on my machine” problem.
Its advantages include portability, easy installation, and isolation, which improve development efficiency and team collaboration.
Step 1: Install Docker and Docker Compose
Visit the official Docker website, download the appropriate version for your OS (Windows, macOS, Linux), and follow the installer. After installation, verify with:
docker --versionStep 2: Create a Dockerfile for a PHP environment
Create a file named Dockerfile in your project directory (no extension) and add the following content:
FROM php:8.0-apache
# Set working directory
WORKDIR /var/www/html
# Install required PHP extensions
RUN docker-php-ext-install mysqli pdo pdo_mysql
# Expose port
EXPOSE 80Step 3: Define services with Docker Compose
Create a docker-compose.yml file to run PHP and MySQL together:
version: '3.8'
services:
php:
build:
context: .
container_name: php_container
volumes:
- ./src:/var/www/html
ports:
- "8080:80"
networks:
- app-network
mysql:
image: mysql:5.7
container_name: mysql_container
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: mydatabase
MYSQL_USER: user
MYSQL_PASSWORD: password
volumes:
- dbdata:/var/lib/mysql
ports:
- "3306:3306"
networks:
- app-network
networks:
app-network:
driver: bridge
volumes:
dbdata:The PHP service builds a container from the Dockerfile and mounts the source code into /var/www/html . The MySQL service uses an official image, stores data in a persistent volume, and runs on a bridge network.
Step 4: Start the project
Run the following command to launch the services in the background:
docker-compose up -dThis starts the containers defined in docker-compose.yml . Access the application at http://localhost:8080 in a browser.
After these steps, you have a complete PHP development environment powered by Docker.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.