Let’s walk through how to setup PHP and Apache with Docker
We will use the following components to achieve this
2. Docker compose file
3. Docker and Docker compose commands
With the PHP official Docker image, apache’s implementation is already available
see this link:
When we run this, PHP 7.3 along with apache will be launched in one container, we will use this image as a base image throughout this post.
With this default image, comes limited packages, you may want to add some PHP packages they are widely used for development.
Let’s try to make Dockerfile where we will mention many of widely used packages and see how to build that and use it to launch containers.
FROM php:7.3-apache RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli RUN apt-get update && apt-get install -y \ libicu-dev \ libpq-dev \ libmcrypt-dev \ default-mysql-client \ git \ zip \ libcurl3-dev \ unzip \ libfreetype6-dev \ libjpeg62-turbo-dev \ libmcrypt-dev \ && rm -r /var/lib/apt/lists/* \ && docker-php-ext-configure pdo_mysql --with-pdo-mysql=mysqlnd \ && docker-php-ext-install \ curl \ mbstring \ exif \ hash \ json \ mysqli \ pdo_mysql \ pdo_pgsql \ pgsql \ posix \ zip \ session RUN docker-php-ext-install -j$(nproc) iconv mcrypt RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ RUN docker-php-ext-install -j$(nproc) gd RUN apt-get update && \ apt-get install -y --no-install-recommends git zip RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer RUN composer
You can add additional PHP extensions wherever needed, Do comment if you face any issues while adding more packages in Dockerfile
Let’s create Docker-compose.yaml file as well
version: '3' services: web: build: . container_name: php-apache-7.3 ports: - "80:80" - "443:443" volumes: - /var/www/html:/var/www/html - /etc/apache2:/etc/apache2/ restart: always
Above docker-compose file will do the following
- When built, creates a new docker image from Dockerfile
- 80 and 443 ports are exposed with the same system ports, so it is accessible through System.
- Volumes are mounted. /var/www/html contains code and /etc/apache2 contains apache configuration files, volumes are mounted to make it persistent even after container restarts.
- restart always policy is set up, so even if docker crashes or system crashes, when the system is up, the container will also re-run
Save this Dockerfile in the same folder as docker-compose files’
It will build this Docker image and give it name that will be written in docker-compose file, in our case php-apache-7.3
Now, let’s make container from this image and complete task.
docker-compose up -d docker ps
With docker ps, you can check if the container is running or not.
Do Comment, if you find any difficulties while implementing this