add php language-specific guide (#18794)

* add php language guide
---------

Signed-off-by: Craig Osterhout <craig.osterhout@docker.com>
Co-authored-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
This commit is contained in:
Craig Osterhout 2023-12-07 12:42:16 -08:00 committed by GitHub
parent 031efe9158
commit e9d930069d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 1004 additions and 1 deletions

View File

@ -12,4 +12,4 @@ services:
path: .
target: /src
ignore:
- node_modules/
- node_modules/

View File

@ -66,5 +66,6 @@ Continue to the language-specific guides to learn how you can use Docker to cont
- [Go](../../language/golang/_index.md)
- [Java](../../language/java/_index.md)
- [Node.js](../../language/nodejs/_index.md)
- [PHP](../../language/php/_index.md)
- [Python](../../language/python/_index.md)
- [Rust](../../language/rust/_index.md)

View File

@ -42,4 +42,7 @@ Learn how to containerize your applications and start developing using Docker. C
<div class="flex items-center flex-1 shadow p-4">
<a href="/language/rust/"><img class="m-auto rounded" src="/language/images/rust-logo.webp" alt="Develop with Rust"></a>
</div>
<div class="flex items-center flex-1 shadow p-4">
<a href="/language/php/"><img class="m-auto rounded" src="/language/images/php-logo.webp" alt="Develop with PHP"></a>
</div>
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,21 @@
---
description: Containerize and develop PHP apps using Docker
keywords: getting started, php, composer
title: PHP language-specific guide
toc_min: 1
toc_max: 2
---
The PHP language-specific guide teaches you how to create a containerized PHP application using Docker. In this guide, you'll learn how to:
* Containerize and run a PHP application
* Set up a local environment to develop a PHP application using containers
* Run tests for a PHP application within containers
* Configure a CI/CD pipeline for a containerized PHP application using GitHub Actions
* Deploy your containerized application locally to Kubernetes to test and debug your deployment
After completing the PHP language-specific guide, you should be able to containerize your own PHP application based on the examples and instructions provided in this guide.
Start by containerizing an existing PHP application.
{{< button text="Containerize a PHP app" url="containerize.md" >}}

View File

@ -0,0 +1,147 @@
---
title: Configure CI/CD for your PHP application
keywords: php, CI/CD
description: Learn how to Configure CI/CD for your PHP application
---
## Prerequisites
Complete all the previous sections of this guide, starting with [Containerize a PHP application](containerize.md). You must have a [GitHub](https://github.com/signup) account and a [Docker](https://hub.docker.com/signup) account to complete this section.
## Overview
In this section, you'll learn how to set up and use GitHub Actions to build and test your Docker image as well as push it to Docker Hub. You will complete the following steps:
1. Create a new repository on GitHub.
2. Define the GitHub Actions workflow.
3. Run the workflow.
## Step one: Create the repository
Create a GitHub repository, configure the Docker Hub secrets, and push your source code.
1. [Create a new repository](https://github.com/new) on GitHub.
2. Open the repository **Settings**, and go to **Secrets and variables** >
**Actions**.
3. Create a new secret named `DOCKER_USERNAME` and your Docker ID as value.
4. Create a new [Personal Access Token (PAT)](../../security/for-developers/access-tokens.md/#create-an-access-token) for Docker Hub. You can name this token `tutorial-docker`.
5. Add the PAT as a second secret in your GitHub repository, with the name
`DOCKERHUB_TOKEN`.
6. In your local repository on your machine, run the following command to change
the origin to the repository you just created. Make sure you change
`your-username` to your GitHub username and `your-repository` to the name of
the repository you created.
```console
$ git remote set-url origin https://github.com/your-username/your-repository.git
```
7. In your local repository on your machine, run the following command to rename
the branch to main.
```console
$ git branch -M main
```
8. Run the following commands to stage, commit, and then push your local
repository to GitHub.
```console
$ git add -A
$ git commit -m "my first commit"
$ git push -u origin main
```
## Step two: Set up the workflow
Set up your GitHub Actions workflow for building, testing, and pushing the image
to Docker Hub.
1. Go to your repository on GitHub and then select the **Actions** tab.
2. Select **set up a workflow yourself**.
This takes you to a page for creating a new GitHub actions workflow file in
your repository, under `.github/workflows/main.yml` by default.
3. In the editor window, copy and paste the following YAML configuration.
```yaml
name: ci
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
-
name: Build and test
uses: docker/build-push-action@v5
with:
context: .
target: test
load: true
-
name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
target: final
tags: ${{ secrets.DOCKER_USERNAME }}/${{ github.event.repository.name }}:latest
```
For more information about the YAML syntax used here, see [Workflow syntax for GitHub Actions](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions).
## Step three: Run the workflow
Save the workflow file and run the job.
1. Select **Commit changes...** and push the changes to the `main` branch.
After pushing the commit, the workflow starts automatically.
2. Go to the **Actions** tab. It displays the workflow.
Selecting the workflow shows you the breakdown of all the steps.
3. When the workflow is complete, go to your
[repositories on Docker Hub](https://hub.docker.com/repositories).
If you see the new repository in that list, it means the GitHub Actions
successfully pushed the image to Docker Hub.
## Summary
In this section, you learned how to set up a GitHub Actions workflow for your application.
Related information:
- [Introduction to GitHub Actions](../../build/ci/github-actions/index.md)
- [Workflow syntax for GitHub Actions](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions)
## Next steps
Next, learn how you can locally test and debug your workloads on Kubernetes before deploying.
{{< button text="Test your deployment" url="./deploy.md" >}}

View File

@ -0,0 +1,130 @@
---
title: Containerize a PHP application
keywords: php, containerize, initialize, apache, composer
description: Learn how to containerize a PHP application.
---
## Prerequisites
* You have installed the latest version of [Docker
Desktop](../../get-docker.md).
* You have a [git client](https://git-scm.com/downloads). The examples in this
section use a command-line based git client, but you can use any client.
## Overview
This section walks you through containerizing and running a PHP
application.
## Get the sample applications
In this guide, you will use a pre-built PHP application. The application uses Composer for library dependency management. You'll serve the application via an Apache web server.
Open a terminal, change directory to a directory that you want to work in, and
run the following command to clone the repository.
```console
$ git clone https://github.com/docker/docker-php-sample
```
The sample application is a basic hello world application and an application that increments a counter in a database. In addition, the application uses PHPUnit for testing.
## Initialize Docker assets
Now that you have an application, you can use `docker init` to create the
necessary Docker assets to containerize your application. Inside the
`docker-php-sample` directory, run the `docker init` command in a terminal.
`docker init` provides some default configuration, but you'll need to answer a
few questions about your application. For example, this application uses PHP
version 8.2. Refer to the following `docker init` example and use the same
answers for your prompts.
```console
$ 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
```
You should now have the following contents in your `docker-php-sample`
directory.
```text
├── docker-php-sample/
│ ├── .git/
│ ├── src/
│ ├── tests/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── compose.yaml
│ ├── composer.json
│ ├── composer.lock
│ ├── Dockerfile
│ ├── README.Docker.md
│ └── README.md
```
To learn more about the files that `docker init` added, see the following:
- [Dockerfile](../../engine/reference/builder.md)
- [.dockerignore](../../engine/reference/builder.md#dockerignore-file)
- [compose.yaml](../../compose/compose-file/_index.md)
## Run the application
Inside the `docker-php-sample` directory, run the following command in a
terminal.
```console
$ docker compose up --build
```
Open a browser and view the application at [http://localhost:9000/hello.php](http://localhost:9000/hello.php). You should see a simple hello world application.
In the terminal, press `ctrl`+`c` to stop the application.
### Run the application in the background
You can run the application detached from the terminal by adding the `-d`
option. Inside the `docker-php-sample` directory, run the following command
in a terminal.
```console
$ docker compose up --build -d
```
Open a browser and view the application at [http://localhost:9000/hello.php](http://localhost:9000/hello.php). You should see a simple hello world application.
In the terminal, run the following command to stop the application.
```console
$ docker compose down
```
For more information about Compose commands, see the [Compose CLI
reference](../../compose/reference/_index.md).
## Summary
In this section, you learned how you can containerize and run a simple PHP
application using Docker.
Related information:
- [docker init reference](../../engine/reference/commandline/init.md)
## Next steps
In the next section, you'll learn how you can develop your application using
Docker containers.
{{< button text="Develop your application" url="develop.md" >}}

View File

@ -0,0 +1,140 @@
---
title: Test your PHP deployment
keywords: deploy, php, local, development
description: Learn how to deploy your application
---
## Prerequisites
- Complete all the previous sections of this guide, starting with [Containerize
a PHP application](containerize.md).
- [Turn on Kubernetes](/desktop/kubernetes/#turn-on-kubernetes) in Docker
Desktop.
## Overview
In this section, you'll learn how to use Docker Desktop to deploy your
application to a fully-featured Kubernetes environment on your development
machine. This allows you to test and debug your workloads on Kubernetes locally
before deploying.
## Create a Kubernetes YAML file
In your `docker-php-sample` directory, create a file named
`docker-php-kubernetes.yaml`. Open the file in an IDE or text editor and add
the following contents. Replace `DOCKER_USERNAME/REPO_NAME` with your Docker
username and the name of the repository that you created in [Configure CI/CD for
your PHP application](configure-ci-cd.md).
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: docker-php-demo
namespace: default
spec:
replicas: 1
selector:
matchLabels:
hello-php: web
template:
metadata:
labels:
hello-php: web
spec:
containers:
- name: hello-site
image: DOCKER_USERNAME/REPO_NAME
imagePullPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
name: php-entrypoint
namespace: default
spec:
type: NodePort
selector:
hello-php: web
ports:
- port: 80
targetPort: 80
nodePort: 30001
```
In this Kubernetes YAML file, there are two objects, separated by the `---`:
- A Deployment, describing a scalable group of identical pods. In this case,
you'll get just one replica, or copy of your pod. That pod, which is
described under `template`, has just one container in it. The container is
created from the image built by GitHub Actions in [Configure CI/CD for your
PHP application](configure-ci-cd.md).
- A NodePort service, which will route traffic from port 30001 on your host to
port 80 inside the pods it routes to, allowing you to reach your app
from the network.
To learn more about Kubernetes objects, see the [Kubernetes documentation](https://kubernetes.io/docs/home/).
## Deploy and check your application
1. In a terminal, navigate to the `docker-php-sample` directory
and deploy your application to Kubernetes.
```console
$ kubectl apply -f docker-php-kubernetes.yaml
```
You should see output that looks like the following, indicating your Kubernetes objects were created successfully.
```text
deployment.apps/docker-php-demo created
service/php-entrypoint created
```
2. Make sure everything worked by listing your deployments.
```console
$ kubectl get deployments
```
Your deployment should be listed as follows:
```text
NAME READY UP-TO-DATE AVAILABLE AGE
docker-php-demo 1/1 1 1 6s
```
This indicates all of the pods are up and running. Do the same check for your services.
```console
$ kubectl get services
```
You should get output like the following.
```text
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 7d22h
php-entrypoint NodePort 10.111.101.229 <none> 80:30001/TCP 33s
```
In addition to the default `kubernetes` service, you can see your `php-entrypoint` service. The `php-entrypoint` service is accepting traffic on port 30001/TCP.
3. Open a browser and visit your app at
[http://localhost:30001/hello.php](http://localhost:30001/hello.php). You
should see your application.
4. Run the following command to tear down your application.
```console
$ kubectl delete -f docker-php-kubernetes.yaml
```
## Summary
In this section, you learned how to use Docker Desktop to deploy your application to a fully-featured Kubernetes environment on your development machine.
Related information:
- [Kubernetes documentation](https://kubernetes.io/docs/home/)
- [Deploy on Kubernetes with Docker Desktop](../../desktop/kubernetes.md)
- [Swarm mode overview](../../engine/swarm/_index.md)

View File

@ -0,0 +1,430 @@
---
title: Use containers for PHP development
keywords: php, development
description: Learn how to develop your PHP application locally using containers.
---
## Prerequisites
Complete [Containerize a PHP application](containerize.md).
## Overview
In this section, you'll learn how to set up a development environment for your containerized application. This includes:
- Adding a local database and persisting data
- Adding phpMyAdmin to interact with the database
- Configuring Compose to automatically update your running Compose services as
you edit and save your code
- Creating a development container that contains the dev dependencies
## Add a local database and persist data
You can use containers to set up local services, like a database.
To do this for the sample application, you'll need to do the following:
- Update the `Dockerfile` to install extensions to connect to the database
- Update the `compose.yaml` file to add a database service and volume to persist data
### Update the Dockerfile to install extensions
To install PHP extensions, you need to update the `Dockerfile`. Open your
Dockerfile in an IDE or text editor and then update the contents. The following
`Dockerfile` includes one new line that installs the `pdo` and `pdo_mysql`
extensions. All comments have been removed.
```dockerfile {hl_lines=11}
# syntax=docker/dockerfile:1
FROM composer:lts as deps
WORKDIR /app
RUN --mount=type=bind,source=composer.json,target=composer.json \
--mount=type=bind,source=composer.lock,target=composer.lock \
--mount=type=cache,target=/tmp/cache \
composer install --no-dev --no-interaction
FROM php:8.2-apache as final
RUN docker-php-ext-install pdo pdo_mysql
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY --from=deps app/vendor/ /var/www/html/vendor
COPY ./src /var/www/html
USER www-data
```
For more details about installing PHP extensions, see the [Official Docker Image for PHP](https://hub.docker.com/_/php).
### Update the compose.yaml file to add a db and persist data
Open the `compose.yaml` file in an IDE or text editor. You'll notice it
already contains commented-out instructions for a PostgreSQL database and volume. For this application, you'll use MariaDB. For more details about MariaDB, see the [MariaDB Official Docker image](https://hub.docker.com/_/mariadb).
Open the `src/database.php` file in an IDE or text editor. You'll notice that it reads environment variables in order to connect to the database.
In the `compose.yaml` file, you'll need to update the following:
1. Uncomment and update the database instructions for MariaDB.
2. Add a secret to the server service to pass in the database password.
3. Add the database connection environment variables to the server service.
4. Uncomment the volume instructions to persist data.
The following is the updated `compose.yaml` file. All comments have been removed.
```yaml
services:
server:
build:
context: .
ports:
- 9000:80
depends_on:
db:
condition: service_healthy
secrets:
- db-password
environment:
- PASSWORD_FILE_PATH=/run/secrets/db-password
- DB_HOST=db
- DB_NAME=example
- DB_USER=root
db:
image: mariadb
restart: always
user: root
secrets:
- db-password
volumes:
- db-data:/var/lib/mysql
environment:
- MARIADB_ROOT_PASSWORD_FILE=/run/secrets/db-password
- MARIADB_DATABASE=example
expose:
- 3306
healthcheck:
test: ["CMD", "/usr/local/bin/healthcheck.sh", "--su-mysql", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
```
> **Note**
>
> To learn more about the instructions in the Compose file, see [Compose file
> reference](/compose/compose-file/).
Before you run the application using Compose, notice that this Compose file uses
`secrets` and specifies a `password.txt` file to hold the database's password.
You must create this file as it's not included in the source repository.
In the `docker-php-sample` directory, create a new directory named `db` and
inside that directory create a file named `password.txt`. Open `password.txt` in an IDE or text editor and add the following password. The password must be on a single line, with no additional lines in the file.
```text
example
```
Save and close the `password.txt` file.
You should now have the following in your `docker-php-sample` directory.
```text
├── docker-php-sample/
│ ├── .git/
│ ├── db/
│ │ └── password.txt
│ ├── src/
│ ├── tests/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── compose.yaml
│ ├── composer.json
│ ├── composer.lock
│ ├── Dockerfile
│ ├── README.Docker.md
│ └── README.md
```
Run the following command to start your application.
```console
$ docker compose up --build
```
Open a browser and view the application at [http://localhost:9000/database.php](http://localhost:9000/database.php). You should see a simple web application with text and a counter that increments every time you refresh.
Press `ctrl+c` in the terminal to stop your application.
## Verify that data persists in the database
In the terminal, run `docker compose rm` to remove your containers and then run `docker compose up` to run your application again.
```console
$ docker compose rm
$ docker compose up --build
```
Refresh [http://localhost:9000/database.php](http://localhost:9000/database.php) in your browser and verify that the previous count still exists. Without a volume, the database data wouldn't persist after you remove the container.
Press `ctrl+c` in the terminal to stop your application.
## Add phpMyAdmin to interact with the database
You can easily add services to your application stack by updating the `compose.yaml` file.
Update your `compose.yaml` to add a new service for phpMyAdmin. For more details, see the [phpMyAdmin Official Docker Image](https://hub.docker.com/_/phpmyadmin). The following is the updated `compose.yaml` file.
```yaml {hl_lines="35-42"}
services:
server:
build:
context: .
ports:
- 9000:80
depends_on:
db:
condition: service_healthy
secrets:
- db-password
environment:
- PASSWORD_FILE_PATH=/run/secrets/db-password
- DB_HOST=db
- DB_NAME=example
- DB_USER=root
db:
image: mariadb
restart: always
user: root
secrets:
- db-password
volumes:
- db-data:/var/lib/mysql
environment:
- MARIADB_ROOT_PASSWORD_FILE=/run/secrets/db-password
- MARIADB_DATABASE=example
expose:
- 3306
healthcheck:
test: ["CMD", "/usr/local/bin/healthcheck.sh", "--su-mysql", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 5
phpmyadmin:
image: phpmyadmin
ports:
- 8080:80
depends_on:
- db
environment:
- PMA_HOST=db
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
```
In the terminal, run `docker compose up` to run your application again.
```console
$ docker compose up --build
```
Open [http://localhost:8080](http://localhost:8080) in your browser to access phpMyAdmin. Log in using `root` as the username and `example` as the password. You can now interact with the database through phpMyAdmin.
Press `ctrl+c` in the terminal to stop your application.
## Automatically update services
Use Compose Watch to automatically update your running Compose services as you edit and save your code. For more details about Compose Watch, see [Use Compose Watch](../../compose/file-watch.md).
Open your `compose.yaml` file in an IDE or text editor and then add the Compose Watch instructions. The following is the updated `compose.yaml` file.
```yaml {hl_lines="17-21"}
services:
server:
build:
context: .
ports:
- 9000:80
depends_on:
db:
condition: service_healthy
secrets:
- db-password
environment:
- PASSWORD_FILE_PATH=/run/secrets/db-password
- DB_HOST=db
- DB_NAME=example
- DB_USER=root
develop:
watch:
- action: sync
path: ./src
target: /var/www/html
db:
image: mariadb
restart: always
user: root
secrets:
- db-password
volumes:
- db-data:/var/lib/mysql
environment:
- MARIADB_ROOT_PASSWORD_FILE=/run/secrets/db-password
- MARIADB_DATABASE=example
expose:
- 3306
healthcheck:
test: ["CMD", "/usr/local/bin/healthcheck.sh", "--su-mysql", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 5
phpmyadmin:
image: phpmyadmin
ports:
- 8080:80
depends_on:
- db
environment:
- PMA_HOST=db
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
```
Run the following command to run your application with Compose Watch.
```console
$ docker compose watch
```
Open a browser and verify that the application is running at [http://localhost:9000/hello.php](http://localhost:9000/hello.php).
Any changes to the application's source files on your local machine will now be
immediately reflected in the running container.
Open `hello.php` in an IDE or text editor and update the string `Hello, world!` to `Hello, Docker!`.
Save the changes to `hello.php` and then wait a few seconds for the application to sync. Refresh [http://localhost:9000/hello.php](http://localhost:9000/hello.php) in your browser and verify that the updated text appears.
Press `ctrl+c` in the terminal to stop Compose Watch. Run `docker compose down` in the terminal to stop the application.
## Create a development container
At this point, when you run your containerized application, Composer isn't installing the dev dependencies. While this small image is good for production, it lacks the tools and dependencies you may need when developing and it doesn't include the `tests` directory. You can use multi-stage builds to build stages for both development and production in the same Dockerfile. For more details, see [Multi-stage builds](../../build/building/multi-stage.md).
In the `Dockerfile`, you'll need to update the following:
1. Split the `deps` staged into two stages. One stage for production
(`prod-deps`) and one stage (`dev-deps`) to install development dependencies.
2. Create a common `base` stage.
3. Create a new `development` stage for development.
4. Update the `final` stage to copy dependencies from the new `prod-deps` stage.
The following is the `Dockerfile` before and after the changes.
{{< tabs >}}
{{< tab name="Before" >}}
```dockerfile
# syntax=docker/dockerfile:1
FROM composer:lts as deps
WORKDIR /app
RUN --mount=type=bind,source=composer.json,target=composer.json \
--mount=type=bind,source=composer.lock,target=composer.lock \
--mount=type=cache,target=/tmp/cache \
composer install --no-dev --no-interaction
FROM php:8.2-apache as final
RUN docker-php-ext-install pdo pdo_mysql
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY --from=deps app/vendor/ /var/www/html/vendor
COPY ./src /var/www/html
USER www-data
```
{{< /tab >}}
{{< tab name="After" >}}
```dockerfile
# syntax=docker/dockerfile:1
FROM composer:lts as prod-deps
WORKDIR /app
RUN --mount=type=bind,source=./composer.json,target=composer.json \
--mount=type=bind,source=./composer.lock,target=composer.lock \
--mount=type=cache,target=/tmp/cache \
composer install --no-dev --no-interaction
FROM composer:lts as dev-deps
WORKDIR /app
RUN --mount=type=bind,source=./composer.json,target=composer.json \
--mount=type=bind,source=./composer.lock,target=composer.lock \
--mount=type=cache,target=/tmp/cache \
composer install --no-interaction
FROM php:8.2-apache as base
RUN docker-php-ext-install pdo pdo_mysql
COPY ./src /var/www/html
FROM base as development
COPY ./tests /var/www/html/tests
RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
COPY --from=dev-deps app/vendor/ /var/www/html/vendor
FROM base as final
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY --from=prod-deps app/vendor/ /var/www/html/vendor
USER www-data
```
{{< /tab >}}
{{< /tabs >}}
Update your `compose.yaml` file by adding an instruction to target the
development stage.
The following is the updated section of the `compose.yaml` file.
```yaml {hl_lines=5}
services:
server:
build:
context: .
target: development
# ...
```
Your containerized application will now install the dev dependencies.
Run the following command to start your application.
```console
$ docker compose up --build
```
Open a browser and view the application at [http://localhost:9000/hello.php](http://localhost:9000/hello.php). You should still see the simple "Hello, Docker!" application.
Press `ctrl+c` in the terminal to stop your application.
While the application appears the same, you can now make use of the dev dependencies. Continue to the next section to learn how you can run tests using Docker.
## Summary
In this section, you took a look at setting up your Compose file to add a local
database and persist data. You also learned how to use Compose Watch to automatically sync your application when you update your code. And finally, you learned how to create a development container that contains the dependencies needed for development.
Related information:
- [Build with Docker guide](../../build/guide/index.md)
- [Compose file reference](/compose/compose-file/)
- [Compose file watch](../../compose/file-watch.md)
- [Dockerfile reference](../../engine/reference/builder.md)
- [Official Docker Image for PHP](https://hub.docker.com/_/php)
## Next steps
In the next section, you'll learn how to run unit tests using Docker.
{{< button text="Run your tests" url="run-tests.md" >}}

View File

@ -0,0 +1,117 @@
---
title: Run PHP tests in a container
keywords: php, test
description: Learn how to run your PHP tests in a container.
---
## Prerequisites
Complete all the previous sections of this guide, starting with [Containerize a PHP application](containerize.md).
## Overview
Testing is an essential part of modern software development. Testing can mean a
lot of things to different development teams. There are unit tests, integration
tests and end-to-end testing. In this guide you take a look at running your unit
tests in Docker when developing and when building.
## Run tests when developing locally
The sample application already has a PHPUnit test inside the `tests` directory. When developing locally, you can use Compose to run your tests.
Run the following command in the `docker-php-sample` directory to run the tests inside a container.
```console
$ docker compose run --build --rm server ./vendor/bin/phpunit tests/HelloWorldTest.php
```
You should see output that contains the following.
```console
Hello, Docker!PHPUnit 9.6.13 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.003, Memory: 4.00 MB
OK (1 test, 1 assertion)
```
To learn more about the command, see [docker compose run](/engine/reference/commandline/compose_run/).
## Run tests when building
To run your tests when building, you need to update your Dockerfile. Create a new test stage that runs the tests.
The following is the updated Dockerfile.
```dockerfile {hl_lines="26-28"}
# syntax=docker/dockerfile:1
FROM composer:lts as prod-deps
WORKDIR /app
RUN --mount=type=bind,source=./composer.json,target=composer.json \
--mount=type=bind,source=./composer.lock,target=composer.lock \
--mount=type=cache,target=/tmp/cache \
composer install --no-dev --no-interaction
FROM composer:lts as dev-deps
WORKDIR /app
RUN --mount=type=bind,source=./composer.json,target=composer.json \
--mount=type=bind,source=./composer.lock,target=composer.lock \
--mount=type=cache,target=/tmp/cache \
composer install --no-interaction
FROM php:8.2-apache as base
RUN docker-php-ext-install pdo pdo_mysql
COPY ./src /var/www/html
FROM base as development
COPY ./tests /var/www/html/tests
RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
COPY --from=dev-deps app/vendor/ /var/www/html/vendor
FROM development as test
WORKDIR /var/www/html
RUN ./vendor/bin/phpunit tests/HelloWorldTest.php
FROM base as final
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY --from=prod-deps app/vendor/ /var/www/html/vendor
USER www-data
```
Run the following command to build an image using the test stage as the target and view the test results. Include `--progress plain` to view the build output, `--no-cache` to ensure the tests always run, and `--target test` to target the test stage.
```console
$ docker build -t php-docker-image-test --progress plain --no-cache --target test .
```
You should see output containing the following.
```console
#18 [test 2/2] RUN ./vendor/bin/phpunit tests/HelloWorldTest.php
#18 0.385 Hello, Docker!PHPUnit 9.6.13 by Sebastian Bergmann and contributors.
#18 0.392
#18 0.394 . 1 / 1 (100%)
#18 0.395
#18 0.395 Time: 00:00.003, Memory: 4.00 MB
#18 0.395
#18 0.395 OK (1 test, 1 assertion)
```
To learn more about building and running tests, see the [Build with Docker guide](../../build/guide/_index.md).
## Summary
In this section, you learned how to run tests when developing locally using Compose and how to run tests when building your image.
Related information:
- [docker compose run](/engine/reference/commandline/compose_run/)
- [Build with Docker guide](../../build/guide/index.md)
## Next steps
Next, youll learn how to set up a CI/CD pipeline using GitHub Actions.
{{< button text="Configure CI/CD" url="configure-ci-cd.md" >}}

View File

@ -138,6 +138,20 @@ Guides:
path: /language/rust/configure-ci-cd/
- title: "Test your deployment"
path: /language/rust/deploy/
- sectiontitle: PHP
section:
- title: "Overview"
path: /language/php/
- title: "Containerize your app"
path: /language/php/containerize/
- title: "Develop your app"
path: /language/php/develop/
- title: "Run your tests"
path: /language/php/run-tests/
- title: "Configure CI/CD"
path: /language/php/configure-ci-cd/
- title: "Test your deployment"
path: /language/php/deploy/
- sectiontitle: Develop with Docker
section:
- path: /develop/