Docker部署nginx+php环境的全过程(简单可用!)

以下是一份关于“Docker部署nginx+php环境的全过程”的攻略。该攻略主要分为三个部分:准备工作、Docker环境搭建、部署nginx和php环境。

准备工作

在开始操作前,需要确保已经安装好以下软件:

  • Docker(至少1.13.0版本)
  • Docker Compose(至少1.10.0版本)

Docker环境搭建

1. 创建Docker环境

创建一个文件夹,用于存放Docker环境的配置文件:

mkdir docker-env
cd docker-env

创建docker-compose.yml文件:

version: "3"

services:
  nginx:
    image: nginx:alpine
    ports:
      - 80:80
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./logs/nginx:/var/log/nginx
      - ./www:/var/www/html
    networks:
      - frontend

  php:
    image: php:7.2-fpm-alpine
    volumes:
      - ./www:/var/www/html
    networks:
      - frontend

networks:
  frontend:

创建一个文件夹用于存放你的nginx配置文件和php代码文件:

mkdir www

创建一个nginx配置文件(名为nginx.conf):

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/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 /var/log/nginx/access.log main;

    sendfile on;
    #tcp_nopush on;

    #keepalive_timeout 0;
    keepalive_timeout 65;

    #gzip on;

    include /etc/nginx/conf.d/*.conf;
}

2. 启动Docker环境

在项目目录下执行以下命令启动Docker环境:

docker-compose up -d

部署nginx和php环境

在执行了上述命令后,你即完成了一个简单的nginx+php环境的搭建。现在,你可以在www文件夹中添加你的php代码文件,通过浏览器访问http://localhost,从而访问到自己的php代码了。

示例1:

假设你的项目目录如下:

/path/to/project/
├── docker-env/
│   ├── docker-compose.yml
│   ├── nginx.conf
│   └── logs/
└── www/
    └── index.php

在www目录下创建一个php文件(名为index.php):

<?php
phpinfo();

然后,在项目目录下启动Docker环境:

cd /path/to/project/
docker-compose up -d

最后,在浏览器中输入http://localhost,你将看到PHP版本信息的展示页面。

示例2:

以下为一个使用Dockerfiledocker-compose的例子,该例子使用的是laravel框架。假设你的项目目录如下:

/path/to/project/
├── docker-env/
│   ├── docker-compose.yml
│   └── nginx/
│       ├── default.conf
│       └── snippets/
│           ├── fastcgi-php.conf
│           └── ssl-params.conf
└── app/
    ├── Dockerfile
    ├── .env
    ├── .env.example
    ├── composer.json
    ├── composer.lock
    └── ...   
  1. 在docker-env目录下的docker-compose.yml和nginx目录下创建一个default.conf文件:
version: "3"

services:
  nginx:
    image: nginx:stable-alpine
    container_name: ${NGINX_CONTAINER_NAME}
    volumes:
      - ./nginx:/etc/nginx/conf.d/
      - ./logs/nginx:/var/log/nginx
      - ./certs:/etc/ssl/certs
      - ../app/public:/var/www/html:ro
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - php
    restart: always

  php:
    build:
      context: ../app
      dockerfile: Dockerfile
    container_name: ${PHP_CONTAINER_NAME}
    environment:
      - DB_HOST=${DB_HOST}
      - DB_DATABASE=${DB_DATABASE}
      - DB_USERNAME=${DB_USERNAME}
      - DB_PASSWORD=${DB_PASSWORD}
    volumes:
      - ../app:/var/www/html/
    expose:
      - 9000
    restart: always

networks:
  frontend:

volumes:
  dbdata:
  1. 在docker-env目录下的nginx/snippets目录中,创建一个fastcgi-php.conf文件和一个ssl-params.conf文件:

fastcgi-php.conf

# File based on https://gist.github.com/diegocasmo/692e67fac9f21134e34e990b50f78d7b
# and https://gist.github.com/wpscholar/a49594e2e2b918f4cff9

# Define PHP 7 & 5.6 socket locations
set $upstream_app_php72 127.0.0.1:9000;
set $upstream_app_php56 127.0.0.1:9056;

# Choose the version of the ingress controller you want to use.
# This is used to tell NGINX which upstream PHP server to use in the default location context.
# In this context, requests are sent for URIs without file extensions (excluding PHP URIs).
#   If you want to use PHP 7.2 as the default, set the variable to 1.
#   If you want to use PHP 5.6 as the default, set the variable to an empty string.
set $default_php 1;
# choose the upstream section based on the variable set above
location ~ [^/]\.php(/|$) {
  if ($default_php = "") {
    set $php_upstream $upstream_app_php56;
  }

  if ($default_php = "1") {
    set $php_upstream $upstream_app_php72;
  }

  # Tells NGINX to pass the PHP script to FastCGI PHP server with parameters in the specified format.
  # That way the PHP server will better understand the format and handle more types of requests and responses.
  fastcgi_split_path_info ^(.+?\.php)(/.*)$;

  # setting a variable named $path to be the base level path of the web application
  set $path_info $fastcgi_path_info;
  fastcgi_param path_info $path_info;

  # set some FastCGI environment variables that contain the basic runtime information about the current PHP request.
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  fastcgi_param SCRIPT_NAME $fastcgi_script_name;
  fastcgi_param X_SCRIPT_NAME $path_info;
  fastcgi_param X_ORIGINAL_PATH_INFO $fastcgi_path_info;
  fastcgi_param QUERY_STRING $query_string;
  fastcgi_param REQUEST_METHOD $request_method;

  # setting a variable named $tmp_dir to be the root directory for temporary files
  set $tmp_dir /var/tmp;

  # setting the directory for FastCGI temporary files
  fastcgi_param TEMP $tmp_dir;

  # Declare a new variable named $real_ip_header and set its value if the Origin header is present.
  set $real_ip_header $http_origin;
  # If the header is not present, set the value to the $host variable. This value is then used to set the header that will
  # be passed to FastCGI PHP servers.
  if ($real_ip_header = '') {
    set $real_ip_header $host;
  }
  # Set the X-Real-IP header based on the real IP header we just defined, then clear the origin header, since we're not actually
  # interested in it.
  fastcgi_param X-Real-IP $real_ip_header;
  fastcgi_param X-Origin-IP $real_ip_header;
  # fastcgi_param X-Forwarded-Proto $real_scheme;
  fastcgi_param X-HOST $http_host;
  fastcgi_param X-PORT $server_port;
  fastcgi_param ALLOWED_METHODS $request_method;
  fastcgi_param -f; #important
  # Pass the URI as an argument to the PHP FastCGI server.
  fastcgi_param QUERY_STRING $query_string;
  fastcgi_param REQUEST_METHOD $request_method;
  fastcgi_param CONTENT_TYPE $content_type;
  fastcgi_param CONTENT_LENGTH $content_length;

  # Add all of the HTTP headers to FastCGI process as environment variables.
  # The "fastcgi_param" directive passes HTTP headers with the "HTTP_" prefix on to the FastCGI PHP server.
  fastcgi_param HTTP_X_FORWARDED_FOR $http_x_forwarded_for;
  fastcgi_param HTTP_REFERER $http_referer;
  fastcgi_param HTTP_ACCEPT_ENCODING $http_accept_encoding;
  fastcgi_param HTTP_ACCEPT_LANGUAGE $http_accept_language;
  fastcgi_param HTTP_ACCEPT_CHARSET $http_accept_charset;
  fastcgi_param HTTP_ACCEPT $http_accept;
  fastcgi_param HTTP_USER_AGENT $http_user_agent;
  fastcgi_param HTTP_COOKIE $http_cookie;
  fastcgi_param HTTP_X_REQUESTED_WITH $http_x_requested_with;

  # Send the request to the upstream PHP FastCGI process.
  fastcgi_pass $php_upstream;

  # Turn on the "proxy_request_buffering" directive to ensure larger request bodies (including JSON payloads) are handled properly.
  # Defaults to "on" with NGINX, but explicitly setting it to "off" here ensures compatibility and reduces the possibility of
  # request failure.
  proxy_request_buffering off;

  # fastcgi_intercept_errors on;
  fastcgi_buffer_size 32k;
  fastcgi_buffers 8 16k;
  fastcgi_busy_buffers_size 256k;

  # The length in bytes of the FastCGI buffer. Determine the appropriate value for your application or service. Exceeding the limit
  # may result in a "502 Bad Gateway" error.
  fastcgi_buffer_size 64k;

  # The maximum number and size of buffers that can be used for reading client request data. When set to the most common values,
  # these provide the best optimization. Amplifying values beyond certain limits could result in the buffer space inefficiency.
  fastcgi_buffers 4 64k;

  # These settings ensure that the system returns HTTP response codes greater than 399 on errors returned by the PHP FastCGI process.
  # This includes errors like 404 Page Not Found. These settings help enforce better SEO and user experiences because when an error
  # is encountered by the site (due to misconfigurations, deprecated URLs, or outdated sitemaps), the error page will be served
  # with properly-formatted error messaging. This makes it easier for end-users to resolve the error and find where they intended
  # on your site.
  fastcgi_intercept_errors on;
  fastcgi_pass_header Set-Cookie;
  fastcgi_pass_header P3P;
  fastcgi_pass_header Cache-Control;
  fastcgi_pass_header Cache-Pragma;
  fastcgi_pass_header Expires;
}

ssl-params.conf

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:ECDHE-ECDSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 5m;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 10s;

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options SAMEORIGIN always;
add_header X-Content-Type-Options nosniff always;

#add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'" always;
#add_header Referrer-Policy same-origin always;
  1. 在app目录下创建一个Dockerfile:

Dockerfile

# Build your PHP stack based on this light weight PHP-FPM image
FROM php:fpm-alpine

# nginx-alpine is an ultra-light weight Docker image based on Alpine Linux, which is approximately 5MB in size
# compared to the almost 1GB size of the full Ubuntu images.
RUN apk update && apk add --no-cache --virtual .build-deps \ 
    $PHPIZE_DEPS \
    postgresql-dev \
    libzip-dev \
    imagemagick-dev \
    libpng-dev \
    libxml2-dev \
    freetype-dev \
    libjpeg-turbo-dev \
    oniguruma-dev \
    autoconf \
    automake \
    file \
    g++ \
    gcc \
    libc-dev \
    make \
    pkgconf \
    re2c \
    wget \
    gnupg \
    && pecl install redis \
    && pecl install imagick \
    && docker-php-ext-install pdo_mysql bcmath zip soap \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-enable redis imagick \
    && docker-php-ext-install opcache

# Change time zone
RUN ln -snf /usr/share/zoneinfo/UTC /etc/localtime && echo UTC > /etc/timezone

# Install additional PHP modules
RUN apk add --no-cache \
    php7-mysqli \
    php7-common \
    php7-dom \
    php7-mbstring \
    php7-pdo \
    php7-gd \
    php7-json \
    php7-simplexml \
    php7-xdebug \
    php7-curl \
    php7-apcu \
    php7-xml \
    php7-xmlreader \
    php7-cgi \
    php7-pdo_pgsql \
    php7-pdo_mysql \
    php7-zip \
    php7-bcmath

WORKDIR /var/www/html

# Expose the port the application should run on - nginx would communicate with this port via FastCGI
EXPOSE 9000
  1. 部署

    在项目目录下执行以下命令,部署你的docker环境:

    sh
    cd /path/to/project/
    docker-compose up -d --build

以上为本攻略Docker部署nginx+php环境的完整攻略。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Docker部署nginx+php环境的全过程(简单可用!) - Python技术站

(0)
上一篇 2023年5月16日
下一篇 2023年5月16日

相关文章

  • docker 学习之路 将docker容器变为镜像并上传

    环境 ubunt 16.4         去hub.docker.com上注册一个账号,并在账号中注册一个公有public或者私有仓库private 步骤如下      如上图 点击该处进入创建docker库页面    除了名字之外,默认为公有仓库  创建完成如下图       登录docker账号仓库 docker login // 输入账号和密码   …

    Docker 2023年4月12日
    00
  • windows 下 安装 Docker 并在Docker 中安装GitLab 并进行相关的设置

      安装Docker Desktop 1,下载这个Docker Desktop Installerwin  软件 微软官网 目前只支持 win10较新的版本   2,安装并设置 软件会自动提示你的电脑是否满足。什么虚拟化的 (我就假设你懂的,不懂的你百度一下,再回来看)   安装好了会提示你重启电脑       设置镜像 “https://registry.…

    Docker 2023年4月11日
    00
  • Docker基础命令详解

    Docker基础命令详解 Docker是一种容器化技术,用于将应用程序打包成可移植的容器,以便在不同环境中轻松部署和运行。这里整理了一些Docker的基础命令,方便大家快速入手。 安装Docker 首先需要安装Docker,具体版本和安装过程请参考官网。安装完成后,可以通过docker –version来验证是否安装成功。 Docker镜像 docker …

    Docker 2023年5月16日
    00
  • 远程云服务器上docker安装redis的过程

    首先明确一点,云服务环境你已经安装好了docker(可参考菜鸟教程:https://www.runoob.com/docker/centos-docker-install.html) 1.安装好以后,输入版本查看命令: docker -v 2.进入docker hub官网查看你所需要的redis的版本信息 docker hub     3.远程连接服务的工具…

    Docker 2023年4月10日
    00
  • 虚拟机安装docker

    最近在win10 电脑上 安装docker 发现系统不支持,又安装一层虚拟机,再安装docker orace vm : 配置网卡有问题,虚拟机访问不了主机,  主机ssh虚拟机一直会偶发断掉,换了vm可以   一 .环境配置: centos  ip  和 域名服务器设置:  vi   /etc/sysconfig/network-scripts/ifcf..…

    Docker 2023年4月12日
    00
  • docker官方镜像下载及使用Dockerfile创建镜像的方法

    下面我来详细讲解如何使用Docker官方镜像下载以及使用Dockerfile创建镜像的方法。 Docker官方镜像下载 Docker官方镜像是由Docker官方团队和社区维护的镜像,它们经过了充分的测试和验证,可以用于生产环境。我们可以在Docker Hub上查找和下载这些镜像。 查找Docker官方镜像 在Docker Hub上查找Docker官方镜像非常…

    Docker 2023年5月16日
    00
  • Docker Compose与Docker镜像仓库详解

    Docker Compose与Docker镜像仓库详解 Docker Compose是一个用于定义和运行多个Docker容器应用程序的工具,它可以通过一个单独的文件来定义整个应用程序的多个容器,包括容器之间的关系、网络连接等。 Docker镜像仓库是用于存储和管理Docker镜像的中央存储库,它被用于存储各种Docker镜像,供其它用户和项目进行使用。 Do…

    Docker 2023年5月16日
    00
  • docker容器从入门到痴迷(推荐)

    Docker容器从入门到痴迷 Docker是目前最流行的容器化技术之一,可以帮助开发者更轻松地构建、交付和运行应用程序。本文将为读者介绍Docker容器的基本概念、使用方法以及注意事项等内容,旨在让读者快速了解并上手Docker容器。 Docker容器的基本概念 Docker容器是Docker的一个主要组件,它是一个轻量级、可移植的容器,包含了应用程序及其所…

    Docker 2023年5月16日
    00
合作推广
合作推广
分享本页
返回顶部