基于Docker部署LNMP架构

环境部署

IP 操作系统
192.168.253.42 centos7.6

 

关闭防火墙,selinux

systemctl stop firewalld
sed -ri 's/^(SELINUX=).*/\1disabled/g'  /etc/selinux/config   //永久关闭selinux
systemctl disable firewalld    //开机不启动防火墙

docker 拉取所需镜像(mysql 5.6,nginx:latest,php7.0-fpm)

docker pull mysql:5.6
docker pull nginx
docker pull php:7.0-fpm

 

 启动容器mysql

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

启动php容器

docker run -d -v /var/log/nginx:/var/www/html -p 9000:9000 --link m_mysql:mysql --name p_php php:7.0-fpm

参数说明
-d 让容器在后台运行
-p 添加主机到容器的端口映射
-v 添加目录映射,主机上的/var/nginx/www/html映射到容器里面 的/var/www/html,如果主机没有这个目录就创建这个目录,或者映射别的目录,但是后面路径要统一
-name 容器的名字
-link 容器与另外一个容器建立联系,这样就可以在当前的容器去使用另一个容器里的服务

启动nginx容器

 docker run -d -p 80:80 -v /var/log/nginx:/var/www/html --link p_php:php --name n_nginx nginx

php容器配置

进入到我们的容器,然后我们在/var/www/html目录下新建一个index.php文件

touch index.php

我们发现我们在容器里的/var/www/html目录中新建的文件也在主机的/var/nginx/www/html目录中,因为在创建容器的时候,我们已经把主机中的目录挂载到了容器中去了。

docker-php-ext-install pdo_mysql

然后我们可以通过命令php -m查看我们的php的所有扩展模块,我们可以去看到我们刚刚安装的pdo_mysql扩展也在里面

 

 

修改Nginx 的配置文件,使他支持php ,方式有多种,可以拷贝进入,也可以进去直接修改

 

 

server {
    listen       80;
    server_name  localhost;
    location / {
        root   /var/www/html;                       // 修改这里默认的路径
        index  index.html index.htmi index.php;     //这里加入添加php的方式
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    location ~ \.php$ {
        root           html;
        fastcgi_pass   92fc30be9a85:9000;        //这里可以用容器ID,也可以用容器IP,都具备唯一性
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/html/$fastcgi_script_name;      //修改这里的路径
        include        fastcgi_params;
    }
}

nginx -s reload 检测配置文件是否正确

最后测试一下安装是否成功

[root@mq01 ~]# cat /var/log/nginx/index.php
<?php
    $db = new PDO('mysql:host=172.17.0.2;dbname=test', 'root', '123456');
   try {
      echo "<table border='2' width='300'>
            <tr>
            <th>id</th><th>name</th>
            </tr>";

      foreach ($db->query('select * from test') as $row){
         echo "<tr>";
         echo "<td>".$row['id']."</td>";
         echo "<td>".$row['name']."</td>";
         echo "</tr>";
        }
        echo "</table>";
        $db = null;
  } catch (PDOException $e){
      echo $e->getMessage();
   }
?>

 

 

 查看IP:

docker inspect --format '{{ .NetworkSettings.IPAddress }}' <container-ID>

建数据库:

CREATE DATABASE IF NOT EXISTS test default charset utf8 COLLATE utf8_general_ci;
create table test (id int not null auto_increment,name varchar(20) not null default '',constraint pk_test primary key(id)) ;

 

注意:如果修改了index.php文件记得要重启php容器,不然会报错

posted on 2020-07-14 15:02  lanist  阅读(247)  评论(0编辑  收藏  举报