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.