Table of Contents
搭建基于Docker的PHP开发环境的详细教程,搭建dockerphp开发
Home Backend Development PHP Tutorial Detailed tutorial on setting up a PHP development environment based on Docker, setting up dockerphp development_PHP tutorial

Detailed tutorial on setting up a PHP development environment based on Docker, setting up dockerphp development_PHP tutorial

Jul 13, 2016 am 09:47 AM
docker hadoop php

搭建基于Docker的PHP开发环境的详细教程,搭建dockerphp开发

现在很多开发者都使用Vagrant来管理他们的虚拟机开发环境,Vagrant确实很酷, 不过也有不少缺点(最主要的是它占用太多的资源)。在容器技术、Docker和更多类Docker技术出现后,解决这个问题就变得简单了。
免责声明

由于boot2docker的工作方式,本文所述的方法在你的环境中可能无法正常运行。如果需要在非Linux环境下共享文件夹到Docker容器,还需要注意更多额外的细节。后续我会写篇文章专门来介绍实际遇到的问题。
怎样才算是好的开发环境

首先,我们得知道什么才是好的开发环境, 对于我而言,一个好的开发环境需要具备以下几个特点:

  •     可随意使用。我必须可以随意删除和创建新的环境。
  •     快速启动。我想要用它工作时候,它立马就能用。
  •     易于更新。在我们行业中,事物发展变化非常快,必须能让我很容易将我的开发环境更新到新的软件版本。

而Docker都支持以上这些特点,甚至更多。你几乎可以即时销毁和重建容器,而更新环境只需要重建你当前使用的镜像即可。
什么是PHP开发环境

目前Web应用错综复杂,PHP开发环境需要很多的东西,为了保证环境的简单性,需要做各种各样的限制。
我们这次使用Nginx、PHP5-FPM、MySQL来运行Synmfony项目。

Pet 与 Cattle

另一个我们要讨论的重点是:我们要把开发环境部署在多容器还是单容器中。 两种方式各有优点:

  •     单容器易于分发、维护。因为它们是独立的,所有的东西都运行在同一个容器中,这点就像是一个虚拟机。但这也意味着,当你要升级其中的某样东西(比如PHP新版本)的时候, 需要重新构建整个容器。
  •     多容器可以在添加组件时提供更好的模块化。因为每个容器包含了堆栈的一部分:Web、PHP、MySQL等,这样可以单独扩展每个服务或者添加服务,并且不需要重建所有的东西。

因为我比较懒,加上我需要在我的笔记本上放点别的内容,所以,这里我们只介绍单个容器的方法。
初始化工程

首先要做的是初始化一个新的Symfony工程. 推荐的方法是用composer的create-project命令。本来可以在工作站上安装composer,但是那样太简单了。这次我们通过Docker来使用它。
我之前发过一篇关于Docker命令的文章:make docker commands(好吧,我说谎了,我本来把它写在这篇文章中了,然后觉得把它独立出来会比较好)。

不管怎么样,你可以读一下。接下来如果还没有composer命令的话,你可以创建一个属于自己的composer 别名。

$ alias composer="docker run -i -t -v \$PWD:/srv ubermuda/composer"

Copy after login

现在你可以初始化Symfony工程了:

$ composer create-project symfony/framwork-standard-edition SomeProject

Copy after login

帅呆了!下面来点实在的工作。

容器

构建一个运行标准Symfony项目且自给自足的容器相当容易,只需要安装好常用的Nginx、PHP5-FPM和MySQL-Server即可,然后把预先准备好的Nginx的虚拟主机配置文件扔进去,再复制一些配置文件进去就完事了。

本容器的源代码在GitHub上的 ubermuda/docker-symfony仓库中可以找到。 Dockerfile 是Docker构建镜像要用到的配置文件,我们来看一下:

FROM debian:wheezy

ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update -y
RUN apt-get install -y nginx php5-fpm php5-mysqlnd php5-cli mysql-server supervisor

RUN sed -e 's/;daemonize = yes/daemonize = no/' -i /etc/php5/fpm/php-fpm.conf
RUN sed -e 's/;listen\.owner/listen.owner/' -i /etc/php5/fpm/pool.d/www.conf
RUN sed -e 's/;listen\.group/listen.group/' -i /etc/php5/fpm/pool.d/www.conf
RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf

ADD vhost.conf /etc/nginx/sites-available/default
ADD supervisor.conf /etc/supervisor/conf.d/supervisor.conf
ADD init.sh /init.sh

EXPOSE 80 3306

VOLUME ["/srv"]
WORKDIR /srv

CMD ["/usr/bin/supervisord"]

Copy after login

我们通过扩展 debian:wheezy 这个基础镜像开始,然后通过一系列的sed命令来配置Nginx和PHP5-FPM。

复制代码 代码如下: RUN sed -e 's/;daemonize = yes/daemonize = no/' -i /etc/php5/fpm/php-fpm.conf
RUN sed -e 's/;listen\.owner/listen.owner/' -i /etc/php5/fpm/pool.d/www.conf
RUN sed -e 's/;listen\.group/listen.group/' -i /etc/php5/fpm/pool.d/www.conf
RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf

这里我们要做两件事。 首先配置PHP5-FPM和Nginx让他们在前台运行以便supervisord可以追踪到他们。
然后,配置PHP5-FPM以指定的用户运行Web-Server,并处理好文件权限。

接下来需要安装一组配置文件,首先是Nginx的虚拟主机配置文件vhost.conf:

server {
  listen 80;

  server_name _;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;

  root /srv/web;
  index app_dev.php;

  location / {
    try_files $uri $uri/ /app_dev.php?$query_string;
  }

  location ~ [^/]\.php(/|$) {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
  }
}

Copy after login

因为我们不需要域名,所以把server_name设成了_(有点像perl的$_占位符变量), 并配置根目录(document root)为/svr/web, 我们会把应用程序部署在/srv下,剩下的就是标准的Mginx + PHP5-FPM配置.

因为一个容器每次只能运行一个程序, 我们需要supervisord(或者任何别的进程管理器,不过我比较中意supervisord)。幸运的是, 这个进程管理器会产生我们需要的所有进程!下面是一小段supervisord的配置:

[supervisord]
nodaemon=true

[program:nginx]
command=/usr/sbin/nginx

[program:php5-fpm]
command=/usr/sbin/php5-fpm

[program:mysql]
command=/usr/bin/mysqld_safe

[program:init]
command=/init.sh
autorestart=false
redirect_stderr=true
redirect_stdout=/srv/app/logs/init.log

Copy after login

这里我们需要做的是定义所有的服务, 加上一个特殊的program:init进程,它不是一个实际的服务,而是一个独创的运行启动脚本的方式。

这个启动脚本的问题在于,它通常需要先启动某些服务。比如,你可能要初始化一些数据库表,但前提是你得先把MySQL跑起来,一个可能的解决办法 是,在启动脚本中启动MySQL,然后初始化表,然后为了防止影响到supervisord的进程管理,需要停掉MySQL,最后再启动 supervisord。

这样的脚本看起来类似下面这样:

/etc/init.d/mysql start
app/console doctrine:schema:update --force
/etc/init.d/mysql stop

exec /usr/bin/supervisord

Copy after login

看起来丑爆了有木有,咱换种方式,让supervisor来运行它并且永不重启。
实际的init.sh脚本如下:

#!/bin/bash

RET=1

while [[ RET -ne 0 ]]; do
  sleep 1;
  mysql -e 'exit' > /dev/null 2>&1; RET=$?
done

DB_NAME=${DB_NAME:-symfony}

mysqladmin -u root create $DB_NAME

if [ -n "$INIT" ]; then
  /srv/$INIT
fi

Copy after login

脚本先等待MySQL启动,然后根据环境变量DB_NAME创建DB,默认为symfony, 然后在INIT环境变量中查找要运行的脚本,并尝试运行它。本文的结尾有说明如何使用这些环境变量。
构建并运行镜像

万事俱备只欠东风。我们还要构建Symfony Docker镜像, 使用docker build命令:

$ cd docker-symfony
$ docker build -t symfony .

Copy after login

现在,可以使用它来运行你的Symfony工程了:

$ cd SomeProject
$ docker run -i -t -P -v $PWD:/srv symfony

Copy after login

我们来看看这一连串的选项分别是干嘛的:

  • -i 启动交互(interactive)模式, 也就是说,STDIO(标准输入输出)连接到了你当前的终端上。当你要接收日志或者给进程发送信号时,它很有用。
  • -t 为容器创建一个虚拟TTY, 它跟-i是好基友,通常一起使用。
  • -P 告诉Docker守护进程发布所有指定的端口, 本例中为80端口。
  • -v $PWD:/srv 把当前目录挂载到容器的/srv目录。挂载一个目录使得目录内容对目标挂载点可用。

现在你还记得之前提到的DB_NAME和INIT环境变量了吧,干嘛用的呢:用于自定义你的环境。 基本上你可以通过 docker run的-e选项在容器中设置环境变量,启动脚本会拿到环境变量,因此,如果你的DB名为some_project_dev, 你就可以这么运行容器:

$ docker run -i -t -P -v $PWD:/srv -e DB_NAME=some_project_dev symfony

Copy after login

INIT 环境变量就更强大了,它允许你启动时运行指定的脚本。比如, 你有一个bin/setup脚本运行composer install命令并且设置数据库schema:

#!/bin/bash
composer install
app/console doctrine:schema:update --force

Copy after login

用-e来运行它:

$ docker run -i -t -P \
  -v $PWD:/srv \
  -e DB_NAME=some_project_dev \
  -e INIT=bin/setup

Copy after login

注意,-e选项可以在docer run中多次使用,看起来相当酷。另外,你的启动脚本需要可执行权限(chmod +x)。

现在我们通过curl发送请求到容器,来检查一下是否所有的东西都像预期一样工作。首先,我们需要取到Docker映射到容器的80端口的公共端口,用docker port命令:

$ docker port $(docker ps -aql 1) 80
0.0.0.0:49153

Copy after login

docker ps -aql 1 是个好用的命令,可以方便的检索到最后一个容器的id, 在我们的例子中,Docker 把容器的80端口映射到了49153端口。我们 curl 一下看看。

$ curl http://localhost:49153
Copy after login
You are not allowed to access this file. Check app_dev.php for more information.

Copy after login

当我们不从localhost(译者注:容器的localhost)访问dev controller时,得到了Symfony的默认错误消息,这再正常不过了, 因为我们不是从容器内部发送 curl 请求的, 所以,可以安全的从前端控制器web/app_dev.php中移除这些行。

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
  || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
  || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
  header('HTTP/1.0 403 Forbidden');
  exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

Copy after login

这些行阻止了任何从localhost以外的地方访问dev controller。
现在再curl的时候就可以正常工作了,或者用浏览器访问 http://localhost:49153/:

201571105429165.png (1554×988)

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1024926.htmlTechArticle搭建基于Docker的PHP开发环境的详细教程,搭建dockerphp开发 现在很多开发者都使用Vagrant来管理他们的虚拟机开发环境,Vagrant确实很酷, 不过...
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to update the image of docker How to update the image of docker Apr 15, 2025 pm 12:03 PM

The steps to update a Docker image are as follows: Pull the latest image tag New image Delete the old image for a specific tag (optional) Restart the container (if needed)

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 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.

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

How to copy files in docker to outside How to copy files in docker to outside Apr 15, 2025 pm 12:12 PM

Methods for copying files to external hosts in Docker: Use the docker cp command: Execute docker cp [Options] <Container Path> <Host Path>. Using data volumes: Create a directory on the host, and use the -v parameter to mount the directory into the container when creating the container to achieve bidirectional file synchronization.

How to exit the container by docker How to exit the container by docker Apr 15, 2025 pm 12:15 PM

Four ways to exit Docker container: Use Ctrl D in the container terminal Enter exit command in the container terminal Use docker stop <container_name> Command Use docker kill <container_name> command in the host terminal (force exit)

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 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.

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

See all articles