version : " 3"
services :
app :
container_name : php
build :
context : ./php
dockerfile : Dockerfile
tty : true
volumes :
- ${PWD}:/var/www/html
ports :
- " 80:80"
network_mode : " myphp"
db1 :
container_name : mysql
image : mysql:latest
command : --default-authentication-plugin=mysql_native_password
environment :
- MYSQL_ROOT_PASSWORD=pass
network_mode : " myphp"
networks :
myphp :
FROM php:7.2-apache
RUN apt-get update && \
# PHPのExtensionをインストール.
docker-php-ext-install pdo_mysql mysqli mbstring
WORKDIR /var/www/html
EXPOSE 80
docker network create myphp
docker-compose up -d
3. join to php /var/www/html
docker container exec -it php bash
<meta charset="UTF -8 ">
<title>テスト</title>
<?php
try {
# hostには「docker-compose.yml」で指定したコンテナ名を記載
$ dsn = "mysql:host=mysql;dbname=sample; " ;
$ db = new PDO ($ dsn , 'root ' , 'pass ' );
$ sql = "SELECT * FROM test " ;
$ stmt = $ db ->prepare ($ sql );
$ stmt ->execute ();
$ result = $ stmt ->fetchAll (PDO ::FETCH_ASSOC );
var_dump ($ result );
} catch (PDOException $ e ) {
echo $ e ->getMessage ();
exit;
}
docker container exec -it mysql /bin/sh
CREATE DATABASE sample ;
USE sample;
CREATE TABLE test (id int AUTO_INCREMENT PRIMARY KEY , name VARCHAR (255 ));
INSERT INTO test (name) VALUES (' John' );
http://192.168.99.100:80/index.php