Skip to content

Instantly share code, notes, and snippets.

@katai5plate
Created July 7, 2020 04:43
Show Gist options
  • Save katai5plate/75755ea1312adeb0114ca8e250fc2f5c to your computer and use it in GitHub Desktop.
Save katai5plate/75755ea1312adeb0114ca8e250fc2f5c to your computer and use it in GitHub Desktop.
docker で PHP

1.

  • docker-compose.yml
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:
  • php/Dockerfile
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

2.

docker network create myphp
docker-compose up -d

3. join to php /var/www/html

docker container exec -it php bash
  • index.php
<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;
    }

4. join to mysql

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');

5.

http://192.168.99.100:80/index.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment