Dnmp

Docker搭建php开发环境

Nginx:

拉取nginx镜像

1
docker pull nginx

启动并运行nginx

1
docker run -d -p 8080:80 -v /Users/gxm/docker/nginx:/etc/nginx/conf.d -v /Users/gxm/docker/html --name=nginx_ nginx

参数说明:

  • -d: 后台运行容器,并返回容器ID
  • -p: 将容器的端口映射到宿主机的端口
  • -v:将宿主机目录挂载到容器目录下
  • —name:为容器指定一个名称
  • -link: 链接另一个容器

PHP7.2

拉取php:7.2-fpm

1
docker pull php:7.2-fpm

启动并运行php

1
2
3
4
docker run -d -p 9000:9000 -v /Users/gxm/docker/html:/usr/share/nginx/html --name=php72 php:7.2-fpm

# 获取运行的php72 在docker中的ip地址
docker inspect php72

MySQL5.7:

1
2
3
docker pull mysql:5.7

docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql mysql:5.7

注意:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# mysql 8.0 的情况下
plugin caching_sha2_password could not be loaded

docker exec -it mysql /bin/bash
# 登录数据库

mysql -uroot -p {your password}
# 使用mysql数据库
mysql>use mysql

# 修改数据库
mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '{your password}';

# 重新修改密码后可连接成功
mysql> alter user 'root'@'%' identified by '123456';

# 刷新数据库
mysql> flush privileges;

参数:

  • -e:指定环境变量,容器中可以使用该环境变量

Nginx—>PHP 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.php index.html index.htm;
#charset koi8-r;

access_log /dev/null;
#access_log /var/log/nginx/nginx.localhost.access.log main;
error_log /var/log/nginx/error.log warn;

#error_page 404 /404.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;
}

# 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
#
location ~ \.php$ {
fastcgi_pass 172.17.0.3:9000; # php72 容器的ip, 获取 docker inspect php容器的名称或容器ID, 假如使用-link 参数的情况下,这里填写链接容器的名称 phpfmp, --link php72:phpfmp
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name; # /var/www/html 是php文件执行目录
}

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


// 加载配置
docker exec -ti nginx_ bash

service nginx reload

PHP安装扩展:

1
2
3
4
5
docker exec -ti php72 bash

cd /usr/local/bin

docker-php-ext-install pdo pdo-mysql // 等等扩展

参数:

  • -t:为容器重新分配一个伪输入终端,通常与 -i 同时使用
  • -i:以交互模式运行容器,通常与 -t 同时使用