zoukankan      html  css  js  c++  java
  • docker一键搭建Nginx+PHP环境(含自动部署命令)

    文章的主要部分是一步一步的教程,文章的最后是我整理好的一键安装命令,自动下载并安装docker,构建镜像,启动容器集群(压缩包内注释覆盖范围达到80%)

    • 大家可以看完教程亲自尝试下,也可以直接执行一键安装命令,整个过程大概10分钟左右,我在四台不同的机器上执行过该命令,由于网络原因,5-15分钟不等。

    • 如本文章内容与通过一键安装下载的不同,以一键安装的为准,一键安装版本会继续更新,v1.3.0版本支持memcache 和 redis。

    • 执行完一键安装后,直接访问 你的IP:8081 访问即可出现phpinfo页面的内容

    • 本次部署,旨在单台服务器上使用docker构建集成环境,并运行Nginx+PHP项目

    宿主机系统:CentOS7+ 内存4G

    安装docker环境

    • 首先更新yum
    $ sudo yum update
    
    • 移除docker旧版本(如果有的话)
    $ sudo yum remove docker 
                      docker-client 
                      docker-client-latest 
                      docker-common 
                      docker-latest 
                      docker-latest-logrotate 
                      docker-logrotate 
                      docker-selinux 
                      docker-engine-selinux 
                      docker-engine
    
    • 安装系统依赖
    sudo yum install -y yum-utils device-mapper-persistent-data lvm2
    
    • 添加软件源信息
    sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
    • 更新yum缓存
    sudo yum makecache fast
    
    • 安装docker-ce
    sudo yum -y install docker-ce
    
    • 启动docker 后台服务
    sudo systemctl start docker
    

    建议使用阿里镜像加速,百度一下就有教程,步骤很简单,否则下载docker官方镜像可能会很慢

    • 测试运行 hello-world
    [root@runoob ~]# docker run hello-world
         docker  run 命令会先在本地查找 hello-world镜像,如果本地没有会自动下载一个到本地,然后在运行hello-world
    

    • 删除docker-ce(如想卸载docker可以执行下面的命令)
    $ sudo yum remove docker-ce
    $ sudo rm -rf /var/lib/docker
    
    • 现在我们已经有了docker环境,下面我们要用docker 构建 Nginx和PHP, 关于数据库,我们还是使用之前的数据库服务器,

    下面使用Dockerfile 构建 Nginx环境,

    • 如想详细了解Dockerfile知识的,推荐 https://www.cnblogs.com/jsonhc/p/7767669.html

    • 在/root目录下 新建 docker-env文件夹,这里面包含nginx和php的镜像构建的所有文件和配置,以及Dockerfile

    cd /root
    
    mkdir docker-env     //建立文件夹
    
    cd docker-env/
    
    mkdir nginx             //存放nginx相关文件
    
    cd nginx/
    
    touch Dockerfile && mkdir conf && mkdir logs && mkdir html && mkdir www    //创建Dockerfile文件,建立nginx的配置目录和日志等目录
    
    
    • nginx文件夹下的Dockerfile内容如下, 用来构建属于自己的nginx镜像
    [root@mdm nginx]# cat Dockerfile 
    # 基础镜像
    FROM centos
    
    # 维护者
    MAINTAINER 271648298@qq.com
    
    # 安装wget下载工具
    RUN yum install -y wget 
    
    # 切换到usr/lcoal/src/目录,相当于cd,并可以用cd 代替, 但docker官方不建议用cd
    WORKDIR /usr/local/src
    
    # 添加远程文件到当前文件夹, 注意:后面有个点(.) 代表当前目录。ADD可以添加远程文件到镜像,但COPY仅可以添加本地文件到镜像中。
    ADD http://nginx.org/download/nginx-1.17.0.tar.gz .
    
    # RUN,在镜像内运行解压命令
    RUN tar zxvf nginx-1.17.0.tar.gz
    
    # 切换目录
    WORKDIR /usr/local/src/nginx-1.17.0
    
    # 更新yum,可不执行
    # RUN yum -y update 
    
    # 安装必要的软件和添加nginx用户
    RUN yum install -y gcc gcc-c++ glibc make openssl-devel
    RUN yum install -y libxslt-devel -y gd-devel GeoIP GeoIP-devel pcre pcre-devel
    RUN  useradd -M -s /sbin/nologin nginx
    
    # 挂载卷,测试用例(这里的挂载卷,不可以指定本机的目录,不够灵活,一般会在 启动容器时通过 -v 参数指定挂载卷,或在docker-compose.yaml文件中指定,都可以指定本地目录)
    VOLUME ["/data"]
    
    # 编译安装nginx
    RUN ./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-file-aio --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_degradation_module --with-http_stub_status_module && make && make install
    
    # 切换到Nginx的配置目录
    WORKDIR /usr/local/nginx/conf
    
    # 建立子配置文件夹,个人爱好,可以不建,或者叫其它名称都可以,但最好不要带特殊符号,
    RUN mkdir vhost
    
    
    # 设置变量,执行命令时,就可以省略前缀目录了	
    ENV PATH /usr/local/nginx/sbin:$PATH
    
    
    # 暴露端口
    EXPOSE 80
    
    # the command of entrypoint
    ENTRYPOINT ["nginx"]
    
    # 执行命令,数组形式, "-g daemon off;" 使我们运行容器时,容器可以前台运行,不会退出
    CMD ["-g", "daemon off;"]
    
    
    • 下面我们先通过一条简单的命令构建nginx镜像
    [root@mdm nginx]# docker build -t centos_nginx:self .    //注意,最后有个点(英文句号),    centos_nginx 是镜像名称,self是打的标签,跟版本号一样的意思
    
    • 然后可以通过docker images 命令查看新构建的镜像,然后通过该镜像启动一个容器,我们要进入该容器并记住里面的目录和配置,因为以后我们可能所有的服务器和环境都使用该容器。
        docker run -d -p 8082:80 --name=test_nginx centos_nginx:self    //启动一个容器,输出成功会提示一串字符串
                -d  是守护进程运行的意思,即容器后台运行不会退出
                -p  映射端口号,宿主机端口:容器端口
                --name 容器名称,
                最后的  centos_nginx:self   是使用的镜像:版本号
        docker ps -a                                                                                   //查看所有容器列表,显示如下,说明nginx容器已经正常启动
    
        CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
        d51f2c95b66c        centos_nginx:self   "nginx -g 'daemon of…"   5 seconds ago       Up 4 seconds        0.0.0.0:8082->80/tcp   test_nginx
        
        通过 curl 127.0.0.1:8082 命令,能看到  Welcome to nginx  等英文提示,即说明一切OK
    
        下面我们进入容器,进入容器有很多方式,还可以通过ssh进入,这里我只介绍我常用的方式
    
        docker exec -it   d51f2c95b66c   /bin/bash      //这种方式进入,不会造成容器的关闭, docker attach 进入再退出会造成容器关闭,  后边的 /bin/bash  也可以换成    /bin/sh(比如alpine 基础镜像)
        
        进来后查看Nginx的配置文件
    
            [root@d51f2c95b66c /]# cd /usr/local/nginx/
            [root@d51f2c95b66c nginx]# ls
            client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
    
        可以自己了解下这个版本的nginx的目录结构,方便后期配置
        通过exit 命令退出容器即可
    
    • 下面我们进入/root/docker-env/nginx/conf 文件夹,
    cd /root/docker-env/nginx/conf
    
    touch nginx.conf       // 该文件将来要挂载到容器中,作为Nginx的配置文件,
    
    你可以通过  docker cp d51f2c95b66c :/usr/local/nginx/conf/nginx.conf /root/docker-env/nginx/conf     复制一份Nginx容器的原生配置文件,也可以使用下面我的nginx配置文件
    
    
    • 我的nginx.conf文件如下, 注意对应nginx.conf中日志和子配置文件的目录,保证都存在,不存在的就进入容器创建对应的目录
    [root@mdm conf]# cat nginx.conf
    
    user  nginx;
    worker_processes  1;
    
    error_log  /usr/local/nginx/logs/error.log warn;
    pid        /usr/local/nginx/logs/nginx.pid;
    
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        	include       /usr/local/nginx/conf/mime.types;
        	default_type  application/octet-stream;
    
        	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';
    
        	access_log  /usr/local/nginx/logs/access.log  main;
    
        	server_names_hash_bucket_size 128;
            client_header_buffer_size 32k;
            large_client_header_buffers 4 32k;
            client_max_body_size 50m;
    
            sendfile   on;
            tcp_nopush on;
    
            keepalive_timeout 60;
    
            tcp_nodelay on;
    
            fastcgi_connect_timeout 300;
            fastcgi_send_timeout 300;
            fastcgi_read_timeout 300;
            fastcgi_buffer_size 64k;
            fastcgi_buffers 4 64k;
            fastcgi_busy_buffers_size 128k;
            fastcgi_temp_file_write_size 256k;
    
            gzip on;
            gzip_min_length  1k;
            gzip_buffers     4 16k;
            gzip_http_version 1.1;
            gzip_comp_level 2;
            gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss;
            gzip_vary on;
            gzip_proxied   expired no-cache no-store private auth;
            gzip_disable   "MSIE [1-6].";
    
            #limit_conn_zone $binary_remote_addr zone=perip:10m;
            ##If enable limit_conn_zone,add "limit_conn perip 10;" to server section.
    
            server_tokens off;
            access_log off;
        	include /usr/local/nginx/conf/vhost/*.conf;
    		
    server {
            listen       80;
            server_name  localhost;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
    
            location / {
                root   html;
                index  index.html index.htm;
            }
    
            #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   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   127.0.0.1:9000;
            #    fastcgi_index  index.php;
            #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;
            #}
        }
    
    
        # another virtual host using mix of IP-, name-, and port-based configuration
        #
        #server {
        #    listen       8000;
        #    listen       somename:8080;
        #    server_name  somename  alias  another.alias;
    	
        #    location / {
        #        root   html;
        #        index  index.html index.htm;
        #    }
        #}
    
    
        # HTTPS server
        #
        #server {
        #    listen       443 ssl;
        #    server_name  localhost;
    
        #    ssl_certificate      cert.pem;
        #    ssl_certificate_key  cert.key;
    
        #    ssl_session_cache    shared:SSL:1m;
        #    ssl_session_timeout  5m;
    
        #    ssl_ciphers  HIGH:!aNULL:!MD5;
        #    ssl_prefer_server_ciphers  on;
    
        #    location / {
        #        root   html;
        #        index  index.html index.htm;
        #    }
        #}
    
    }
    		
    
    
    • 现在nginx 的配置基本完成,我们停止刚才启动的容器,释放8082端口,然后通过挂载目录的形式启动
    docker  stop  d51f2c95b66c
    
    
    docker run -d -p 8082:80 -v /root/docker-env/nginx/logs:/usr/local/nginx/logs -v /root/docker-env/nginx/conf/nginx.conf:/usr/local/nginx/conf/nginx.conf -v /root/docker-env/nginx/conf/vhost:/usr/local/nginx/conf/vhost -v /www:/www centos_nginx:self
    //这样的话,nginx的配置文件和项目所在目录/www都挂载上了,可以在宿主机修改配置文件并访问nginx, nginx的基本配置到此结束。
    

    PHP镜像的构建

    • 建立php文件夹
    cd /root/docker-env
    mkdir php
    cd php
    touch Dockerfile
    
    • php的Dockerfile文件内容如下:
    [root@guangai-app php]# cat Dockerfile 
    
    
    FROM php:7.1-fpm-alpine3.9
    
    MAINTAINER 271648298@qq.com
    
    
    # install redis
     RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories 
        && apk update 
        && apk add --no-cache libmcrypt-dev freetype-dev libjpeg-turbo-dev 
        && docker-php-ext-install mcrypt pdo_mysql 
        && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-png-dir=/usr/include/ 
        && docker-php-ext-install -j$(nproc) gd 
        && mkdir -p /usr/src/php/ext/redis 
        && curl -L https://github.com/phpredis/phpredis/archive/3.1.6.tar.gz | tar xvz -C /usr/src/php/ext/redis --strip 1 
        && echo 'redis' >> /usr/src/php-available-exts 
        && docker-php-ext-install redis
    
    
    docker build -t alpine_php:self .    //注意,最后有个点(.)
    
    
    • 根据此镜像,启动一个容器,并关联/www目录
    docker run --name myphp-fpm -v /root/docker-env/nginx/www:/www -d alpine_php:self
    
    • 现在我们有了 Nginx 和 PHP 的镜像,并且他们都能启动,PHP镜像中还包含了一些必须的扩展,那么我们新开一台服务器的时候如何部署呢,
    • 用命令也是可以的,不过这里介绍docker-compose这个轻量级的容器编排工具
    • 安装docker-compose
    sudo curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose   //这里可能会很慢
    
    sudo chmod +x /usr/local/bin/docker-compose
    
    docker-compose --version
    
    • 此时你已经安装好了docker-compose工具, 下面来看看如何使用,
    • 进入我们的docker-env文件夹
    [root@guangai-app ~]#cd /root/docker-env
    [root@guangai-app docker-env]# ls
    docker-compose.yml  nginx  php
    
    可以看到,这里有我们刚完成的nginx 目录和 php 目录,除此之外还有一个docker-compose.yml文件
    
    • docker-compose.yml文件内容如下
    [root@guangai-app docker-env]# cat docker-compose.yml 
    nginx:
        build: ./nginx
        volumes: 
            - /root/docker-env/nginx/html:/usr/share/nginx/html
            - /root/docker-env/nginx/conf/nginx.conf:/usr/local/nginx/conf/nginx.conf
            - /root/docker-env/nginx/conf/vhost:/usr/local/nginx/conf/vhost
            - /root/docker-env/nginx/logs:/usr/local/nginx/logs
            - /www:/www
        ports: 
            - "8081:80"
        links: 
            - php
    php:
        build: ./php
        volumes:
            - /www:/www
            
    
    • 我们要在/root/docker-env/nginx/conf/vhost 创建一个nginx的配置文件(test-php.conf), 供nginx容器使用,test-php.conf 文件内容如下
    • 当然第一次时,这个文件你可以写的尽可能简单,只要能解析php就行。
    [root@guangai-app vhost]# cat test-php.conf 
    server {
        listen       80;
        server_name  localhost;
    
    	location / {
    		    root   /www/api_wx_klagri_com_cn/public;
                index  index.php index.html index.htm;
                if (!-e $request_filename) {
                  rewrite ^(.*)$ /index.php?s=$1 last;
                  break;
                }
            }
    
    
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
    		root   /www/cms/public;
        }
    
    	location ~ .php$ {
                    root           /www/api_wx_klagri_com_cn/public;
                    fastcgi_pass    php:9000;
                    fastcgi_index   index.php;
                    #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
                    fastcgi_split_path_info ^(.+.php)(.*)$;
                    fastcgi_param PATH_INFO $fastcgi_path_info;
                    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
                    include        fastcgi_params;
                    set $real_script_name $fastcgi_script_name;
                    if ($fastcgi_script_name ~ "^(.+?.php)(/.+)$") {
                            set $real_script_name $1;
                            set $path_info $2;
                    }
                    fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
                    fastcgi_param SCRIPT_NAME $real_script_name;
                    fastcgi_param PATH_INFO $path_info;
    				include		   vhost/my_params/api_wx.conf;
            }
    
    
    }
    
    
    • 配置好nginx,下面我们通过docker-compose启动nginx+php
    docker-compose up -d      //-d  后台运行
    
    修改nginx配置后,通过  docker-compose up -d --force-recreate  重启
    
    • 然后通过你ip+端口号访问 ,比如http://59.110.217.236:8081/index.php

    • OK

    以上是我整理出来的docker部署Nginx + PHP.x + Redis + Memcache的步骤,因为我还有核心开发工作要做,中途中断了好几次,不敢保证质量,仅做参考,如按步骤执行有问题可以留言

    后期我整理过的最新一键 安装命令如下, root用户执行,建议在/root目录下执行, 执行后,直接访问8081端口看到熟悉的phpinfo页面即代表成功

    #  请先在linux上安装unzip后执行下面的命令(安装unzip, yum install -y unzip)。
    cd /root && wget https://github.com/eternity-wdd/docker-env/archive/master.zip && unzip master.zip && mv docker-env-master docker-env && cd docker-env && /bin/bash init.sh
    #  更多详情见下载文件中的README.md
    
    • 需要注意的是:服务器环境内存大于4G, 内核版本大于3.10。个人小霸服务器王基本不可以,本地虚拟机未尝试运行此命令,第一次执行未成功,请再执行一遍(个例)。
    • Nginx和PHP的配置文件,日志文件都在docker-env文件夹对应的目录中。
    • 如需停止环境,可以进入docker-env文件夹 执行 docker-compose stop 命令 再次启动执行 docker-compose up -d 即可
    • PHP扩展自行安装,已有部分扩展,gd,mysqlpdo, redis等

    如果上面的步骤成功,你可以尝试自定义修改自己的环境配置文件

    • 修改nginx配置后,通过 docker-compose up -d --force-recreate 重启, 如需重新编译 可以在最后加上 docker-compose up -d --force-recreate --build
    • 通过8081端口直接访问,可以显示phpinfo() 页面即成功, 安装包内有完整的说明文件,包括域名测试,注释覆盖率贼高。适合新手看~
    • 注意,自动安装脚本只适合在未安装docker的服务器上使用,否则会卸载旧版本安装最新版本,如果之前有docker并修改了docker的配置(比如用于IDE远程连接),配置将会被覆盖,容器会exit,但可以再次启动。
  • 相关阅读:
    jQuery初学:find()方法及children方法的区别分析
    百万级访问网站前期的技术准备
    TCP/IP协议三次握手与四次握手流程解析
    TCP/IP详解学习笔记
    Dubbo框架入门介绍
    如何提高Web服务端并发效率的异步编程技术
    杂 -- 有关程序员
    关于高性能的那点事
    大型网站的灵魂- 性能
    分布式java应用
  • 原文地址:https://www.cnblogs.com/lz0925/p/10985700.html
Copyright © 2011-2022 走看看