docker中安装php+mysql+nginx

1、拉取镜像

php和mysql不要用最新的版本,听说有很多坑

docker pull nginx
docker pull php:7.1-fpm
docker pull mysql:5.7

2. 创建文件夹

# 网站目录
mkdir -p /data/www
# nginx 配置
mkdir -p /data/nginx/conf.d

# mysql数据
mkdir -p /data/mysql/data
# mysql配置
mkdir -p /data/mysql/conf.d

3、创建 Nginx 容器

将nginx配置文件nginx.conf复制到主机/data/nginx目录中

docker run --rm nginx cat /etc/nginx/nginx.conf > /data/nginx/nginx.conf

创建nginx

docker run --name nginx \
-v /data/www:/usr/local/html \
-v /data/nginx/conf.d:/etc/nginx/conf.d \
-v /data/nginx/nginx.conf:/etc/nginx/nginx.conf:ro \
--net=host \
-d nginx

这里会启动失败,因为缺少个default.conf配置,后面php容器创建好后会添加

4. 创建 PHP 容器

docker run --name php-fpm \
-v /data/www:/var/www/html \
-d php:7.1-fpm

5. 查看 PHP 容器的IP

docker inspect php-fpm --format='{{.NetworkSettings.IPAddress}}'

# 返回 IP
172.17.0.2

6. 创建 Nginx 配置文件

vim /data/nginx/conf.d/default.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.php index.html index.htm;
    }

    location ~ \.php(.*)$ {
        root          /var/www/html;           # php 容器的目录,进 php 容器查看
        fastcgi_pass  172.17.0.2:9000;         # php 容器的IP
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

修改后重启一下 nginx 容器

docker restart nginx    

7. 测试

编写测试页

echo "<?php phpinfo(); ?>" > /data/www/info.php

测试

curl http://127.0.0.1/info.php

8. 创建 MySQL 容器

docker run --name mysql \
-p 3306:3306 \
-v /data/mysql/conf.d:/etc/mysql/conf.d \
-v /data/mysql/data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7

9. PHP 安装 MySQLI 扩展

# 进入容器
docker exec -it php-fpm /bin/bash

# 安装 pdo_mysql mysqli
docker-php-ext-install pdo_mysql mysqli

# CTRL + D 退出容器
docker restart php-fpm

10. 连接 MySQL测试

查看mysql的ip

docker inspect mysql --format='{{.NetworkSettings.IPAddress}}'

# 返回 IP
172.17.0.3

编辑连接测试文件 vim /data/www/conn.php

<?php
        $serve = '172.17.0.3:3306';
        $username = 'root';
        $password = '123456';
        $dbname = 'mysql';

        $mysqli = new Mysqli($serve,$username,$password,$dbname);

        if ($mysqli->connect_error) {
                die('connect error:'.$mysqli->connect_errno);
        }

        $mysqli->set_charset('UTF-8');
        $result = $mysqli->query('select * from user');
        $data = $result->fetch_all();
        print_r($data);
?>

测试

curl http://127.0.0.1/conn.php

本文参考:https://blog.csdn.net/mshxuyi/article/details/105409457

0%