Cane's Blog

Cane

【Docker】安装php、nginx

15
2019-08-22

安装 PHP

docker pull php:7.1-fpm

docker run -p 9000:9000 --name php -v /docker/nginx/php:/home -d php:7.1-fpm

安装 Nginx

docker pull nginx

docker run -p 80:80 --name nginx -v /docker/nginx/php:/www -v /docker/nginx/conf.d:/etc/nginx/conf.d -d nginx

启动 nginx 的时候,首先把本机的 /docker/nginx/php 映射到 nginx 的 /www 目录,然后把本机的 /docker/nginx/conf.d 目录映射到 docker 的 /etc/nginx/conf.d 目录

这样,要想给 nginx 添加配置,只需在本机的 /etc/nginx/conf.d 目录新建 *.conf 文件即可

nginx 默认访问 /www 目录,把本机的 /docker/nginx/php 映射到 nginx 的 /www 目录,同时把 php 的默认 /home 路径也映射到 /docker/nginx/php,如下

2019-08-22-10-57-37.png接着给在本机的 /docker/nginx/nginx.d 中新建 *.conf 的文件来给 nginx 添加配置,如下

2019-08-22-11-06-30.png添加完毕之后,进入到 nginx 中(docker exec -it nginx bash)执行 service reload nginx 来重启 nginx即可

若上面的 /home 配置错误会提示 「file not found」错误,查看 error.log 日志文件提示「Primary script unknown" while reading response header from upstream」

补充

查看 docker 容器中的 nginx 的配置文件

docker exec -it nginx bash
cd /etc/nginx && cat nginx.conf

2019-08-22-11-09-54.pngnginx 配置

server {
    listen       80;
    server_name  127.0.0.1;

    root    /www;
    location / {
        index  index.html index.htm index.php l.php;
       autoindex  off;
    }
    location ~/d/file/p.*\.php$ {
        deny all;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

    location ~ \.php(.*)$  {
        fastcgi_pass   172.17.0.4:9000;
        fastcgi_index  index.php;
        fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
        fastcgi_param  SCRIPT_FILENAME  /home$fastcgi_script_name;
        fastcgi_param  PATH_INFO  $fastcgi_path_info;
        fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;

        include        fastcgi_params;
    }
    gzip on; 
    gzip_min_length 1k; 
    gzip_buffers 4 16k; 
    gzip_comp_level 2; 
    gzip_types text/plain application/x-javascript application/javascript text/javascript text/css application/xml application/x-httpd-php image/jpeg image/gif image/png; 
    gzip_vary on; 
    gzip_disable "MSIE [1-6]\.";
}

最下面是开启 nginx Gzip 配置,location ~d/file/p.*\.php$ {...} 是在特定正则规则下,禁止 php 的访问