If we want to run mysql, too, not only php (as shown here), here’s one way of doing it.
It is a bit more complicated. One reason is that the official php apache image doesn’t come with mysql support. Another reason is that you need to find out the IP address of the mysql container.
This is for developing, not for shipping applications.
docker run --name mymysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=testdb -e MYSQL_USER=testuser -e MYSQL_PASSWORD=testpw -d mysql:8.0
This time I use names, in this case mymysql. It’s easier to set a name so that we already know the name of the container we want to link to (instead of using a randomly assigned name).
my-secret-pw is the password for the mysql root user, set with MYSQL_ROOT_PASSWORD. In the same way set the following to whatever you like, if needed
MYSQL_DATABASE=testdb, MYSQL_USER=testuser, MYSQL_PASSWORD=testpw
You can check at the Docker Hub what mysql versions are available.
Start php as before, but use
in this case mymysql because that’s the name I chose for my mysql.
We can’t use an unmodified image anymore (the official php apache image doesn’t come with mysql support), so we need a Dockerfile or we get a Class ‘mysqli’ not found error.
Create a Dockerfile with the following content
FROM php:7-apache RUN docker-php-ext-install mysqli
go to folder with Dockerfile, then build, in this case I call is phpwsql
docker build -t phpwsql .
docker run --name myphp70 --link mymysql:mysql -d -p 80:80 -v /pathtofolder/:/var/www/html/ phpwsql
Get the IP address of the mysql container
The mysql and the php containers will have different IP addresses, so localhost won’t work. To get the IP address of the mysql container type
docker inspect mymysql | grep IPAddress
which you can then use in your php code.
At the time of writing this blog post both mysql and php-apache are based on debian:jessie, so there’s not much overhead.