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日

相关文章

  • 仓库管理、dockerfile

    Docker仓库管理 ​ 仓库(Repository)是集中存放镜像的地方。 Docker Dockerfile 什么是Dockerfile? ​ Dockerfile 是一个用来构建镜像的文本文件,文本内容包含了一条条构建镜像所需的指令和说明。 使用Dockerfile定制镜像 1、下面以定制一个 nginx 镜像(构建好的镜像内会有一个 /usr/sha…

    Docker 2023年4月8日
    00
  • 简单介绍几款Docker的检测工具

    当使用 Docker 时,我们需要了解 Docker 的安全性和安全操作。为此,许多 Docker 安全检测工具应运而生。下面,我将对几款 Docker 的检测工具进行简要介绍。 ClamAV ClamAV 是一款开源的反病毒软件。它不仅可以用于检查文件和邮件中的病毒,也可以用于 Docker 中的容器安全检测。ClamAV 可以检测 Docker 镜像中嵌…

    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
  • docker安装jumpserver

    注意MySQL的密码设置要有复杂度,否则jumpserver用不了 #先准备一台服务器安装MySQL和redis(注意官网版本要求) root@ubuntu:~# docker pull mysql:5.6.45 root@ubuntu:~# docker pull redis #:启动MySQL和redis root@ubuntu:~# docker ru…

    Docker 2023年4月16日
    00
  • Docker-Vulhub快速漏洞环境搭建

    Docker-Vulhub快速漏洞环境搭建 推荐一个大哥写的文章,挺容易懂的:https://www.jianshu.com/p/5e69341157d9 docker介绍 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的镜像中,然后发布到任何流行的 Linux或Windows 机器上,也可以实现虚拟化。容器是完全使…

    Docker 2023年4月12日
    00
  • 详解CentOS 7 下安装 Docker 及操作命令的方法

    下面是对“详解CentOS 7 下安装 Docker 及操作命令的方法”的完整攻略的详细讲解。 安装 Docker 步骤一:卸载旧版本的 Docker 如果你的系统上已经安装了旧版本的 Docker,请先执行以下命令卸载旧版的 Docker : $ sudo yum remove docker \ docker-common \ docker-selinux…

    Docker 2023年5月16日
    00
  • 影片自由,丝滑流畅,Docker容器基于WebDav协议通过Alist挂载(百度网盘/阿里云盘)Python3.10接入

    使用过NAS(Network Attached Storage)的朋友都知道,它可以通过局域网将本地硬盘转换为局域网内的“网盘”,简单理解就是搭建自己的“私有云”,但是硬件和网络成本都太高了,有点可望而不可及的意思。Alist开源库则可以满足我们,它能将公共网盘反过来变成一种联网的本地硬盘,使用Web页面来统一挂载和管理,网盘类型包含但不限于:百度网盘、阿里…

    2023年4月9日
    00
  • 如何精简 Prometheus 的指标和存储占用

    前言 随着 Prometheus 监控的组件、数量、指标越来越多,Prometheus 对计算性能的要求会越来越高,存储占用也会越来越多。 在这种情况下,要优化 Prometheus 性能, 优化存储占用. 第一时间想到的可能是各种 Prometheus 的兼容存储方案, 如 Thanos 或 VM、Mimir 等。但是实际上虽然集中存储、长期存储、存储降采…

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