search
HomeBackend DevelopmentPHP TutorialHow Docker arranges PHP development environment, docker arranges PHP development_PHP tutorial

Docker 如何布置PHP开发环境,docker布置php开发

环境部署一直是一个很大的问题,无论是开发环境还是生产环境,但是 Docker 将开发环境和生产环境以轻量级方式打包,提供了一致的环境。极大的提升了开发部署一致性。当然,实际情况并没有这么简单,因为生产环境和开发环境的配置是完全不同的,比如日志等的问题都需要单独配置,但是至少比以前更加简单方便了,这里以 PHP 开发作为例子讲解 Docker 如何布置开发环境。

一般来说,一个 PHP 项目会需要以下工具:

  1. Web 服务器: Nginx/Tengine
  2. Web 程序: PHP-FPM
  3. 数据库: MySQL/PostgreSQL
  4. 缓存服务: Redis/Memcache

这是最简单的架构方式,在 Docker 发展早期,Docker 被大量的滥用,比如,一个镜像内启动多服务,日志收集依旧是按照 Syslog 或者别的老方式,镜像容量非常庞大,基础镜像就能达到 80M,这和 Docker 当初提出的思想完全南辕北辙了,而 Alpine Linux 发行版作为一个轻量级 Linux 环境,就非常适合作为 Docker 基础镜像,Docker 官方也推荐使用 Alpine 而不是 Debian 作为基础镜像,未来大量的现有官方镜像也将会迁移到 Alpine 上。本文所有镜像都将以 Alpine 作为基础镜像。

Nginx/Tengine

这部分笔者已经在另一篇文章 Docker 容器的 Nginx 实践中讲解了 Tengine 的 Docker 实践,并且给出了 Dockerfile,由于比较偏好 Tengine,而且官方已经给出了 Nginx 的 alpine 镜像,所以这里就用 Tengine。笔者已经将镜像上传到官方 DockerHub,可以通过

docker pull chasontang/tengine:2.1.2_f

获取镜像,具体请看 Dockerfile。

PHP-FPM

Docker 官方已经提供了 PHP 的 7.0.7-fpm-alpine 镜像,Dockerfile 如下:

FROM alpine:3.4

# persistent / runtime deps
ENV PHPIZE_DEPS \
    autoconf \
    file \
    g++ \
    gcc \
    libc-dev \
    make \
    pkgconf \
    re2c
RUN apk add --no-cache --virtual .persistent-deps \
    ca-certificates \
    curl

# ensure www-data user exists
RUN set -x \
  && addgroup -g 82 -S www-data \
  && adduser -u 82 -D -S -G www-data www-data
# 82 is the standard uid/gid for "www-data" in Alpine
# http://git.alpinelinux.org/cgit/aports/tree/main/apache2/apache2.pre-install?h=v3.3.2
# http://git.alpinelinux.org/cgit/aports/tree/main/lighttpd/lighttpd.pre-install?h=v3.3.2
# http://git.alpinelinux.org/cgit/aports/tree/main/nginx-initscripts/nginx-initscripts.pre-install?h=v3.3.2

ENV PHP_INI_DIR /usr/local/etc/php
RUN mkdir -p $PHP_INI_DIR/conf.d

##<autogenerated>##
ENV PHP_EXTRA_CONFIGURE_ARGS --enable-fpm --with-fpm-user=www-data --with-fpm-group=www-data
##</autogenerated>##

ENV GPG_KEYS 1A4E8B7277C42E53DBA9C7B9BCAA30EA9C0D5763

ENV PHP_VERSION 7.0.7
ENV PHP_FILENAME php-7.0.7.tar.xz
ENV PHP_SHA256 9cc64a7459242c79c10e79d74feaf5bae3541f604966ceb600c3d2e8f5fe4794

RUN set -xe \
  && apk add --no-cache --virtual .build-deps \
    $PHPIZE_DEPS \
    curl-dev \
    gnupg \
    libedit-dev \
    libxml2-dev \
    openssl-dev \
    sqlite-dev \
  && curl -fSL "http://php.net/get/$PHP_FILENAME/from/this/mirror" -o "$PHP_FILENAME" \
  && echo "$PHP_SHA256 *$PHP_FILENAME" | sha256sum -c - \
  && curl -fSL "http://php.net/get/$PHP_FILENAME.asc/from/this/mirror" -o "$PHP_FILENAME.asc" \
  && export GNUPGHOME="$(mktemp -d)" \
  && for key in $GPG_KEYS; do \
    gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \
  done \
  && gpg --batch --verify "$PHP_FILENAME.asc" "$PHP_FILENAME" \
  && rm -r "$GNUPGHOME" "$PHP_FILENAME.asc" \
  && mkdir -p /usr/src \
  && tar -Jxf "$PHP_FILENAME" -C /usr/src \
  && mv "/usr/src/php-$PHP_VERSION" /usr/src/php \
  && rm "$PHP_FILENAME" \
  && cd /usr/src/php \
  && ./configure \
    --with-config-file-path="$PHP_INI_DIR" \
    --with-config-file-scan-dir="$PHP_INI_DIR/conf.d" \
    $PHP_EXTRA_CONFIGURE_ARGS \
    --disable-cgi \
# --enable-mysqlnd is included here because it's harder to compile after the fact than extensions are (since it's a plugin for several extensions, not an extension in itself)
    --enable-mysqlnd \
# --enable-mbstring is included here because otherwise there's no way to get pecl to use it properly (see https://github.com/docker-library/php/issues/195)
    --enable-mbstring \
    --with-curl \
    --with-libedit \
    --with-openssl \
    --with-zlib \
  && make -j"$(getconf _NPROCESSORS_ONLN)" \
  && make install \
  && { find /usr/local/bin /usr/local/sbin -type f -perm +0111 -exec strip --strip-all '{}' + || true; } \
  && make clean \
  && runDeps="$( \
    scanelf --needed --nobanner --recursive /usr/local \
      | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \
      | sort -u \
      | xargs -r apk info --installed \
      | sort -u \
  )" \
  && apk add --no-cache --virtual .php-rundeps $runDeps \
  && apk del .build-deps

COPY docker-php-ext-* /usr/local/bin/

##<autogenerated>##
WORKDIR /var/www/html

RUN set -ex \
  && cd /usr/local/etc \
  && if [ -d php-fpm.d ]; then \
    # for some reason, upstream's php-fpm.conf.default has "include=NONE/etc/php-fpm.d/*.conf"
    sed 's!=NONE/!=!g' php-fpm.conf.default | tee php-fpm.conf > /dev/null; \
    cp php-fpm.d/www.conf.default php-fpm.d/www.conf; \
  else \
    # PHP 5.x don't use "include=" by default, so we'll create our own simple config that mimics PHP 7+ for consistency
    mkdir php-fpm.d; \
    cp php-fpm.conf.default php-fpm.d/www.conf; \
    { \
      echo '[global]'; \
      echo 'include=etc/php-fpm.d/*.conf'; \
    } | tee php-fpm.conf; \
  fi \
  && { \
    echo '[global]'; \
    echo 'error_log = /proc/self/fd/2'; \
    echo; \
    echo '[www]'; \
    echo '; if we send this to /proc/self/fd/1, it never appears'; \
    echo 'access.log = /proc/self/fd/2'; \
    echo; \
    echo 'clear_env = no'; \
    echo; \
    echo '; Ensure worker stdout and stderr are sent to the main error log.'; \
    echo 'catch_workers_output = yes'; \
  } | tee php-fpm.d/docker.conf \
  && { \
    echo '[global]'; \
    echo 'daemonize = no'; \
    echo; \
    echo '[www]'; \
    echo 'listen = [::]:9000'; \
  } | tee php-fpm.d/zz-docker.conf

EXPOSE 9000
CMD ["php-fpm"]
##</autogenerated>##

首先,镜像继承自 alpine:3.4 镜像,使用 apk 命令安装 php 最小依赖,同时添加 www-data 作为 php-fpm 的运行用户,将 php 的配置文件指定到 /usr/local/etc/php,然后就是下载 php-src,编译安装,这里可以参考笔者之前写的 php 编译安装文章。参数都中规中矩。安装目录被指定到 /usr/local,然后使用 scanelf 获得所依赖的运行库列表,并且将其他安装包删除。将 docker-php-ext-configure、docker-php-ext-enable、docker-php-ext-install 复制到容器中,这三个文件用于后续安装扩展。然后将 php-fpm.conf 复制到配置目录,将 error_log 和 access_log 指定到终端标准输出,daemonize = no 表示不以服务进程运行。EXPOSE 9000 端口用于和其他容器通信,然后就是 CMD ["php-fpm"] 运行 php-fpm。而且工作目录被指定到 /var/www/html。

docker-compose

已经搞定了基础镜像,我们就可以使用基础镜像来配置容器,但是通过手工 docker 命令启动容器会非常麻烦。但是万幸的是官方已经提供了 docker-compose 命令来编排容器,只需要写一个 docker-compose.yaml 文件就行,具体可以参考官方文档。

version: '2'
services:
 php-fpm:
  image: php:7.0.7-fpm-alpine
  volumes:
   - "./src:/var/www/html"
  restart: always

 tengine:
  depends_on:
   - php-fpm
  links:
   - php-fpm
  image: chasontang/tengine:2.1.2_f
  volumes:
   - "./nginx.vh.default.conf:/etc/nginx/conf.d/default.conf"
  ports:
   - "80:80"
  restart: always

非常容易理解,这里定义了两个服务,php-fpm 依赖 php:7.0.7-fpm-alpine 镜像,并且将 src 文件夹映射为 /var/www/html 文件夹,tengine 服务依赖 php-fpm 服务,并且 link php-fpm 服务,这样就能通过网络与 php-fpm 容器通信,tengine 服务基于 chasontang/tengine:2.1.2_f 镜像,并将 nginx.vh.default.conf 文件映射为 /etc/nginx/conf.d/default.conf 文件。然后来看 nginx.vh.default.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;
  #}

  location ~ [^/]\.php(/|$) {
    fastcgi_split_path_info ^(.+&#63;\.php)(/.*)$;
    fastcgi_pass php-fpm:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    include fastcgi_params;
  }

  # deny access to .htaccess files, if Apache's document root
  # concurs with nginx's one
  #
  #location ~ /\.ht {
  #  deny all;
  #}
}

tengine 镜像实际上使用两个配置文件,一个是 /etc/nginx/nginx.conf,还有就是 /etc/nginx/conf.d/ 目录下的所有文件,因为 /etc/nginx/nginx.conf 中使用 include /etc/nginx/conf.d/*.conf; 包含了这个目录,也就是说,可以不需要去管 nginx 其他配置,只需要用自己的 nginx 虚拟主机配置替代默认的虚拟主机配置,或者说增加虚拟主机配置就行了。

从上面可以看到,default.conf 文件定义了一个 location 匹配包含 .php 的 URL,然后将其分割出 PATH_INFO 参数,将这些变量传递给 php-fpm:9000 的 php-fpm 服务。

这里需要注意的是,由于 Nginx 和 PHP-FPM 不在同一台主机上,所以 Nginx 只做静态文件处理和路由转发,实际的 PHP 文件执行时在 PHP-FPM 容器中发生的。所以 SCRIPT_FILENAME 变量必须要使用 PHP-FPM 容器中的目录,所以这里使用硬编码指定。当然,也可以让两个容器共享同一个数据卷,但是笔者认为,这只是为了方便容器编排,其他完全没有好处。

It’s easy! Now we can quickly start and update the environment, but there are still many areas that need improvement.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1136621.htmlTechArticleDocker How to arrange the PHP development environment, docker layout PHP development environment deployment has always been a big problem, whether it is development The environment is still the production environment, but Docker combines the development environment and production...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools