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新手初探之常用命令实践记录”的完整攻略: Docker新手初探之常用命令实践记录 介绍 Docker是一种轻量级的容器化技术,它可以在不同的计算机环境中实现应用程序的快速开发、测试和部署。在这篇文章中,我们将介绍Docker的一些常用命令,并提供两个实例说明。 Docker常用命令 以下是Docker的一些常用命令: 镜像相关操作…

    Docker 2023年5月16日
    00
  • Jenkins Docker部署

    jenkins/jenkins Docker Hub 上的官方 Jenkins 镜像 How to run and upgrade Jenkins using the official Docker image 部署 过程 创建jenkins目录 mkdir -p /mnt/softwares/jenkins chmod a+w /mnt/softwares…

    Docker 2023年4月11日
    00
  • Docker到底是什么?Docker为什么它这么火!

    下面我会详细讲解Docker的相关内容,包括Docker的定义、特点、优势和示例。请耐心阅读。 Docker的定义 Docker是一种应用容器引擎,可以让你打包你的应用程序和依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 或 Windows 机器上,而不用担心环境不一致的问题。它可以大大简化应用的部署、管理和运行,并提供高效、可靠和可重复的应用…

    Docker 2023年5月16日
    00
  • Docker中 container 和 image 的命名

    在Docker中,container和image的命名都是十分重要的。本文将从container和image的概念入手,详细讲解Docker中container和image的命名规则,以及如何为container和image命名,同时提供两个示例说明。 Container和Image的概念 在Docker中,container和image是两个重要的概念,它…

    Docker 2023年5月15日
    00
  • WIN10下安装Docker的教程

    下面是WIN10下安装Docker的完整攻略: 步骤一:下载Docker 首先,在Windows官网上下载Docker Desktop for Windows(https://docs.docker.com/docker-for-windows/install/),根据版本选择合适的下载方式进行下载。 步骤二:安装Docker 下载完成后,双击.exe文件开…

    Docker 2023年5月16日
    00
  • docker上传镜像到harbor镜像仓库

    1. 登陆docker服务器绑定hosts [root@docker ~]# vim /etc/hosts [root@docker ~]# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost loc…

    Docker 2023年4月16日
    00
  • 关闭或启动linux防火墙后,docker启动容器报错问题解决方式  关闭或启动linux防火墙后,docker启动容器报错问题解决方式

    解决办法:重建docker0网络恢复 1、按照进程名杀死docker进程 pkill docker 2、清空防火墙规则-清空nat表的所有链 iptables -t nat -F 3、查看定义规则的详细信息 iptables -L -n -v 4、关闭docker0接口 ifconfig docker0 down 5、删除docker0接口 brctl de…

    Docker 2023年4月13日
    00
  • HTTPS基础原理和配置-3

    书接上文:HTTPS 基础原理和配置 – 2,接下来介绍: 配置 NGINX 后端 HTTPS 检查配置 配置 HSTS OCSP Stapling 重要部分来了。如何使用这些选项并配置NGINX? 一、NGINX 的 HTTPS 配置 这里有一些基本的原语(或叫做指令),你可以使用:ssl_certificate、ssl_certificate_key、s…

    2023年4月9日
    00
合作推广
合作推广
分享本页
返回顶部