Setting up PHP in a Docker environment is a powerful way to streamline your development workflow. Whether you’re creating a new application or managing an existing one, Docker allows you to isolate your PHP development environment
Before getting started, ensure you have Docker installed on your system. You can download Docker Desktop for Windows or macOS, or install Docker Engine for Linux from the official Docker website.
Start by creating a directory for your project where all your Docker-related files and configurations will live.
mkdir php-docker-setup cd php-docker-setup
A Dockerfile is a blueprint for building your Docker image. In this case, it will define a PHP runtime environment. Create a Dockerfile in your project directory and add the following content:
# Use the official PHP image from Docker Hub FROM php:8.1-apache # Install additional PHP extensions if needed RUN docker-php-ext-install pdo pdo_mysql # Copy your application code into the container COPY ./src /var/www/html # Set the working directory WORKDIR /var/www/html # Expose port 80 for the web server EXPOSE 80
This configuration uses the official PHP image with an Apache web server, installs additional PHP extensions, and copies your project files into the container.
To simplify the process of managing your Docker containers, you can use Docker Compose. Create a docker-compose.yml file in your project directory:
docker-compose.yml
version: '3.8' services: php-apache: build: context: . dockerfile: Dockerfile ports: - "8080:80" volumes: - ./src:/var/www/html environment: - APACHE_RUN_USER=www-data - APACHE_RUN_GROUP=www-data
This configuration defines a service named php-apache, maps port 8080 on your local machine to port 80 in the container, and mounts the src directory for live file updates.
Create a src directory in your project folder and add your PHP files. For example, add an index.php file:
src
index.php
mkdir src
Then create your PHP files in the src directory. Your project structure should look like:
php-docker-setup/ ├── Dockerfile ├── docker-compose.yml └── src/ └── index.php
Once you've completed all the steps above, you can start your Docker container with:
docker-compose up -d
Then visit http://localhost:8080 in your browser to see your PHP application running!
http://localhost:8080