Search code examples
phpsql-serverdockerpdo

Install / Configure SQL Server PDO driver for PHP docker image


I have a simple docker file, as follows:

FROM php:7.2-apache
COPY src/ /var/www/html/

Normally to install drivers for Mongo or MySQL connectivity I would do so by adding something like the below to the dockerfile:

docker-php-ext-install mongo

On this occasion I want to connect my php application to a SQL Server database, and I understand the best way to do this for php 7.x is by using the PDO driver, however I am unfamiliar with how to do configure this in the dockerfile.

I've tried doing a pecl install, like adding:

RUN pecl install sqlsrv pdo_sqlsrv

However this fails with a combination of errors that do not seem to point me in the right direction.

I'm just looking for a simple way to get this done in a dockerfile or by using docker run.

For added info, here's the error I'm getting:

/tmp/pear/temp/sqlsrv/shared/xplat.h:30:17: fatal error: sql.h: No such file or directory
 #include <sql.h>
                 ^
compilation terminated.
Makefile:194: recipe for target 'conn.lo' failed
make: *** [conn.lo] Error 1
ERROR: `make' failed
The command '/bin/sh -c pecl install sqlsrv pdo_sqlsrv     && docker-php-ext-enable pdo_sqlsrv' returned a non-zero code: 1

Thanks all


Solution

  • I have created a docker file for this exact purpose:

    FROM php:7.3-apache
    ENV ACCEPT_EULA=Y
    RUN apt-get update && apt-get install -y gnupg2
    RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - 
    RUN curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list 
    RUN apt-get update 
    RUN ACCEPT_EULA=Y apt-get -y --no-install-recommends install msodbcsql17 unixodbc-dev 
    RUN pecl install sqlsrv
    RUN pecl install pdo_sqlsrv
    RUN docker-php-ext-enable sqlsrv pdo_sqlsrv
    
    COPY . /var/www/html/
    

    Enjoy!