Install php nginx mysql phpmyadmin on docker


Ta có cấu trúc thư mục sau:

|- docker-compose.yml
|- Dockerfile
|- default.conf
|- src
    |- index.php

Ta xem file docker-compose.yml

version: "3.9"

services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
    volumes: 
      - ./src:/var/www/html
      - ./default.conf:/etc/nginx/conf.d/default.conf
    links:
      - php-fpm

  php-fpm:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ./src:/var/www/html 


  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: 123456
    volumes:
      - "mysql_data:/var/lib/mysql" # data container

  phpmyadmin:
    image: phpmyadmin
    ports:
      - "8082:80"
    environment:
      PMA_HOST: mysql
    depends_on:
      - mysql

volumes:
  mysql_data:
    driver: local

Thư mục src là nơi chứa code.

Dockerfile

FROM php:fpm
RUN docker-php-ext-install pdo pdo_mysql
RUN pecl install xdebug && docker-php-ext-enable xdebug

File nginx config, default.conf

server {
    index index.php index.html;
    server_name phpfpm.local;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html;
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php-fpm:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

Test dùng file index.php

<?php
$servername = "mysql";
$username = "root";
$password = "123456";

try {
  $conn = new PDO("mysql:host=$servername;dbname=test", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>

Ta chạy các container bằng câu lệnh

docker-compose up -d 

Ta muốn tắt các container.

docker-compose down

Ta truy cập web

http://localhost:8080 

Ta truy cập phpmyadmin

http://localhost:8082 

Với user là root, pass là 123456