Docker でローカル環境構築 PHP + Nginx

環境

  • MacBook Pro (macOS: Big Sur)

ファイル構成

/app
  └ /public
      ├ index.html
      └ index.php
docker-compose.yaml
Dockerfile
/nginx
  └ default.conf

サンプルコード

docker-compose.yaml

  • app と php それぞれに volumes: に「- ./app:/var/www/html」 してるのは、
    app だけに記述すると PHP が動かず、
    php だけに記述すると PHP 以外のファイルを更新するとうまく同期されなかったため。
version: "3"

services:
    app:
        build:
            context: .
        volumes:
            - ./app:/var/www/html
            - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
        ports:
            # http://localhost:8080/
            - "8080:80"
        depends_on:
            - php
    php:
        # https://hub.docker.com/_/php
        image: php:fpm
        volumes:
            - ./app:/var/www/html

Dockerfile

FROM nginx:1

WORKDIR /var/www/html

COPY ./app /var/www/html
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf

app/public/index.html

  • 適当に書く。
<!DOCTYPE html>
<html lang="ja" dir="ltr">
	<head>
		<meta charset="utf-8">
		<title>docker-sample/nginx-php-fpm</title>
	</head>
	<body>
		<h1>hello world</h1>
		<p>docker-sample/nginx-php-fpm</p>
		<p><a href="index.php">index.php &gt;&gt;</a></p>
		<hr>
		html
	</body>
</html>

app/public/index.php

  • 適当に書く。
  • phpinfo() してみる。
<!DOCTYPE html>
<html lang="ja" dir="ltr">
	<head>
		<meta charset="utf-8">
		<title>docker-sample/nginx-php-fpm</title>
	</head>
	<body>
		<h1>hello world</h1>
		<p>docker-sample/nginx-php-fpm</p>
		<p><a href="index.html">index.html &gt;&gt;</a></p>
		<hr>
		<?php phpinfo(); ?>
	</body>
</html>

nginx/default.conf

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    root /var/www/html/public;

    index index.php index.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # using PHP
    # https://gist.github.com/md5/d9206eacb5a0ff5d6be0
    #
    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
        }

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;

        fastcgi_pass   php:9000;
        fastcgi_index  index.php;
    }

    # using PHP Framework
    #
    try_files $uri $uri/ @rewrite;

    location @rewrite {
        rewrite ^(.*)$ /index.php?_url=$1;
    }
    location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
        root /var/www/html/public;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny  all;
    }
}

実行

$ cd /path/to/your/project

# http://localhost:8080 にアクセス
$ docker-compose up