Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to MySQL server from php with Docker

Tags:

docker

mysql

I am new to Docker. I am developing a PHP application in Docker environment, and I need to use a MySql Server/database to persist data. Following documentation, I run this command to create the MySql server image:

docker run -v /var/lib/mysql mariadb

It downloaded it, but I also go this error with it:

error: database is uninitialized and password option is not specified You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD

How do I set the MYSQL_ALLOW_EMPTY_PASSWORD option?

And then how would I create a database on this image, and then read/write to it from my PHP code (which is on a different image)?

like image 903
Drake Avatar asked Mar 30 '17 20:03

Drake


1 Answers

Create container

Run this command: docker run --name some-mariadb -e MYSQL_ROOT_PASSWORD=mysecretpw -v mysql:/var/lib/mysql -d mariadb:latest

With this, you are creating your docker container with mariadb, and storing data on mysql folder. In the command, you have -e MYSQL_ROOT_PASSWORD=my-secret-pw. This set your root password as my-secret-pw. When you connect to it, your user is root, and password is my-secret-pw.

Find out the address

docker inspect some-mariadb - With this command, you will find all information about your container. You need your IP address.

Hint: docker inspect some-mariadb | grep IPAddress you make easier to find your IP Address.

Connecting

Now, it is the PHP part. Run the PHP below, but check your host address, that in my case was 172.17.0.2 (from PHP documentation.):

<?php
$link = mysqli_connect("172.17.0.2", "root", "my-secret-pw");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made!" . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);

And if works fine, you will read:

A proper connection to MySQL was made!
Host information: 172.17.0.2 via TCP/IP

Ps.: For database creation, run the required commands as you would make in a database without the docker. It is the same (CREATE DATABASE mydb).

This is just for starting. I recommend you to study docker compose. When you get it, will you learn a lot about docker advantages.

like image 193
Rafael Avatar answered Oct 26 '22 01:10

Rafael