Using Docker to localhost PHP and mysql

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.

Running mysql

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.

Running php

Start php as before, but use

--link mymysql:mysql

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 .

then run

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s