Video Lesson: Install a new PHP extension by building a custom Docker image

Install a new PHP extension by building a custom Docker image

Learn how to build a custom Docker image that extends a base image with additional software and configuration.


Lesson Content

Let’s create a custom PHP Docker image that installs an additional PHP extension.

First, copy the current PHP image name from the phpfpm service in docker-compose.yml. The image in this example is markoshust/magento-php with its version and tag.

Create an images/php directory and add a file named Dockerfile with a capital D. Start the file with the image from docker-compose.yml as the base image:

FROM markoshust/magento-php:7.4-fpm-11

Use the complete version and tag from your docker-compose.yml file, which is 7.4-fpm-11 in this example.

You can choose a different base image version by visiting the docker-magento project on GitHub. Use the View Docker files section to find the PHP service, then select the tag and version you want to build from.

The PHP image switches to the app user near the end of its Dockerfile. Since installing packages and PHP extensions requires the root user, switch to root before running custom commands. After those commands, switch back to app:

FROM markoshust/magento-php:7.4-fpm-11

USER root

RUN docker-php-ext-install calendar

USER app

The docker-php-ext-install helper comes with the PHP Docker image and installs PHP extensions for you. The calendar extension adds calendaring functions to PHP.

You can add other commands to the Dockerfile as needed. For example, install nano with apt-get if you prefer it to vim:

FROM markoshust/magento-php:7.4-fpm-11

USER root

RUN docker-php-ext-install calendar
RUN apt-get install nano

USER app

Next, update the phpfpm service in docker-compose.yml. Remove its image property and replace it with a build property that points to the directory containing the custom Dockerfile:

phpfpm:
    build: images/php

Keep the other phpfpm service configuration in place. Docker Compose uses the Dockerfile inside images/php to build the image.

Restart the phpfpm container so Docker detects the new build configuration. The first time Docker sees the build property, it builds the custom image.

Confirm that the calendar extension is installed by checking the PHP configuration and filtering the output:

bin/cli php -i | grep calendar

The output includes the configuration file for the calendar extension.

When you change the Dockerfile, Docker needs to rebuild the image before the changes are available. Run the build command again:

docker-compose build

Docker rebuilds any layers affected by your changes. If nothing has changed, it reports cached layers and reuses the existing image data.

Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!