Docker based PHP calls the Docker based Mysql database

  • 2020-05-24 06:32:24
  • OfStack

docker introduction:

Docker is an open source application container engine that allows developers to package their applications and dependencies into a portable container and release them to any popular Linux machine, as well as virtualization. Containers are completely sandboxed and have no interfaces with each other.

Ever since the introduction of docker, 1 has wanted to achieve this kind of gameplay. Here are the steps

1. Build mysql based on docker, refer to the article

Mac converts MySql installed by brew to Docker

2: build php image based on docker

In the current directory, create Dockerfile as follows


FROM php:7.0-cli
MAINTAINER Terry Zhang <zterry@qq.com>
RUN docker-php-ext-install pdo_mysql mysqli

3. Create an php mirror


docker build -t php-mysql

4. Write php script, which can read data from mysql database:


<?php
$host = 'mysql';
$user = 'root';
$pwd = 'password';
$db = 'test';
$mysqli = new mysqli($host, $user, $pwd, $db);
if ($mysqli->connect_errno) {
echo "Errno: " . $mysqli->connect_errno . "\n";
}
$sql = 'SELECT * FROM users';
if ($res = $mysqli->query($sql)) {
while ($row = $res->fetch_assoc()) {
print_r($row);
}
}
?>

5. Execute php container with the following parameters:


bash docker run -it --rm -v (pwd):/var --link my-mysql-server1:mysql php-mysql:latest php /var/mysql.php

The important thing to note is the link parameter, which calls a container named my-mysql-server1, whose host in the php container is mysql. You can verify it with the following command:


docker run -it --rm php-mysql ping mysql

Related articles: