Docker Official PHP container how to enable PDO

The Official PHP & Apache[1] container is a great starting point for a local development environment. One thing that might trip you up is if you try to install or run queries against a database.

Out of the box, PDO drivers are not enabled. This will likely resort to the following errors:

[PDOException]  could not find driver

This might lead you to think you need to install the driver via your own Dockerfile. Using the following command:

RUN sudo apt-get update && apt-get install -y mysql7.0-mysql

Which quickly results in too the following list of error.

Package php7.0-mysql is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package ‘php7.0-mysql’ has no installation candidate
ERROR: Service ‘web’ failed to build: The command ‘/bin/sh -c apt-get update && apt-get install -y php7.0-mysql’ returned a non-zero code: 100

The PHP container doesn’t have a php.ini file either, so why not copy one and uncomment the line: extension=php_pdo_mysql.dll

Well, this is likely to end up with the following error:

HP Warning: PHP Startup: Unable to load dynamic library ‘php_pdo_mysql.dll’ (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20170718/php_pdo_mysql.dll (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/php_pdo_mysql.dll: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20170718/php_pdo_mysql.dll.so (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/php_pdo_mysql.dll.so: cannot open shared object file: No such file or directory)) in Unknown on line 0

So whats the solution? Turns out you need to use the docker-php-ext-install option, via Dockerfile built FROM the php container.

Your Dockerfile would look something similar to:

FROM php:7.2-apache
RUN docker-php-ext-install pdo pdo_mysql

Links

[1] https://hub.docker.com/_/php/