使用 docker 搭建 nginx+php-fpm 环境 (两个独立镜像)

  1. 获取 nginx 镜像
docker search nginx
docker pull nginx
  1. 使用nginx镜像开启 nginx 应用容器
docker run -d --name nginx -p 8080:80 -v /tmp:/usr/share/nginx/html docker.io/nginx 

说明

  1. -d 后台运行
  2. --name 自定义容器名称
  3. -p 8080:80 宿主机的8080 映射到容器的80端口
  4. -v 宿主机 tmp 目录映射容器地址(nginx服务器项目默认路径)

在/tmp 目录下新建一个 index.html 里面打个 hello nginx
访问 127.0.0.1:8080 正确的情况下会出现该文件内容

  1. 获取 php-fpm 镜像
docker search php-fpm
docker pull bitnami/php-fpm

4.运行 php-fpm

docker run -d -v /tmp:/usr/share/nginx/html --name php-fpm docker.io/bitnami/php-fpm 
  1. 查看 php-fpm IP
docker inspect php-fpm | grep "IPAddress"
  1. 修改 nginx 配置文件 使他跟 php-fpm 关联起来
#copy 配置文件
docker cp nginx:/etc/nginx/conf.d/default.conf ./default.conf
vim ./default.conf

#copy 下面的
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

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

    #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$ {
        root           html;
        fastcgi_pass   172.17.0.2:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html/$fastcgi_script_name;
        include        fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
# 修改 fastcgi_pass   127.0.0.1:9000;  为:
# fastcgi_pass   172.17.0.2:9000;
# 其中 172.17.0.2  上面查看 IP 获取的 每次都不一样
#覆盖到 nginx 
docker cp ./default.conf nginx:/etc/nginx/conf.d/default.conf
#重启 nginx
docker restart nginx
  1. 新建 /tmp/index.php
<?php
    echo phpinfo();
  1. 访问本地 127.0.0.1 即可
  2. docker 常用命令

进入容器

docker exec -it nginx /bin/bash

复制容器内的配置到宿主机器

docker cp nginx:/etc/nginx/conf.d/default.conf ./default.conf

复制宿主机器文件到容器

docker cp ./default.conf myNginx:/etc/nginx/conf.d/default.conf

docker 重启容器

docker restart nginx

停止所有容器

docker stop $(docker ps -a -q)

删除所有容器

docker rm $(docker ps -a -q)

猜你喜欢

转载自www.cnblogs.com/wangmy/p/10441084.html