Recently I accepted a job that had to deal with php 5.6 code. It is still using mysql_connect in its code. Since the requirements are just trivial bug fixes and minor enhancements, I have no plan to upgrade it to using mysqli or pdo.
I was following this great guide written by Christian Engel, the original link: https://parastudios.de/local-development-with-docker-php-and-mysql/
My file have only slight differences with his docker-compose.yml:
version: '3' services: db: image: mariadb/server:10.3 environment: MYSQL_ROOT_PASSWORD: root ports: - "3306:3306" volumes: - ./data/dump.sql:/docker-entrypoint-initdb.d/dump.sql web: image: php:5.6.40-apache container_name: somename depends_on: - db ports: - "8080:80" volumes: - ./php/:/var/www/html/
However, after I followed his guide and ran the final bash command
docker-compose up there’s an error on the web page saying that
Fatal error: Call to undefined function mysql_connect() in /var/www/html/xxx_db_connect.php on line 16
To this I found an easy fix, it is because the original php extension for mysql is missing. Together with installing the mysqli extension, the better way to do that is to install them during the building of the docker image, instead of during the container runtime. So I created Dockerfile and placed the following code into it
FROM php:5.6.40-apache RUN docker-php-ext-install mysql && docker-php-ext-install mysqli
Then I change the line
image: php:5.6.40-apache in my docker-compose.yml into
Then again I run
docker-compose up --build since we need to rebuild the image to install the php extensions (after I ran docker-compose down to close the previous containers). And Voila! This time it works. The
localhost:8080 page renders as expected.
But the story does not end here! In fact from the original source code, the string variable
$host for the mysql_connect command was previously
"localhost", which is pretty normal for traditional php environments. However, we are now using Docker with separated containers of the web app and the database so things are a little different. Actually Docker would create a default common network for these two separated containers to communicate. The code actually does not recognise
"localhost" in mysql_connect and would give out
Warning: mysql_connect(): No such file or directory in ... and the connection would fail. Rest assured, there is an easy fix for this, just replace the
"localhost" string to
"db", which is the service name in your docker-compose.yml, then the web app will automagically connects to the mysql database!