帮助初次接触 docker 的 php 开发者,快速构建 docker 化的 php 开发环境。
要求
请确保已经安装 docker 和 docker-compose
环境构成
- php7.2
- nginx
- mysql 5.7
目录结构
-
docker-compose.yml
- (环境编排文件) html
- tp5 (作为volume,存放项目代码) mysql
- (作为volume,存放mysql数据文件) nginx
- default.conf (作为volume,存放nginx配置文件) php
- Dockerfile
nginx default.conf文件 (此处部署的是tp5的项目)
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html/tp5/public;
index index.php index.html index.htm;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
error_page 404 /404.html;
location = /40x.html {
root /usr/share/nginx/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;
}
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
}
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
# PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI协议默认配置.
# Fastcgi服务器和程序(PHP,Python)沟通的协议.
location ~ \.php$ {
# php容器的网站根目录
root /var/www/html/tp5/public;
# 设置监听端口
fastcgi_pass php:9000;
fastcgi_index index.php;
# 设置脚本文件请求的路径
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# 引入fastcgi的配置文件
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
php Dockerfile文件
FROM php:7.2-fpm
RUN apt-get update && apt-get install -y \
&& docker-php-ext-install pdo_mysql && docker-php-ext-enable pdo_mysql \
&& docker-php-ext-install mysqli && docker-php-ext-enable mysqli
docker-compose.yml文件
version: '3'
services:
nginx:
image: nginx
ports:
- "8000:80"
depends_on:
- php
volumes:
- "$PWD/nginx/default.conf:/etc/nginx/conf.d/default.conf"
- "$PWD/html:/usr/share/nginx/html"
networks:
- app_net
container_name: "docker-www-nginx"
php:
build: ./php
ports: ["9000"]
links:
- mysql
volumes:
- "$PWD/html:/var/www/html"
networks:
- app_net
container_name: "docker-www-php"
mysql:
image: mysql:5.7
ports: ["3306"]
environment:
- MYSQL_ROOT_PASSWORD=root
volumes:
- "$PWD/mysql:/var/lib/mysql"
networks:
- app_net
container_name: "docker-www-mysql"
networks:
app_net:
在docker-www 目录下运行docker-compose up 即可将php项目运行起来
测试访问,访问成功
如果以后需要项目迁移只需要以下几步即可完成自动化构建
- 安装 docker 和 docker-compose
- 将 docker-www 目录复制到新服务器
- 在 docker-www 目录运行 docker-compose up 命令
QQ交流群: 294088839