将 PHP 应用程序容器化
先决条件
- 您已安装最新版本的 Docker Desktop。
- 你有一个 git 客户端。本节中的示例使用基于命令行的 git 客户端,但您可以使用任何客户端。
概述
本部分将引导您完成容器化和运行 PHP 应用程序。
获取示例应用程序
在本指南中,您将使用预构建的 PHP 应用程序。该应用程序使用 Composer 进行库依赖管理。您将通过 Apache Web 服务器为应用程序提供服务。
打开终端,将目录更改为您想要工作的目录,然后运行以下命令来克隆存储库。
$ git clone https://github.com/docker/docker-php-sample
该示例应用程序是一个基本的 hello world 应用程序和一个递增数据库中计数器的应用程序。此外,该应用程序使用 PHPUnit 进行测试。
初始化 Docker 资产
现在您已经有了一个应用程序,您可以用来docker init
创建必要的 Docker 资产来容器化您的应用程序。在目录内
docker-php-sample
,docker init
在终端中运行命令。
docker init
提供了一些默认配置,但您需要回答一些有关您的应用程序的问题。例如,此应用程序使用 PHP 版本 8.2。请参阅以下docker init
示例并对提示使用相同的答案。
$ docker init
Welcome to the Docker Init CLI!
This utility will walk you through creating the following files with sensible defaults for your project:
- .dockerignore
- Dockerfile
- compose.yaml
- README.Docker.md
Let's get started!
? What application platform does your project use? PHP with Apache
? What version of PHP do you want to use? 8.2
? What's the relative directory (with a leading .) for your app? ./src
? What local port do you want to use to access your server? 9000
您的目录中现在应该有以下内容docker-php-sample
。
├── docker-php-sample/
│ ├── .git/
│ ├── src/
│ ├── tests/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── compose.yaml
│ ├── composer.json
│ ├── composer.lock
│ ├── Dockerfile
│ ├── README.Docker.md
│ └── README.md
要了解有关添加的文件的更多信息docker init
,请参阅以下内容:
运行应用程序
在目录内docker-php-sample
,在终端中运行以下命令。
$ docker compose up --build
打开浏览器并在http://localhost:9000/hello.php查看应用程序 。您应该看到一个简单的 hello world 应用程序。
在终端中,按ctrl
+c
停止应用程序。
在后台运行应用程序
您可以通过添加选项来运行与终端分离的应用程序-d
。在目录内docker-php-sample
,在终端中运行以下命令。
$ docker compose up --build -d
打开浏览器并在http://localhost:9000/hello.php查看应用程序 。您应该看到一个简单的 hello world 应用程序。
在终端中,运行以下命令来停止应用程序。
$ docker compose down
有关 Compose 命令的更多信息,请参阅 Compose CLI 参考。
概括
在本部分中,您了解了如何使用 Docker 容器化并运行简单的 PHP 应用程序。
相关信息:
下一步
在下一节中,您将了解如何使用 Docker 容器开发应用程序。