docker php mysql_使用Docker从PHP连接到MySQL服务器

bd96500e110b49cbb3cd949968f18be7.png

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)?

解决方案

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.):

$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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值