I do quite a bit of PHP development where I am deploying to cloud based hosting provides (e.g. BlueHost, HostGator, etc.) where they are running Linux that uses PHP, MySQL, and Apache. This is the necessary docker files to run the application locally using Docker.
Some background, the file structure looks like this:
- /
- application
- {php/html files go in this directory}
- docker-compose.yml
- Dockerfile
- php.ini
Dockerfile:
Code:
FROM php:8.2-apache
RUN apt-get update && apt-get install -y \
libzip-dev libmariadb-dev libmariadb-dev-compat libpq-dev \
vim \
&& docker-php-ext-install \
pdo pdo_mysql zip
COPY ./php.ini /usr/local/etc/php/php.ini
WORKDIR /var/www/html
COPY . /var/www/html
RUN chown -R www-data:www-data /var/www/html \
&& chmod -R 755 /var/www/html
# this assumes you're using composer to install 3rd party libraries
# if not, then comment the next line or delete it
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
EXPOSE 80
CMD ["apache2-foreground"]
RUN echo "ServerName localhost" > /etc/apache2/conf-available/servername.conf \
&& ln -s /etc/apache2/conf-available/servername.conf /etc/apache2/conf-enabled/servername.conf
RUN a2enmod rewrite
docker-compose.yml:
Code:
services:
app:
build: .
container_name: php_app
ports:
- "8080:80"
volumes:
- ./application:/var/www/html
- ./php.ini:/usr/local/etc/php/php.ini
environment:
- APACHE_DOCUMENT_ROOT=/var/www/html
depends_on:
- db
db:
image: mysql:5.7
container_name: mysql_db
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: change_me_database_name
MYSQL_USER: change_me_database_username
MYSQL_PASSWORD: change_me_database_password
volumes:
- mysql_data:/var/lib/mysql
phpmyadmin:
image: phpmyadmin:5.2.1
container_name: phpmyadmin
depends_on:
- db
ports:
- "8081:80"
environment:
PMA_HOST: db
MYSQL_ROOT_PASSWORD: change_me_database_password
volumes:
mysql_data:
What this will do is copy the source code, located in the application directory, to the /var/www/html and install all the necessary infrastructure to run PHP locally.
To run the application, start Docker then run the following commands:
Code:
docker-compose build --no-cache && docker-compose up -d
To access the PHP application, go to localhost:8080 in your browser. To access phpMyAdmin, go to localhost:8081.
To stop the application, run this command:
Code:
docker-compose down --remove-orphans
Because of the db column in docker-compose.yml, it will save the state of the database when you shut down the docker container.
This setup is useful because:
- You do not need PHP/MySQL/Apache installed on your local machine.
- You can manage your code base via a code repository (i.e. Git)
- Your developing environment will replicate the exact environment you are deploying to.