

# Deploying PHP applications with Elastic Beanstalk
<a name="create_deploy_PHP_eb"></a>

You can deploy a PHP application in a few minutes using the Elastic Beanstalk Command Line Interface (EB CLI) or the Elastic Beanstalk console. To learn how, start with the QuickStart tutorial, then review the advanced examples.

Resources for deploying PHP applications to Elastic Beanstalk
+ [QuickStart for PHP](php-quickstart.md) — Step-by-step instructions to deploy a *Hello World* PHP application using the EB CLI.
+ [Using the Elastic Beanstalk PHP platform](create_deploy_PHP.container.md) — How to use platform features specifically for PHP.
+ [Advanced examples](php-samples.md) — How to tutorials for common PHP frameworks and applications, plus how to add an Amazon RDS database to your environment.

For more info on developing with PHP in AWS, see the following resources:
+ [GitHub](https://github.com/aws/aws-sdk-php/) — Install the AWS SDK for PHP using GitHub.
+ [PHP Developer Center](https://aws.amazon.com/php/) — Tools, docs, and sample code to develop PHP applications on AWS.
+ [AWS SDK for PHP FAQs](http://docs.aws.amazon.com/aws-sdk-php/guide/latest/faq.html) — Get answers to commonly asked questions.

# QuickStart: Deploy a PHP application to Elastic Beanstalk
<a name="php-quickstart"></a>

In the following tutorial, you'll learn how to create and deploy a sample PHP application to an AWS Elastic Beanstalk environment using the EB CLI.

**Not for production use**  
Examples are intended for demonstration only. Do not use example applications in production.

**Topics**
+ [Your AWS account](#php-quickstart-aws-account)
+ [Prerequisites](#php-quickstart-prereq)
+ [Step 1: Create a PHP application](#php-quickstart-create-app)
+ [Step 2: Run your application locally](#php-quickstart-run-local)
+ [Step 3: Initialize and deploy your PHP application](#php-quickstart-deploy)
+ [Step 4: Browse your cloud application](#php-quickstart-run-eb-ap)
+ [Step 5: Update and redeploy your application](#php-quickstart-run-eb-ap)
+ [Clean up](#php-quickstart-cleanup)
+ [Next steps](#php-quickstart-next-steps)

## Your AWS account
<a name="php-quickstart-aws-account"></a>

If you're not already an AWS customer, you need to create an AWS account to use Elastic Beanstalk.

### Create an AWS account
<a name="php-quickstart-aws-account-procedure"></a>

#### Sign up for an AWS account
<a name="sign-up-for-aws"></a>

If you do not have an AWS account, complete the following steps to create one.

**To sign up for an AWS account**

1. Open [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Follow the online instructions.

   Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.

   When you sign up for an AWS account, an *AWS account root user* is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform [tasks that require root user access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to [https://aws.amazon.com/](https://aws.amazon.com/) and choosing **My Account**.

#### Create a user with administrative access
<a name="create-an-admin"></a>

After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks.

**Secure your AWS account root user**

1.  Sign in to the [AWS Management Console](https://console.aws.amazon.com/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.

   For help signing in by using root user, see [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial) in the *AWS Sign-In User Guide*.

1. Turn on multi-factor authentication (MFA) for your root user.

   For instructions, see [Enable a virtual MFA device for your AWS account root user (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html) in the *IAM User Guide*.

**Create a user with administrative access**

1. Enable IAM Identity Center.

   For instructions, see [Enabling AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html) in the *AWS IAM Identity Center User Guide*.

1. In IAM Identity Center, grant administrative access to a user.

   For a tutorial about using the IAM Identity Center directory as your identity source, see [ Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html) in the *AWS IAM Identity Center User Guide*.

**Sign in as the user with administrative access**
+ To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user.

  For help signing in using an IAM Identity Center user, see [Signing in to the AWS access portal](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

**Assign access to additional users**

1. In IAM Identity Center, create a permission set that follows the best practice of applying least-privilege permissions.

   For instructions, see [ Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html) in the *AWS IAM Identity Center User Guide*.

1. Assign users to a group, and then assign single sign-on access to the group.

   For instructions, see [ Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html) in the *AWS IAM Identity Center User Guide*.

## Prerequisites
<a name="php-quickstart-prereq"></a>
+ Elastic Beanstalk Command Line Interface - For installation, see [Install EB CLI with setup script (recommended)](eb-cli3.md#eb-cli3-install).
+ PHP - Install PHP on your local machine by following [Installation and Configuration](https://www.php.net/manual/en/install.php) instructions on the PHP website.

## Step 1: Create a PHP application
<a name="php-quickstart-create-app"></a>

For this quick start, you will create a *Hello World* PHP application.

Create a project directory.

```
~$ mkdir eb-php
~$ cd eb-php
```

Next, create an `index.php` file in the project directory and add the following code.

**Example `index.php`**  

```
<?php
  echo "Hello from a PHP application running in Elastic Beanstalk!";
?>
```

## Step 2: Run your application locally
<a name="php-quickstart-run-local"></a>

Use the following command to run your application locally.

```
~$ php -S localhost:5000
```

Open a browser to [http://localhost:5000](http://localhost:5000).

You should see your hello message in the browser and log messages in your terminal.

Stop the local server by entering `Control+c`, so you can deploy the Elastic Beanstalk.

## Step 3: Initialize and deploy your PHP application
<a name="php-quickstart-deploy"></a>

Next, you will deploy your application to an *environment* using the Elastic Beanstalk console or the EB CLI. For this tutorial, you'll use the EB CLI with the interactive option to initialize an environment. 

**To initialize your environment and create an environment**

1. Run the following **init** command.

   ```
   ~$ eb init -i
   ```

   The init command creates an application interactively. The application name will default to the local folder which is `eb-php`.

   For all prompts, except SSH access, accept the defaults to create an environment with the latest PHP platform version. For troubleshooting instances, you can set up SSH access by re-running the `eb init -i`command at a later time, or connect using Amazon EC2 Instance Connect or Session Manager.

1. Create an environment and deploy your application

   Run the following command to create an environment named `blue-env`.

   ```
   ~$ eb create blue-env
   ```

   When you run the **eb create** command for the first time, Elastic Beanstalk automatically builds a zip file of your application, called a *source bundle*. Next, Elastic Beanstalk creates an environment with one or more Amazon EC2 instances, and then deploys the application into the environment.

   Deploying your application to Elastic Beanstalk might take up to five minutes.

## Step 4: Browse your cloud application
<a name="php-quickstart-run-eb-ap"></a>

When the process to create your environment completes, your application should be running and listening for requests on port 5000. Connect to your application with the following command:

```
~$ eb open
```

The `eb open` command opens a browser tab to a custom subdomain created for your application.

## Step 5: Update and redeploy your application
<a name="php-quickstart-run-eb-ap"></a>

After you have created an application and deployed to an environment, you can deploy a new version of the application or a different application at any time. Deploying a new application version is faster because it doesn't require provisioning or restarting Amazon EC2 instances.

Update your PHP code to include the REQUEST\$1TIME value from the server environment:

```
<?php
  echo "Hello from a PHP application running in Elastic Beanstalk!";
  
  $timestamp = $_SERVER['REQUEST_TIME'];
  echo '<br/>Request time: ' . date('Y/m/d H:i:s', $timestamp);
?>
```

Redeploy your PHP code to Elastic Beanstalk with the following command:

```
~$ eb deploy
```

When you run **eb deploy**, the EB CLI bundles up the contents of your project directory and deploys it to your environment.

After the deploy finishes, refresh the page or reconnect to your application with `eb open`. You should see your updates. If not, troubleshoot by running your local server again to verify your changes.

****Congratulations\$1****  
You've created, deployed, and updated a PHP application with Elastic Beanstalk\$1

## Clean up
<a name="php-quickstart-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

Alternatively, you can terminate your environment with the EB CLI with the following command:

```
~$ eb terminate
```

## Next steps
<a name="php-quickstart-next-steps"></a>

You can explore your application environment using the Elastic Beanstalk console. For more info, see [Explore your environment](GettingStarted.md#GettingStarted.Explore).

For advanced examples using PHP, see [Advanced examples for PHP in Elastic Beanstalk](php-samples.md).

# Using the Elastic Beanstalk PHP platform
<a name="create_deploy_PHP.container"></a>

AWS Elastic Beanstalk provides and supports various **platform branches** for different versions of PHP. The platforms support PHP web applications that run stand-alone or under Composer. See [PHP](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.PHP) in the *AWS Elastic Beanstalk Platforms* document for a full list of supported platform branches.

Elastic Beanstalk provides [configuration options](command-options.md) that you can use to customize the software that runs on the Amazon EC2 instances in your Elastic Beanstalk environment. You can [configure environment variables](environments-cfg-softwaresettings.md#environments-cfg-softwaresettings-console) required by your application, enable log rotation to Amazon S3, map folders in your application source that contain static files to paths served by the proxy server, and set common PHP initialization settings.

Configuration options are available in the Elastic Beanstalk console for [modifying the configuration of a running environment](environment-configuration-methods-after.md). To avoid losing your environment's configuration when you terminate it, you can use [saved configurations](environment-configuration-savedconfig.md) to save your settings and later apply them to another environment.

To save settings in your source code, you can include [configuration files](ebextensions.md). Settings in configuration files are applied every time you create an environment or deploy your application. You can also use configuration files to install packages, run scripts, and perform other instance customization operations during deployments.

If you use Composer, you can [include a `composer.json` file](#php-configuration-composer) in your source bundle to install packages during deployment.

For advanced PHP configuration and PHP settings that are not provided as configuration options, you can [use configuration files to provide an `INI` file](#php-configuration-phpini) that can extend and override the default settings applied by Elastic Beanstalk, or install additional extensions.

Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they exist. This lets you have default settings in configuration files, and override them with environment-specific settings in the console. For more information about precedence, and other methods of changing settings, see [Configuration options](command-options.md).

For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see [Extending Elastic Beanstalk Linux platforms](platforms-linux-extend.md).

**Topics**
+ [Installing the AWS SDK for PHP](#php-development-environment-sdk)
+ [Considerations for PHP 8.1 on Amazon Linux 2](#php-8-1-considerations)
+ [Configuring your PHP environment](#php-console)
+ [Namespaces for configuration](#php-namespaces)
+ [Installing dependencies](#php-configuration-composer)
+ [Updating Composer](#php-configuration-composerupdate)
+ [Extending php.ini](#php-configuration-phpini)

## Installing the AWS SDK for PHP
<a name="php-development-environment-sdk"></a>

If you need to manage AWS resources from within your application, install the AWS SDK for PHP. For example, with the SDK for PHP, you can use Amazon DynamoDB (DynamoDB) to store user and session information without creating a relational database.

To install the SDK for PHP with Composer

```
$ composer require aws/aws-sdk-php
```

For more information, see the [AWS SDK for PHP](https://aws.amazon.com/sdk-for-php/) homepage. For instructions, see [ Install the AWS SDK for PHP](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/getting-started_installation.html).

## Considerations for PHP 8.1 on Amazon Linux 2
<a name="php-8-1-considerations"></a>

Read this section if you're using the *PHP 8.1 on Amazon Linux 2* platform branch.

### Considerations for PHP 8.1 on Amazon Linux 2
<a name="php-8-1-considerations-detail"></a>

**Note**  
The information in this topic only applies to the *PHP 8.1 on Amazon Linux 2* platform branch. It does not apply to the PHP platform branches based on AL2023. It also does not apply to the *PHP 8.0 Amazon Linux 2* platform branch. 

Elastic Beanstalk stores the PHP 8.1 related RPM packages for the *PHP 8.1 on Amazon Linux 2* platform branch on the EC2 instances in a local directory, instead of the Amazon Linux repository. You can use **rpm -i ** to install packages. Starting with [PHP 8.1 Platform Version 3.5.0](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-10-03-linux.html), Elastic Beanstalk stores the PHP 8.1 related RPM packages in the following local EC2 directory.

 `/opt/elasticbeanstalk/RPMS` 

The following example installs the *php-debuginfo* package.

```
$rpm -i /opt/elasticbeanstalk/RPMS/php-debuginfo-8.1.8-1.amzn2.x86_64.rpm
```

The version in the package name will vary according to the actual version that's listed in the EC2 local directory `/opt/elasticbeanstalk/RPMS`. Use the same syntax to install other PHP 8.1 RPM packages.

Expand the following section to display a list of RPM packages we provide.

#### RPM Packages
<a name="php-8-1-considerations-detail-rpm-packages"></a>

The following list provides the RMP packages that the Elastic Beanstalk PHP 8.1 platform provides on Amazon Linux 2. These are located in the local directory `/opt/elasticbeanstalk/RPMS`.

The version numbers *8.1.8-1* and *3.7.0-1 * in the listed package names are only an example.
+ `php-8.1.8-1.amzn2.x86_64.rpm`
+ `php-bcmath-8.1.8-1.amzn2.x86_64.rpm`
+ `php-cli-8.1.8-1.amzn2.x86_64.rpm`
+ `php-common-8.1.8-1.amzn2.x86_64.rpm`
+ `php-dba-8.1.8-1.amzn2.x86_64.rpm`
+ `php-dbg-8.1.8-1.amzn2.x86_64.rpm`
+ `php-debuginfo-8.1.8-1.amzn2.x86_64.rpm`
+ `php-devel-8.1.8-1.amzn2.x86_64.rpm`
+ `php-embedded-8.1.8-1.amzn2.x86_64.rpm`
+ `php-enchant-8.1.8-1.amzn2.x86_64.rpm`
+ `php-fpm-8.1.8-1.amzn2.x86_64.rpm`
+ `php-gd-8.1.8-1.amzn2.x86_64.rpm`
+ `php-gmp-8.1.8-1.amzn2.x86_64.rpm`
+ `php-intl-8.1.8-1.amzn2.x86_64.rpm`
+ `php-ldap-8.1.8-1.amzn2.x86_64.rpm`
+ `php-mbstring-8.1.8-1.amzn2.x86_64.rpm`
+ `php-mysqlnd-8.1.8-1.amzn2.x86_64.rpm`
+ `php-odbc-8.1.8-1.amzn2.x86_64.rpm`
+ `php-opcache-8.1.8-1.amzn2.x86_64.rpm`
+ `php-pdo-8.1.8-1.amzn2.x86_64.rpm`
+ `php-pear-1.10.13-1.amzn2.noarch.rpm`
+ `php-pgsql-8.1.8-1.amzn2.x86_64.rpm`
+ `php-process-8.1.8-1.amzn2.x86_64.rpm`
+ `php-pspell-8.1.8-1.amzn2.x86_64.rpm`
+ `php-snmp-8.1.8-1.amzn2.x86_64.rpm`
+ `php-soap-8.1.8-1.amzn2.x86_64.rpm`
+ `php-sodium-8.1.8-1.amzn2.x86_64.rpm`
+ `php-xml-8.1.8-1.amzn2.x86_64.rpm`
+ `php-pecl-imagick-3.7.0-1.amzn2.x86_64.rpm`
+ `php-pecl-imagick-debuginfo-3.7.0-1.amzn2.x86_64.rpm`
+ `php-pecl-imagick-devel-3.7.0-1.amzn2.noarch.rpm`

You can use the PEAR and PECL packages to install common extensions. For more information about PEAR, see the [PEAR PHP Extension and Application Repository](https://pear.php.net) website. For more information about PECL, see the [PECL extension](https://pecl.php.net) website.

The following example commands install the Memcached extensions.

```
$pecl install memcache
```

Or you could also use the following:

```
$pear install pecl/memcache
```

The following example commands install the Redis extensions.

```
$pecl install redis
```

Or you could also use the following:

```
$pear install pecl/redis
```

## Configuring your PHP environment
<a name="php-console"></a>

You can use the Elastic Beanstalk console to enable log rotation to Amazon S3, configure variables that your application can read from the environment, and change PHP settings.

**To configure your PHP environment in the Elastic Beanstalk console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

### PHP settings
<a name="php-console-settings"></a>
+ **Proxy server** – The proxy server to use on your environment instances. By default, nginx is used.
+ **Document root** – The folder that contains your site's default page. If your welcome page is not at the root of your source bundle, specify the folder that contains it relative to the root path. For example, `/public` if the welcome page is in a folder named `public`.
+ **Memory limit** – The maximum amount of memory that a script is allowed to allocate. For example, `512M`.
+ **Zlib output compression** – Set to `On` to compress responses.
+ **Allow URL fopen** – Set to `Off` to prevent scripts from downloading files from remote locations.
+ **Display errors** – Set to `On` to show internal error messages for debugging.
+ **Max execution time** – The maximum time in seconds that a script is allowed to run before the environment terminates it.

### Log options
<a name="php-console-logs"></a>

The Log Options section has two settings:
+ **Instance profile**– Specifies the instance profile that has permission to access the Amazon S3 bucket associated with your application.
+ **Enable log file rotation to Amazon S3** – Specifies whether log files for your application's Amazon EC2 instances are copied to the Amazon S3 bucket associated with your application.

### Static files
<a name="php-console-staticfiles"></a>

To improve performance, you can use the **Static files** section to configure the proxy server to serve static files (for example, HTML or images) from a set of directories inside your web application. For each directory, you set the virtual path to directory mapping. When the proxy server receives a request for a file under the specified path, it serves the file directly instead of routing the request to your application.

For details about configuring static files using configuration files or the Elastic Beanstalk console, see [Serving static files](environment-cfg-staticfiles.md).

### Environment properties
<a name="php-console-properties"></a>

The **Environment Properties** section lets you specify environment configuration settings on the Amazon EC2 instances that are running your application. These settings are passed in as key-value pairs to the application. 

Your application code can access environment properties by using `$_SERVER` or the `get_cfg_var` function.

```
$endpoint = $_SERVER['API_ENDPOINT'];
```

See [Environment variables and other software settings](environments-cfg-softwaresettings.md) for more information.

## Namespaces for configuration
<a name="php-namespaces"></a>

You can use a [configuration file](ebextensions.md) to set configuration options and perform other instance configuration tasks during deployments. Configuration options can be [platform specific](command-options-specific.md) or apply to [all platforms](command-options-general.md) in the Elastic Beanstalk service as a whole. Configuration options are organized into *namespaces*.

The following namespaces configure both your proxy service and PHP specific options:
+ [`aws:elasticbeanstalk:environment:proxy:staticfiles`](command-options-general.md#command-options-general-environmentproxystaticfiles) – configure the environment proxy to serve static files. You define mappings of virtual paths to application directories.
+ [`aws:elasticbeanstalk:environment:proxy`](command-options-specific.md#command-options-php) – specify the environment's proxy server. 
+ [`aws:elasticbeanstalk:container:php:phpini`](command-options-specific.md#command-options-php) – configure PHP specific options. This namespace includes `composer_options`, which is not available on the Elastic Beanstalk console. This option sets the custom options to use when installing dependencies using Composer through the `composer.phar install` command. For more information about this command, including available options, see [install](https://getcomposer.org/doc/03-cli.md#install-i) on the *getcomposer.org* website.

The following example [configuration file](ebextensions.md) specifies a static files option that maps a directory named `staticimages` to the path `/images`, and shows settings for each of the options available in the `aws:elasticbeanstalk:container:php:phpini` namespace:

**Example .ebextensions/php-settings.config**  

```
option_settings:
  aws:elasticbeanstalk:environment:proxy:
    ProxyServer: apache
  aws:elasticbeanstalk:environment:proxy:staticfiles:
    /images: staticimages
  aws:elasticbeanstalk:container:php:phpini:
    document_root: /public
    memory_limit: 128M
    zlib.output_compression: "Off"
    allow_url_fopen: "On"
    display_errors: "Off"
    max_execution_time: 60
    composer_options: vendor/package
```

**Note**  
The `aws:elasticbeanstalk:environment:proxy:staticfiles` namespace isn't defined on Amazon Linux AMI PHP platform branches (preceding Amazon Linux 2).

Elastic Beanstalk provides many configuration options for customizing your environment. In addition to configuration files, you can also set configuration options using the console, saved configurations, the EB CLI, or the AWS CLI. See [Configuration options](command-options.md) for more information.

## Installing your Elastic Beanstalk PHP application's dependencies
<a name="php-configuration-composer"></a>

This topic describes how to configure you application to install other PHP packages that it requires. Your application might have dependencies on other PHP packages. You can configure your application to install these dependencies on the environment's Amazon Elastic Compute Cloud (Amazon EC2) instances. Alternatively, you can include your application's dependencies in the source bundle and deploy them with the application. The following section discuss both of these ways.

### Use a Composer file to install dependencies on instances
<a name="php-configuration-composer.oninstances"></a>

Use a `composer.json` file in the root of your project source to use composer to install packages that your application requires on your environment's Amazon EC2 instances.

**Example composer.json**  

```
{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}
```

When a `composer.json` file is present, Elastic Beanstalk runs `composer.phar install` to install dependencies. You can add options to append to the command by setting the [`composer_options` option](#php-namespaces) in the `aws:elasticbeanstalk:container:php:phpini` namespace.

### Include dependencies in source bundle
<a name="php-configuration-composer.inbundle"></a>

If your application has a large number of dependencies, installing them might take a long time. This can increase deployment and scaling operations, because dependencies are installed on every new instance.

To avoid the negative impact on deployment time, use Composer in your development environment to resolve dependencies and install them into the `vendor` folder.

**To include dependencies in your application source bundle**

1. Run the following command:

   ```
   % composer install
   ```

1. Include the generated `vendor` folder in the root of your application source bundle.

When Elastic Beanstalk finds a `vendor` folder on the instance, it ignores the `composer.json` file (even if it exists). Your application then uses dependencies from the `vendor` folder.

## Updating Composer on Elastic Beanstalk
<a name="php-configuration-composerupdate"></a>

This topic describes how to configure Elastic Beanstalk to keep Composer up to date. You may have to update Composer if you see an error when you try to install packages with a Composer file, or if you're unable to use the latest platform version. Between platform updates, you can update Composer in your environment instances through the use of configuration files in your [`.ebextensions`](ebextensions.md) folder.

You can self-update Composer with the following configuration.

```
commands:
  01updateComposer:
    command: /usr/bin/composer.phar self-update 2.7.0
```

The following [option setting](command-options-general.md#command-options-general-elasticbeanstalkapplicationenvironment) sets the `COMPOSER_HOME` environment variable, which configures the location of the Composer cache.

```
option_settings:
  - namespace: aws:elasticbeanstalk:application:environment
    option_name: COMPOSER_HOME
    value: /home/webapp/composer-home
```

You can combine both of these in the same configuration file in your `.ebextensions` folder.

**Example .ebextensions/composer.config**  

```
commands:
  01updateComposer:
    command: /usr/bin/composer.phar self-update 2.7.0
    
option_settings:
  - namespace: aws:elasticbeanstalk:application:environment
    option_name: COMPOSER_HOME
    value: /home/webapp/composer-home
```

**Note**  
Due to updates to the Composer installation in the [February 22, 2024](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2024-02-22-al2023.html), AL2023 platform release and the [February 28, 2024](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2024-02-28-al2.html), AL2 platform release, the Composer self-update may fail if `COMPOSER_HOME` is set when the self-update executes.   
The following combined commands will fail to execute: `export COMPOSER_HOME=/home/webapp/composer-home && /usr/bin/composer.phar self-update 2.7.0`   
However, the previous example will work. In the previous example, the option setting for `COMPOSER_HOME` will not be passed to the `01updateComposer` execution, and it will not be set when the self-update command executes.

**Important**  
If you omit the version number from the `composer.phar self-update` command, Composer will update to the latest version available every time you deploy your source code, and when new instances are provisioned by Auto Scaling. This could cause scaling operations and deployments to fail if a version of Composer is released that is incompatible with your application.

For more information about the Elastic Beanstalk PHP Platforms, including the version of Composer, see [PHP platform versions](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.PHP) in the document *AWS Elastic Beanstalk Platforms*.

## Extending php.ini in your Elastic Beanstalk configuration
<a name="php-configuration-phpini"></a>

Use a configuration file with a `files` block to add a `.ini` file to `/etc/php.d/` on the instances in your environment. The main configuration file, `php.ini`, pulls in settings from files in this folder in alphabetical order. Many extensions are enabled by default by files in this folder.

**Example .ebextensions/mongo.config**  

```
files:
  "/etc/php.d/99mongo.ini":
    mode: "000755"
    owner: root
    group: root
    content: |
      extension=mongo.so
```

# Advanced examples for PHP in Elastic Beanstalk
<a name="php-samples"></a>

To get started with PHP applications on AWS Elastic Beanstalk, you need an application [source bundle](applications-sourcebundle.md) to upload as your first application version to deploy to an environment. 

We recommend the [QuickStart for PHP](php-quickstart.md) to get started with a simple PHP application deployed with the EB CLI.

**Topics**
+ [Adding a database](create_deploy_PHP.rds.md)
+ [Tutorial - Laravel](php-laravel-tutorial.md)
+ [Tutorial - CakePHP](php-cakephp-tutorial.md)
+ [Tutorial - Symfony](php-symfony-tutorial.md)
+ [Tutorial - HA production](php-ha-tutorial.md)
+ [Tutorial - HA WordPress](php-hawordpress-tutorial.md)
+ [Tutorial - HA Drupal](php-hadrupal-tutorial.md)

# Adding an Amazon RDS DB instance to your PHP Elastic Beanstalk environment
<a name="create_deploy_PHP.rds"></a>

This topic provides instructions to create an Amazon RDS using the Elastic Beanstalk console. You can use an Amazon Relational Database Service (Amazon RDS) DB instance to store data gathered and modified by your application. The database can be coupled to your environment and managed by Elastic Beanstalk, or it can be created as decoupled and managed externally by another service. In these instructions the database is coupled to your environment and managed by Elastic Beanstalk. For more information about integrating an Amazon RDS with Elastic Beanstalk, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

**Topics**
+ [Adding a DB instance to your environment](#php-rds-create)
+ [Downloading a driver](#php-rds-drivers)
+ [Connecting to a database with a PDO or MySQLi](#php-rds-connect)
+ [Connecting to a database with Symfony](#php-rds-symfony)

## Adding a DB instance to your environment
<a name="php-rds-create"></a>

**To add a DB instance to your environment**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Database** configuration category, choose **Edit**.

1. Choose a DB engine, and enter a user name and password.

1. To save the changes choose **Apply** at the bottom of the page.

Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB instance's hostname and other connection information are available to your application through the following environment properties:


| Property name | Description | Property value | 
| --- | --- | --- | 
|  `RDS_HOSTNAME`  |  The hostname of the DB instance.  |  On the **Connectivity & security** tab on the Amazon RDS console: **Endpoint**.  | 
|  `RDS_PORT`  |  The port where the DB instance accepts connections. The default value varies among DB engines.  |  On the **Connectivity & security** tab on the Amazon RDS console: **Port**.  | 
|  `RDS_DB_NAME`  |  The database name, **ebdb**.  |  On the **Configuration** tab on the Amazon RDS console: **DB Name**.  | 
|  `RDS_USERNAME`  |  The username that you configured for your database.  |  On the **Configuration** tab on the Amazon RDS console: **Master username**.  | 
|  `RDS_PASSWORD`  |  The password that you configured for your database.  |  Not available for reference in the Amazon RDS console.  | 

For more information about configuring a database instance coupled with an Elastic Beanstalk environment, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

## Downloading a driver
<a name="php-rds-drivers"></a>

To use PHP Data Objects (PDO) to connect to the database, install the driver that matches the database engine that you chose.
+ **MySQL** – [http://php.net/manual/en/ref.pdo-mysql.php](http://php.net/manual/en/ref.pdo-mysql.php)
+ **PostgreSQL** – [http://php.net/manual/en/ref.pdo-pgsql.php](http://php.net/manual/en/ref.pdo-pgsql.php)
+ **Oracle** – [http://php.net/manual/en/ref.pdo-oci.php](http://php.net/manual/en/ref.pdo-oci.php)
+ **SQL Server** – [http://php.net/manual/en/ref.pdo-sqlsrv.php](http://php.net/manual/en/ref.pdo-sqlsrv.php)

For more information, see [http://php.net/manual/en/pdo.installation.php](http://php.net/manual/en/pdo.installation.php).

## Connecting to a database with a PDO or MySQLi
<a name="php-rds-connect"></a>

You can use `$_SERVER[`VARIABLE`]` to read connection information from the environment.

For a PDO, create a Data Source Name (DSN) from the host, port, and name. Pass the DSN to the [constructor for the PDO](https://php.net/manual/en/pdo.construct.php) with the database user name and password.

**Example Connect to an RDS database with PDO - MySQL**  

```
<?php
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;

$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];

$pdo = new PDO($dsn, $username, $password);
?>
```

For other drivers, replace `mysql` with the name of your driver – `pgsql`, `oci`, or `sqlsrv`.

For MySQLi, pass the hostname, user name, password, database name, and port to the `mysqli` constructor.

**Example Connect to an RDS database with mysqli\$1connect()**  

```
$link = new mysqli($_SERVER['RDS_HOSTNAME'], $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);
```

## Connecting to a database with Symfony
<a name="php-rds-symfony"></a>

For Symfony version 3.2 and newer, you can use `%env(PROPERTY_NAME)%` to set database parameters in a configuration file based on the environment properties set by Elastic Beanstalk.

**Example app/config/parameters.yml**  

```
parameters:
    database_driver:   pdo_mysql
    database_host:     '%env(RDS_HOSTNAME)%'
    database_port:     '%env(RDS_PORT)%'
    database_name:     '%env(RDS_DB_NAME)%'
    database_user:     '%env(RDS_USERNAME)%'
    database_password: '%env(RDS_PASSWORD)%'
```

See [External Parameters (Symfony 3.4)](http://symfony.com/doc/3.4/configuration/external_parameters.html) for more information.

For earlier versions of Symfony, environment variables are only accessible if they start with `SYMFONY__`. This means that the Elastic Beanstalk-defined environment properties are not accessible, and you must define your own environment properties to pass the connection information to Symfony.

To connect to a database with Symfony 2, [create an environment property](create_deploy_PHP.container.md#php-console-properties) for each parameter. Then, use `%property.name%` to access the Symfony-transformed variable in a configuration file. For example, an environment property named `SYMFONY__DATABASE__USER` is accessible as `database.user`.

```
    database_user:     "%database.user%"
```

See [External Parameters (Symfony 2.8)](http://symfony.com/doc/2.8/configuration/external_parameters.html) for more information.

# Deploying a Laravel application to Elastic Beanstalk
<a name="php-laravel-tutorial"></a>

Laravel is an open source, model-view-controller (MVC) framework for PHP. This tutorial walks you through the process of generating a Laravel application, deploying it to an AWS Elastic Beanstalk environment, and configuring it to connect to an Amazon Relational Database Service (Amazon RDS) database instance.

**Topics**
+ [Prerequisites](#php-laravel-tutorial-prereqs)
+ [Launch an Elastic Beanstalk environment](#php-laravel-tutorial-launch)
+ [Install Laravel and generate a website](#php-laravel-tutorial-generate)
+ [Deploy your application](#php-laravel-tutorial-deploy)
+ [Configure Composer settings](#php-laravel-tutorial-configure)
+ [Add a database to your environment](#php-laravel-tutorial-database)
+ [Cleanup](#php-laravel-tutorial-cleanup)
+ [Next steps](#php-laravel-tutorial-nextsteps)

## Prerequisites
<a name="php-laravel-tutorial-prereqs"></a>

This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic Beanstalk console. If you haven't already, follow the instructions in [Learn how to get started with Elastic Beanstalk](GettingStarted.md) to launch your first Elastic Beanstalk environment.

To follow the procedures in this guide, you will need a command line terminal or shell to run commands. Commands are shown in listings preceded by a prompt symbol (\$1) and the name of the current directory, when appropriate.

```
~/eb-project$ this is a command
this is output
```

On Linux and macOS, you can use your preferred shell and package manager. On Windows you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.

Laravel 6 requires PHP 7.2 or later. It also requires the PHP extensions listed in the [server requirements](https://laravel.com/docs/6.x/installation#server-requirements) topic in the official Laravel documentation. Follow the instructions to install PHP and Composer.

For Laravel support and maintenance information, see the [support policy](https://laravel.com/docs/master/releases#support-policy) topic on the official Laravel documentation.

## Launch an Elastic Beanstalk environment
<a name="php-laravel-tutorial-launch"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. Choose the **PHP** platform and accept the default settings and sample code.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about 5 minutes and creates the following resources:
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **CloudFormation stack** – Elastic Beanstalk uses CloudFormation to launch the resources in your environment and propagate configuration changes. The resources are defined in a template that you can view in the [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+ **Domain name** – A domain name that routes to your web app in the form **subdomain*.*region*.elasticbeanstalk.com*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Install Laravel and generate a website
<a name="php-laravel-tutorial-generate"></a>

Composer can install Laravel and create a working project with one command:

```
~$ composer create-project --prefer-dist laravel/laravel eb-laravel
```

Composer installs Laravel and its dependencies, and generates a default project.

If you run into any issues installing Laravel, go to the installation topic in the official documentation: [https://laravel.com/docs/6.x](https://laravel.com/docs/6.x). 

## Deploy your application
<a name="php-laravel-tutorial-deploy"></a>

Create a [source bundle](applications-sourcebundle.md) containing the files created by Composer. The following command creates a source bundle named `laravel-default.zip`. It excludes files in the `vendor` folder, which take up a lot of space and are not necessary for deploying your application to Elastic Beanstalk.

```
~/eb-laravel$ zip ../laravel-default.zip -r * .[^.]* -x "vendor/*"
```

Upload the source bundle to Elastic Beanstalk to deploy Laravel to your environment.

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

**Note**  
To optimize the source bundle further, initialize a Git repository and use the [`git archive` command](applications-sourcebundle.md#using-features.deployment.source.git) to create the source bundle. The default Laravel project includes a `.gitignore` file that tells Git to exclude the `vendor` folder and other files that are not required for deployment.

## Configure Composer settings
<a name="php-laravel-tutorial-configure"></a>

When the deployment completes, click the URL to open your Laravel application in the browser:

![\[Error message indicating no permission to access or on this server.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/php-laravel-403.png)


What's this? By default, Elastic Beanstalk serves the root of your project at the root path of the website. In this case, though, the default page (`index.php`) is one level down in the `public` folder. You can verify this by adding `/public` to the URL. For example, `http://laravel.us-east-2.elasticbeanstalk.com/public`.

To serve the Laravel application at the root path, use the Elastic Beanstalk console to configure the *document root* for the website.

**To configure your website's document root**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

1. For **Document Root**, enter **/public**.

1. To save the changes choose **Apply** at the bottom of the page.

1. When the update is complete, click the URL to reopen your site in the browser.

![\[Laravel logo with navigation menu items: Documentation, Laracasts, News, Forge, GitHub.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/php-laravel-defaultnodb.png)


So far, so good. Next you'll add a database to your environment and configure Laravel to connect to it.

## Add a database to your environment
<a name="php-laravel-tutorial-database"></a>

Launch an RDS DB instance in your Elastic Beanstalk environment. You can use MySQL, SQLServer, or PostgreSQL databases with Laravel on Elastic Beanstalk. For this example, we'll use MySQL.

**To add an RDS DB instance to your Elastic Beanstalk environment**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Database** configuration category, choose **Edit**.

1. For **Engine**, choose **mysql**.

1. Type a master **username** and **password**. Elastic Beanstalk will provide these values to your application using environment properties.

1. To save the changes choose **Apply** at the bottom of the page.

Creating a database instance takes about 10 minutes. For more information about databases coupled to an Elastic Beanstalk environment, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

In the meantime, you can update your source code to read connection information from the environment. Elastic Beanstalk provides connection details using environment variables, such as `RDS_HOSTNAME`, that you can access from your application.

Laravel's database configuration is stored in a file named `database.php` in the `config` folder in your project code. Find the `mysql` entry and modify the `host`, `database`, `username`, `and password` variables to read the corresponding values from Elastic Beanstalk:

**Example \$1/Eb-laravel/config/database.php**  

```
...
    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('RDS_HOSTNAME', '127.0.0.1'),
            'port' => env('RDS_PORT', '3306'),
            'database' => env('RDS_DB_NAME', 'forge'),
            'username' => env('RDS_USERNAME', 'forge'),
            'password' => env('RDS_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
...
```

To verify that the database connection is configured correctly, add code to `index.php` to connect to the database and add some code to the default response:

**Example \$1/Eb-laravel/public/index.php**  

```
...
if(DB::connection()->getDatabaseName())
{
   echo "Connected to database ".DB::connection()->getDatabaseName();
}
$response->send();
...
```

When the DB instance has finished launching, bundle and deploy the updated application to your environment.

**To update your Elastic Beanstalk environment**

1. Create a new source bundle:

   ```
   ~/eb-laravel$ zip ../laravel-v2-rds.zip -r * .[^.]* -x "vendor/*"
   ```

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Upload and Deploy**.

1. Choose **Browse**, and upload `laravel-v2-rds.zip`.

1. Choose **Deploy**.

Deploying a new version of your application takes less than a minute. When the deployment is complete, refresh the web page again to verify that the database connection succeeded:

![\[Laravel website header with navigation menu items for Documentation, Laracasts, News, Forge, and GitHub.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/php-laravel-defaultwdb.png)


## Cleanup
<a name="php-laravel-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

In addition, you can terminate database resources that you created outside of your Elastic Beanstalk environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the data to another instance later.

**To terminate your RDS DB instance**

1. Open the [Amazon RDS console](https://console.aws.amazon.com/rds).

1. Choose **Databases**.

1. Choose your DB instance.

1. Choose **Actions**, and then choose **Delete**.

1. Choose whether to create a snapshot, and then choose **Delete**.

## Next steps
<a name="php-laravel-tutorial-nextsteps"></a>

For more information about Laravel, go to the Laravel official website at [laravel.com](https://laravel.com/).

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

In this tutorial, you used the Elastic Beanstalk console to configure composer options. To make this configuration part of your application source, you can use a configuration file like the following.

**Example .ebextensions/composer.config**  

```
option_settings:
  aws:elasticbeanstalk:container:php:phpini:
    document_root: /public
```

For more information, see [Advanced environment customization with configuration files (`.ebextensions`)](ebextensions.md).

Running an Amazon RDS DB instance in your Elastic Beanstalk environment is great for development and testing, but it ties the lifecycle of your database to your environment. See [Adding an Amazon RDS DB instance to your PHP Elastic Beanstalk environment](create_deploy_PHP.rds.md) for instructions on connecting to a database running outside of your environment.

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.

# Deploying a CakePHP application to Elastic Beanstalk
<a name="php-cakephp-tutorial"></a>

CakePHP is an open source, MVC framework for PHP. This tutorial walks you through the process of generating a CakePHP project, deploying it to an Elastic Beanstalk environment, and configuring it to connect to an Amazon RDS database instance.

**Topics**
+ [Prerequisites](#php-cakephp-tutorial-prereqs)
+ [Launch an Elastic Beanstalk environment](#php-cakephp-tutorial-launch)
+ [Install CakePHP and generate a website](#php-cakephp-tutorial-generate)
+ [Deploy your application](#php-cakephp-tutorial-deploy)
+ [Add a database to your environment](#php-cakephp-tutorial-database)
+ [Cleanup](#php-cakephp-tutorial-cleanup)
+ [Next steps](#php-cakephp-tutorial-nextsteps)

## Prerequisites
<a name="php-cakephp-tutorial-prereqs"></a>

This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic Beanstalk console. If you haven't already, follow the instructions in [Learn how to get started with Elastic Beanstalk](GettingStarted.md) to launch your first Elastic Beanstalk environment.

To follow the procedures in this guide, you will need a command line terminal or shell to run commands. Commands are shown in listings preceded by a prompt symbol (\$1) and the name of the current directory, when appropriate.

```
~/eb-project$ this is a command
this is output
```

On Linux and macOS, you can use your preferred shell and package manager. On Windows you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.

CakePHP 4 requires PHP 7.4 or later. It also requires the PHP extensions listed in the official [CakePHP installation](https://book.cakephp.org/4/en/installation.html) documentation. You must install both PHP and Composer.

## Launch an Elastic Beanstalk environment
<a name="php-cakephp-tutorial-launch"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. Choose the **PHP** platform and accept the default settings and sample code.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about 5 minutes and creates the following resources:
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **CloudFormation stack** – Elastic Beanstalk uses CloudFormation to launch the resources in your environment and propagate configuration changes. The resources are defined in a template that you can view in the [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+ **Domain name** – A domain name that routes to your web app in the form **subdomain*.*region*.elasticbeanstalk.com*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Install CakePHP and generate a website
<a name="php-cakephp-tutorial-generate"></a>

Composer can install CakePHP and create a working project with one command:

```
~$ composer create-project --prefer-dist cakephp/app eb-cake
```

Composer installs CakePHP and around 20 dependencies, and generates a default project.

If you run into any issues installing CakePHP, visit the installation topic in the official documentation: [http://book.cakephp.org/4.0/en/installation.html](http://book.cakephp.org/4.0/en/installation.html)

## Deploy your application
<a name="php-cakephp-tutorial-deploy"></a>

Create a [source bundle](applications-sourcebundle.md) containing the files created by Composer. The following command creates a source bundle named `cake-default.zip`. It excludes files in the `vendor` folder, which take up a lot of space and are not necessary for deploying your application to Elastic Beanstalk.

```
eb-cake zip ../cake-default.zip -r * .[^.]* -x "vendor/*"
```

Upload the source bundle to Elastic Beanstalk to deploy CakePHP to your environment.

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

**Note**  
To optimize the source bundle further, initialize a Git repository and use the [`git archive` command](applications-sourcebundle.md#using-features.deployment.source.git) to create the source bundle. The default Symfony project includes a `.gitignore` file that tells Git to exclude the `vendor` folder and other files that are not required for deployment.

When the process completes, click the URL to open your CakePHP application in the browser.

So far, so good. Next you'll add a database to your environment and configure CakePHP to connect to it.

## Add a database to your environment
<a name="php-cakephp-tutorial-database"></a>

Launch an Amazon RDS database instance in your Elastic Beanstalk environment. You can use MySQL, SQLServer, or PostgreSQL databases with CakePHP on Elastic Beanstalk. For this example, we'll use PostgreSQL.

**To add an Amazon RDS DB instance to your Elastic Beanstalk environment**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. Under **Database**, choose **Edit**.

1. For **DB engine**, choose **postgres**.

1. Type a master **username** and **password**. Elastic Beanstalk will provide these values to your application using environment properties.

1. To save the changes choose **Apply** at the bottom of the page.

Creating a database instance takes about 10 minutes. In the meantime, you can update your source code to read connection information from the environment. Elastic Beanstalk provides connection details using environment variables such as `RDS_HOSTNAME` that you can access from your application.

CakePHP's database configuration is in a file named `app.php` in the `config` folder in your project code. Open this file and add some code that reads the environment variables from `$_SERVER` and assigns them to local variables. Insert the highlighted lines in the below example after the first line (`<?php`):

**Example \$1/Eb-cake/config/app.php**  

```
<?php
if (!defined('RDS_HOSTNAME')) {
  define('RDS_HOSTNAME', $_SERVER['RDS_HOSTNAME']);
  define('RDS_USERNAME', $_SERVER['RDS_USERNAME']);
  define('RDS_PASSWORD', $_SERVER['RDS_PASSWORD']);
  define('RDS_DB_NAME', $_SERVER['RDS_DB_NAME']);
}
return [
...
```

The database connection is configured further down in `app.php`. Find the following section and modify the default datasources configuration with the name of the driver that matches your database engine (`Mysql`, `Sqlserver`, or `Postgres`), and set the `host`, `username`, `password` and `database` variables to read the corresponding values from Elastic Beanstalk:

**Example \$1/Eb-cake/config/app.php**  

```
...
     /**
     * Connection information used by the ORM to connect
     * to your application's datastores.
     * Drivers include Mysql Postgres Sqlite Sqlserver
     * See vendor\cakephp\cakephp\src\Database\Driver for complete list
     */
    'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Postgres',
            'persistent' => false,
            'host' => RDS_HOSTNAME,
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',
            'username' => RDS_USERNAME,
            'password' => RDS_PASSWORD,
            'database' => RDS_DB_NAME,
            /*
             * You do not need to set this flag to use full utf-8 encoding (internal default since CakePHP 3.6).
             */
            //'encoding' => 'utf8mb4',
            'timezone' => 'UTC',
            'flags' => [],
            'cacheMetadata' => true,
            'log' => false,
...
```

When the DB instance has finished launching, bundle up and deploy the updated application to your environment:

**To update your Elastic Beanstalk environment**

1. Create a new source bundle:

   ```
   ~/eb-cake$ zip ../cake-v2-rds.zip -r * .[^.]* -x "vendor/*"
   ```

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Upload and Deploy**.

1. Choose **Browse** and upload `cake-v2-rds.zip`.

1. Choose **Deploy**.

Deploying a new version of your application takes less than a minute. When the deployment is complete, refresh the web page again to verify that the database connection succeeded:

![\[Green checkmark icon indicating successful database connection for CakePHP.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/php-cakephp-defaultwdb.png)


## Cleanup
<a name="php-cakephp-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

In addition, you can terminate database resources that you created outside of your Elastic Beanstalk environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the data to another instance later.

**To terminate your RDS DB instance**

1. Open the [Amazon RDS console](https://console.aws.amazon.com/rds).

1. Choose **Databases**.

1. Choose your DB instance.

1. Choose **Actions**, and then choose **Delete**.

1. Choose whether to create a snapshot, and then choose **Delete**.

## Next steps
<a name="php-cakephp-tutorial-nextsteps"></a>

For more information about CakePHP, read the book at [book.cakephp.org](http://book.cakephp.org/4.0/en/index.html).

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

Running an Amazon RDS DB instance in your Elastic Beanstalk environment is great for development and testing, but it ties the lifecycle of your database to your environment. See [Adding an Amazon RDS DB instance to your PHP Elastic Beanstalk environment](create_deploy_PHP.rds.md) for instructions on connecting to a database running outside of your environment.

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.

# Deploying a Symfony application to Elastic Beanstalk
<a name="php-symfony-tutorial"></a>

[Symfony](http://symfony.com/) is an open-source framework for developing dynamic PHP web applications. This tutorial walks you through the process of generating a Symfony application and deploying it to an AWS Elastic Beanstalk environment.

**Topics**
+ [Prerequisites](#php-symfony-tutorial-prereqs)
+ [Launch an Elastic Beanstalk environment](#php-symfony-tutorial-launch)
+ [Install Symfony and generate a website](#php-symfony-tutorial-generate)
+ [Deploy your application](#php-symfony-tutorial-deploy)
+ [Configure Composer settings](#php-symfony-tutorial-configure)
+ [Cleanup](#php-symfony-tutorial-cleanup)
+ [Next steps](#php-symfony-tutorial-nextsteps)

## Prerequisites
<a name="php-symfony-tutorial-prereqs"></a>

This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic Beanstalk console. If you haven't already, follow the instructions in [Learn how to get started with Elastic Beanstalk](GettingStarted.md) to launch your first Elastic Beanstalk environment.

To follow the procedures in this guide, you will need a command line terminal or shell to run commands. Commands are shown in listings preceded by a prompt symbol (\$1) and the name of the current directory, when appropriate.

```
~/eb-project$ this is a command
this is output
```

On Linux and macOS, you can use your preferred shell and package manager. On Windows you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.

Symfony 4.4.9 requires PHP 7.1.3 or later. It also requires the PHP extensions listed in the [technical requirements](https://symfony.com/doc/4.4/setup.html ) topic in the official Symfony installation documentation. In this tutorial, we use PHP 7.2 and the corresponding Elastic Beanstalk [platform version](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.PHP). Before you proceed, you must install both PHP and Composer.

For Symfony support and maintenance information, see the [symfony releases](https://symfony.com/releases) topic on the Symfony website. For more information about updates related to PHP version support for Symfony 4.4.9, see the [Symfony 4.4.9 release notes](https://symfony.com/blog/symfony-4-4-9-released) topic on the Symfony website.

## Launch an Elastic Beanstalk environment
<a name="php-symfony-tutorial-launch"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. Choose the **PHP** platform and accept the default settings and sample code.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about 5 minutes and creates the following resources:
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **CloudFormation stack** – Elastic Beanstalk uses CloudFormation to launch the resources in your environment and propagate configuration changes. The resources are defined in a template that you can view in the [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+ **Domain name** – A domain name that routes to your web app in the form **subdomain*.*region*.elasticbeanstalk.com*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Install Symfony and generate a website
<a name="php-symfony-tutorial-generate"></a>

Composer can install Symfony and create a working project with one command:

```
~$ composer create-project symfony/website-skeleton eb-symfony
```

Composer installs Symfony and its dependencies, and generates a default project.

If you run into any issues installing Symfony, go to the [installation](https://symfony.com/doc/4.4/setup.html) topic in the official Symfony documentation.

## Deploy your application
<a name="php-symfony-tutorial-deploy"></a>

Go to the project directory.

```
~$ cd eb-symfony
```

Create a [source bundle](applications-sourcebundle.md) containing the files created by Composer. The following command creates a source bundle named `symfony-default.zip`. It excludes files in the `vendor` folder, which take up a lot of space and are not necessary for deploying your application to Elastic Beanstalk.

```
eb-symfony$ zip ../symfony-default.zip -r * .[^.]* -x "vendor/*"
```

Upload the source bundle to Elastic Beanstalk to deploy Symfony to your environment.

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

**Note**  
To optimize the source bundle further, initialize a Git repository and use the [`git archive` command](applications-sourcebundle.md#using-features.deployment.source.git) to create the source bundle. The default Symfony project includes a `.gitignore` file that tells Git to exclude the `vendor` folder and other files that are not required for deployment.

## Configure Composer settings
<a name="php-symfony-tutorial-configure"></a>

When the deployment completes, click the URL to open your Symfony application in the browser.

What's this? By default, Elastic Beanstalk serves the root of your project at the root path of the web site. In this case, though, the default page (`app.php`) is one level down in the `web` folder. You can verify this by adding `/public` to the URL. For example, `http://symfony.us-east-2.elasticbeanstalk.com/public`.

To serve the Symfony application at the root path, use the Elastic Beanstalk console to configure the *document root* for the web site.

**To configure your web site's document root**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

1. For **Document root**, enter **/public**.

1. To save the changes choose **Apply** at the bottom of the page.

1. When the update is complete, click the URL to reopen your site in the browser.

## Cleanup
<a name="php-symfony-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

## Next steps
<a name="php-symfony-tutorial-nextsteps"></a>

For more information about Symfony, see [What is Symfony?](https://symfony.com/what-is-symfony) at symfony.com.

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

In this tutorial, you used the Elastic Beanstalk console to configure composer options. To make this configuration part of your application source, you can use a configuration file like the following.

**Example .ebextensions/composer.config**  

```
option_settings:
  aws:elasticbeanstalk:container:php:phpini:
    document_root: /public
```

For more information, see [Advanced environment customization with configuration files (`.ebextensions`)](ebextensions.md).

Symfony uses its own configuration files to configure database connections. For instructions on connecting to a database with Symfony, see [Connecting to a database with Symfony](create_deploy_PHP.rds.md#php-rds-symfony).

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.

# Deploying a high-availability PHP application with an external Amazon RDS database to Elastic Beanstalk
<a name="php-ha-tutorial"></a>

This tutorial walks you through the process of [launching an RDS DB instance](AWSHowTo.RDS.md) external to AWS Elastic Beanstalk, and configuring a high-availability environment running a PHP application to connect to it. Running a DB instance external to Elastic Beanstalk decouples the database from the lifecycle of your environment. This lets you connect to the same database from multiple environments, swap out one database for another, or perform a blue/green deployment without affecting your database.

The tutorial uses a [sample PHP application](https://github.com/awslabs/eb-demo-php-simple-app) that uses a MySQL database to store user-provided text data. The sample application uses [configuration files](ebextensions.md) to configure [PHP settings](create_deploy_PHP.container.md#php-namespaces) and to create a table in the database for the application to use. It also shows how to use a [Composer file](create_deploy_PHP.container.md#php-configuration-composer) to install packages during deployment.

**Topics**
+ [Prerequisites](#php-hawrds-tutorial-prereqs)
+ [Launch a DB instance in Amazon RDS](#php-hawrds-tutorial-database)
+ [Create an Elastic Beanstalk environment](#php-hawrds-tutorial-create)
+ [Configure security groups, environment properties, and scaling](#php-hawrds-tutorial-configure)
+ [Deploy the sample application](#php-hawrds-tutorial-deploy)
+ [Cleanup](#php-hawrds-tutorial-cleanup)
+ [Next steps](#php-hawrds-tutorial-nextsteps)

## Prerequisites
<a name="php-hawrds-tutorial-prereqs"></a>

Before you start, download the sample application source bundle from GitHub: [eb-demo-php-simple-app-1.3.zip](https://github.com/aws-samples/eb-demo-php-simple-app/releases/download/v1.3/eb-demo-php-simple-app-v1.3.zip)

The procedures in this tutorial for Amazon Relational Database Service (Amazon RDS) tasks assume that you are launching resources in a default [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC). All new accounts include a default VPC in each region. If you don't have a default VPC, the procedures will vary. See [Using Elastic Beanstalk with Amazon RDS](AWSHowTo.RDS.md) for instructions for EC2-Classic and custom VPC platforms.

## Launch a DB instance in Amazon RDS
<a name="php-hawrds-tutorial-database"></a>

To use an external database with an application running in Elastic Beanstalk, first launch a DB instance with Amazon RDS. When you launch an instance with Amazon RDS, it is completely independent of Elastic Beanstalk and your Elastic Beanstalk environments, and will not be terminated or monitored by Elastic Beanstalk.

Use the Amazon RDS console to launch a Multi-AZ **MySQL** DB instance. Choosing a Multi-AZ deployment ensures that your database will fail over and continue to be available if the source DB instance goes out of service.

**To launch an RDS DB instance in a default VPC**

1. Open the [RDS console](https://console.aws.amazon.com/rds/home).

1. In the navigation pane, choose **Databases**.

1. Choose **Create database**.

1. Choose **Standard Create**.
**Important**  
Do not choose **Easy Create**. If you choose it, you can't configure the necessary settings to launch this RDS DB.

1. Under **Additional configuration**, for **Initial database name**, type **ebdb**. 

1. Review the default settings and adjust these settings according to your specific requirements. Pay attention to the following options:
   + **DB instance class** – Choose an instance size that has an appropriate amount of memory and CPU power for your workload.
   + **Multi-AZ deployment** – For high availability, set this to **Create an Aurora Replica/Reader node in a different AZ**.
   + **Master username** and **Master password** – The database username and password. Make a note of these settings because you will use them later.

1. Verify the default settings for the remaining options, and then choose **Create database**.

Next, modify the security group attached to your DB instance to allow inbound traffic on the appropriate port. This is the same security group that you will attach to your Elastic Beanstalk environment later, so the rule that you add will grant ingress permission to other resources in the same security group.

**To modify the inbound rules on the security group that's attached to your RDS instance**

1. Open the [ Amazon RDS console](https://console.aws.amazon.com/rds/home).

1. Choose **Databases**.

1. Choose the name of your DB instance to view its details.

1. In the **Connectivity** section, make a note of the **Subnets**, **Security groups**, and **Endpoint** that are displayed on this page. This is so you can use this information later.

1. Under **Security**, you can see the security group that's associated with the DB instance. Open the link to view the security group in the Amazon EC2 console.

1. In the security group details, choose **Inbound**.

1. Choose **Edit**.

1. Choose **Add Rule**.

1. For **Type**, choose the DB engine that your application uses.

1. For **Source**, type **sg-** to view a list of available security groups. Choose the security group that's associated with the Auto Scaling group that's used with your Elastic Beanstalk environment. This is so that Amazon EC2 instances in the environment can have access to the database.  
![\[Screen image to edit the inbound rules for a security group in the Amazon EC2 console.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/ec2-securitygroup-rds.png)

1. Choose **Save**.

Creating a DB instance takes about 10 minutes. In the meantime, create your Elastic Beanstalk environment.

## Create an Elastic Beanstalk environment
<a name="php-hawrds-tutorial-create"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. Choose the **PHP** platform and accept the default settings and sample code. After you launch the environment, you can configure the environment to connect to the database, then deploy the sample application that you downloaded from GitHub.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about 5 minutes and creates the following resources:
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **CloudFormation stack** – Elastic Beanstalk uses CloudFormation to launch the resources in your environment and propagate configuration changes. The resources are defined in a template that you can view in the [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+ **Domain name** – A domain name that routes to your web app in the form **subdomain*.*region*.elasticbeanstalk.com*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains. The RDS DB instance that you launched is outside of your environment, so you are responsible for managing its lifecycle.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Configure security groups, environment properties, and scaling
<a name="php-hawrds-tutorial-configure"></a>

Add the security group of your DB instance to your running environment. This procedure causes Elastic Beanstalk to reprovision all instances in your environment with the additional security group attached.

**To add a security group to your environment**
+ Do one of the following:
  + To add a security group using the Elastic Beanstalk console

    1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

    1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

    1. In the navigation pane, choose **Configuration**.

    1. In the **Instances** configuration category, choose **Edit**.

    1. Under **EC2 security groups**, choose the security group to attach to the instances, in addition to the instance security group that Elastic Beanstalk creates.

    1. To save the changes choose **Apply** at the bottom of the page.

    1. Read the warning, and then choose **Confirm**.
  + To add a security group using a [configuration file](ebextensions.md), use the [https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/security-configuration/securitygroup-addexisting.config](https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/security-configuration/securitygroup-addexisting.config) example file.

Next, use environment properties to pass the connection information to your environment. The sample application uses a default set of properties that match the ones that Elastic Beanstalk configures when you provision a database within your environment.

**To configure environment properties for an Amazon RDS DB instance**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

1. In the **Environment properties** section, define the variables that your application reads to construct a connection string. For compatibility with environments that have an integrated RDS DB instance, use the following names and values. You can find all values, except for your password, in the [RDS console](https://console.aws.amazon.com/rds/home).    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/php-ha-tutorial.html)  
![\[Environment properties configuration section with RDS properties added\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/environment-cfg-envprops-rds.png)

1. To save the changes choose **Apply** at the bottom of the page.

Finally, configure your environment's Auto Scaling group with a higher minimum instance count. Run at least two instances at all times to prevent the web servers in your environment from being a single point of failure, and to allow you to deploy changes without taking your site out of service.

**To configure your environment's Auto Scaling group for high availability**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Capacity** configuration category, choose **Edit**.

1. In the **Auto Scaling group** section, set **Min instances** to **2**.

1. To save the changes choose **Apply** at the bottom of the page.

## Deploy the sample application
<a name="php-hawrds-tutorial-deploy"></a>

Now your environment is ready to run the sample application and connect to Amazon RDS. Deploy the sample application to your environment.

**Note**  
Download the source bundle from GitHub, if you haven't already: [eb-demo-php-simple-app-1.3.zip](https://github.com/aws-samples/eb-demo-php-simple-app/releases/download/v1.3/eb-demo-php-simple-app-v1.3.zip)

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

The site collects user comments and uses a MySQL database to store the data. To add a comment, choose **Share Your Thought**, enter a comment, and then choose **Submit Your Thought**. The web app writes the comment to the database so that any instance in the environment can read it, and it won't be lost if instances go out of service.

![\[User interface for sharing thoughts, with a posted comment about Elastic Beanstalk on AWS.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/php-ha-tutorial-app.png)


## Cleanup
<a name="php-hawrds-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

In addition, you can terminate database resources that you created outside of your Elastic Beanstalk environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the data to another instance later.

**To terminate your RDS DB instance**

1. Open the [Amazon RDS console](https://console.aws.amazon.com/rds).

1. Choose **Databases**.

1. Choose your DB instance.

1. Choose **Actions**, and then choose **Delete**.

1. Choose whether to create a snapshot, and then choose **Delete**.

## Next steps
<a name="php-hawrds-tutorial-nextsteps"></a>

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

The sample application uses configuration files to configure PHP settings and create a table in the database if it doesn't already exist. You can also use a configuration file to configure the security group settings of your instances during environment creation to avoid time-consuming configuration updates. See [Advanced environment customization with configuration files (`.ebextensions`)](ebextensions.md) for more information.

For development and testing, you might want to use the Elastic Beanstalk functionality for adding a managed DB instance directly to your environment. For instructions on setting up a database inside your environment, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

If you need a high-performance database, consider using [Amazon Aurora](https://aws.amazon.com/rds/aurora/). Amazon Aurora is a MySQL-compatible database engine that offers commercial database features at low cost. To connect your application to a different database, repeat the [security group configuration](#php-hawrds-tutorial-database) steps and [update the RDS-related environment properties](#php-hawrds-tutorial-configure). 

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.

# Deploying a high-availability WordPress website with an external Amazon RDS database to Elastic Beanstalk
<a name="php-hawordpress-tutorial"></a>

This tutorial describes how to [launch an Amazon RDS DB instance](AWSHowTo.RDS.md) that is external to AWS Elastic Beanstalk, then how to configure a high-availability environment running a WordPress website to connect to it. The website uses Amazon Elastic File System (Amazon EFS) as the shared storage for uploaded files.

Running a DB instance external to Elastic Beanstalk decouples the database from the lifecycle of your environment. This lets you connect to the same database from multiple environments, swap out one database for another, or perform a [blue/green deployment](using-features.CNAMESwap.md) without affecting your database.

**Note**  
For current information about the compatibility of PHP releases with WordPress versions, see [PHP Compatibility and WordPress Versions](https://make.wordpress.org/core/handbook/references/php-compatibility-and-wordpress-versions/) on the WordPress website. You should refer to this information before you upgrade to a new release of PHP for your WordPress implementations.

**Topics**
+ [Prerequisites](#php-wordpress-tutorial-prereqs)
+ [Launch a DB instance in Amazon RDS](#php-hawordpress-tutorial-database)
+ [Download WordPress](#php-hawordpress-tutorial-download)
+ [Launch an Elastic Beanstalk environment](#php-hawordpress-tutorial-launch)
+ [Configure security groups and environment properties](#php-wordpress-tutorial-configure)
+ [Configure and deploy your application](#php-wordpress-tutorial-deploy)
+ [Install WordPress](#php-hawordpress-tutorial-install)
+ [Update keys and salts](#php-hawordpress-tutorial-updatesalts)
+ [Remove access restrictions](#php-hawordpress-tutorial-updateenv)
+ [Configure your Auto Scaling group](#php-hawordpress-tutorial-autoscaling)
+ [Upgrade WordPress](#php-hawordpress-tutorial-upgrade)
+ [Clean up](#php-hawordpress-tutorial-cleanup)
+ [Next steps](#php-hawordpress-tutorial-nextsteps)

## Prerequisites
<a name="php-wordpress-tutorial-prereqs"></a>

This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic Beanstalk console. If you haven't already, follow the instructions in [Learn how to get started with Elastic Beanstalk](GettingStarted.md) to launch your first Elastic Beanstalk environment.

To follow the procedures in this guide, you will need a command line terminal or shell to run commands. Commands are shown in listings preceded by a prompt symbol (\$1) and the name of the current directory, when appropriate.

```
~/eb-project$ this is a command
this is output
```

On Linux and macOS, you can use your preferred shell and package manager. On Windows you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.

**Default VPC**  
The Amazon Relational Database Service (Amazon RDS) procedures in this tutorial assume that you are launching resources in a default [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC). All new accounts include a default VPC in each AWS Region. If you don't have a default VPC, the procedures will vary. See [Using Elastic Beanstalk with Amazon RDS](AWSHowTo.RDS.md) for instructions for EC2-Classic and custom VPC platforms.

**AWS Regions**  
The sample application uses Amazon EFS, which only works in AWS Regions that support Amazon EFS. To learn about supported AWS Regions, see [Amazon Elastic File System Endpoints and Quotas](https://docs.aws.amazon.com/general/latest/gr/elasticfilesystem.html) in the *AWS General Reference*.

## Launch a DB instance in Amazon RDS
<a name="php-hawordpress-tutorial-database"></a>

When you launch an instance with Amazon RDS, it's completely independent of Elastic Beanstalk and your Elastic Beanstalk environments, and will not be terminated or monitored by Elastic Beanstalk.

In the following steps you'll use the Amazon RDS console to:
+ Launch a database with the **MySQL** engine.
+ Enable a **Multi-AZ deployment**. This creates a standby in a different Availability Zone (AZ) to provide data redundancy, eliminate I/O freezes, and minimize latency spikes during system backups.

**To launch an RDS DB instance in a default VPC**

1. Open the [RDS console](https://console.aws.amazon.com/rds/home).

1. In the navigation pane, choose **Databases**.

1. Choose **Create database**.

1. Choose **Standard Create**.
**Important**  
Do not choose **Easy Create**. If you choose it, you can't configure the necessary settings to launch this RDS DB.

1. Under **Additional configuration**, for **Initial database name**, type **ebdb**. 

1. Review the default settings and adjust these settings according to your specific requirements. Pay attention to the following options:
   + **DB instance class** – Choose an instance size that has an appropriate amount of memory and CPU power for your workload.
   + **Multi-AZ deployment** – For high availability, set this to **Create an Aurora Replica/Reader node in a different AZ**.
   + **Master username** and **Master password** – The database username and password. Make a note of these settings because you will use them later.

1. Verify the default settings for the remaining options, and then choose **Create database**.

After your DB instance is created, modify the security group attached to it in order to allow inbound traffic on the appropriate port..

**Note**  
This is the same security group that you'll attach to your Elastic Beanstalk environment later, so the rule that you add now will grant ingress permission to other resources in the same security group.

**To modify the inbound rules on the security group that's attached to your RDS instance**

1. Open the [ Amazon RDS console](https://console.aws.amazon.com/rds/home).

1. Choose **Databases**.

1. Choose the name of your DB instance to view its details.

1. In the **Connectivity** section, make a note of the **Subnets**, **Security groups**, and **Endpoint** that are displayed on this page. This is so you can use this information later.

1. Under **Security**, you can see the security group that's associated with the DB instance. Open the link to view the security group in the Amazon EC2 console.

1. In the security group details, choose **Inbound**.

1. Choose **Edit**.

1. Choose **Add Rule**.

1. For **Type**, choose the DB engine that your application uses.

1. For **Source**, type **sg-** to view a list of available security groups. Choose the security group that's associated with the Auto Scaling group that's used with your Elastic Beanstalk environment. This is so that Amazon EC2 instances in the environment can have access to the database.  
![\[Screen image to edit the inbound rules for a security group in the Amazon EC2 console.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/ec2-securitygroup-rds.png)

1. Choose **Save**.

Creating a DB instance takes about 10 minutes. In the meantime, download WordPress and create your Elastic Beanstalk environment.

## Download WordPress
<a name="php-hawordpress-tutorial-download"></a>

To prepare to deploy WordPress using AWS Elastic Beanstalk, you must copy the WordPress files to your computer and provide the correct configuration information.

**To create a WordPress project**

1. Download WordPress from [wordpress.org](https://wordpress.org/download/).

   ```
   ~$curl https://wordpress.org/wordpress-6.2.tar.gz -o wordpress.tar.gz
   ```

1. Download the configuration files from the sample repository.

   ```
   ~$ wget https://github.com/aws-samples/eb-php-wordpress/releases/download/v1.1/eb-php-wordpress-v1.zip
   ```

1. Extract WordPress and change the name of the folder.

   ```
    ~$ tar -xvf wordpress.tar.gz
    ~$ mv wordpress wordpress-beanstalk
    ~$ cd wordpress-beanstalk
   ```

1. Extract the configuration files over the WordPress installation.

   ```
    ~/wordpress-beanstalk$ unzip ../eb-php-wordpress-v1.zip
     creating: .ebextensions/
    inflating: .ebextensions/dev.config
    inflating: .ebextensions/efs-create.config
    inflating: .ebextensions/efs-mount.config
    inflating: .ebextensions/loadbalancer-sg.config
    inflating: .ebextensions/wordpress.config
    inflating: LICENSE
    inflating: README.md
    inflating: wp-config.php
   ```

## Launch an Elastic Beanstalk environment
<a name="php-hawordpress-tutorial-launch"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. After you launch the environment, you can configure it to connect to the database, then deploy the WordPress code to the environment.

In the following steps, you'll use the Elastic Beanstalk console to:
+ Create an Elastic Beanstalk application using the managed **PHP** platform.
+ Accept the default settings and sample code.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about five minutes and creates the following resources. 

### Elastic Beanstalk created resources
<a name="php-hawordpress-tutorial-launch.EB-resources"></a>
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **CloudFormation stack** – Elastic Beanstalk uses CloudFormation to launch the resources in your environment and propagate configuration changes. The resources are defined in a template that you can view in the [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+ **Domain name** – A domain name that routes to your web app in the form **subdomain*.*region*.elasticbeanstalk.com*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains.

Because the Amazon RDS instance that you launched is outside of your environment, you are responsible for managing its lifecycle.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Configure security groups and environment properties
<a name="php-wordpress-tutorial-configure"></a>

Add the security group of your DB instance to your running environment. This procedure causes Elastic Beanstalk to reprovision all instances in your environment with the additional security group attached.

**To add a security group to your environment**
+ Do one of the following:
  + To add a security group using the Elastic Beanstalk console

    1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

    1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

    1. In the navigation pane, choose **Configuration**.

    1. In the **Instances** configuration category, choose **Edit**.

    1. Under **EC2 security groups**, choose the security group to attach to the instances, in addition to the instance security group that Elastic Beanstalk creates.

    1. To save the changes choose **Apply** at the bottom of the page.

    1. Read the warning, and then choose **Confirm**.
  + To add a security group using a [configuration file](ebextensions.md), use the [https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/security-configuration/securitygroup-addexisting.config](https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/security-configuration/securitygroup-addexisting.config) example file.

Next, use environment properties to pass the connection information to your environment.

The WordPress application uses a default set of properties that match the ones that Elastic Beanstalk configures when you provision a database within your environment.

**To configure environment properties for an Amazon RDS DB instance**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

1. In the **Environment properties** section, define the variables that your application reads to construct a connection string. For compatibility with environments that have an integrated RDS DB instance, use the following names and values. You can find all values, except for your password, in the [RDS console](https://console.aws.amazon.com/rds/home).    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/php-hawordpress-tutorial.html)  
![\[Environment properties configuration section with RDS properties added\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/environment-cfg-envprops-rds.png)

1. To save the changes choose **Apply** at the bottom of the page.

## Configure and deploy your application
<a name="php-wordpress-tutorial-deploy"></a>

Verify that the structure of your `wordpress-beanstalk` folder is correct, as shown.

```
wordpress-beanstalk$ tree -aL 1
.
├── .ebextensions
├── index.php
├── LICENSE
├── license.txt
├── readme.html
├── README.md
├── wp-activate.php
├── wp-admin
├── wp-blog-header.php
├── wp-comments-post.php
├── wp-config.php
├── wp-config-sample.php
├── wp-content
├── wp-cron.php
├── wp-includes
├── wp-links-opml.php
├── wp-load.php
├── wp-login.php
├── wp-mail.php
├── wp-settings.php
├── wp-signup.php
├── wp-trackback.php
└── xmlrpc.php
```

The customized `wp-config.php` file from the project repo uses the environment variables that you defined in the previous step to configure the database connection. The `.ebextensions` folder contains configuration files that create additional resources within your Elastic Beanstalk environment.

The configuration files require modification to work with your account. Replace the placeholder values in the files with the appropriate IDs and create a source bundle.

**To update configuration files and create a source bundle**

1. Modify the configuration files as follows.
   + `.ebextensions/dev.config` – Restricts access to your environment to protect it during the WordPress installation process. Replace the placeholder IP address near the top of the file with the public IP address of the computer you'll use to access your environment's website to complete your WordPress installation. 
**Note**  
Depending on your network, you might need to use an IP address block.
   + `.ebextensions/efs-create.config` – Creates an EFS file system and mount points in each Availability Zone/subnet in your VPC. Identify your default VPC and subnet IDs in the [Amazon VPC console](https://console.aws.amazon.com/vpc/home#subnets:filter=default).

1. Create a [source bundle](applications-sourcebundle.md) containing the files in your project folder. The following command creates a source bundle named `wordpress-beanstalk.zip`.

   ```
   ~/eb-wordpress$ zip ../wordpress-beanstalk.zip -r * .[^.]*
   ```

Upload the source bundle to Elastic Beanstalk to deploy WordPress to your environment.

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

## Install WordPress
<a name="php-hawordpress-tutorial-install"></a>

**To complete your WordPress installation**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose the environment URL to open your site in a browser. You are redirected to a WordPress installation wizard because you haven't configured the site yet.

1. Perform a standard installation. The `wp-config.php` file is already present in the source code and configured to read the database connection information from the environment. You shouldn't be prompted to configure the connection.

Installation takes about a minute to complete.

## Update keys and salts
<a name="php-hawordpress-tutorial-updatesalts"></a>

The WordPress configuration file `wp-config.php` also reads values for keys and salts from environment properties. Currently, these properties are all set to `test` by the `wordpress.config` file in the `.ebextensions` folder.

The hash salt can be any value that meets the [environment property requirements](environments-cfg-softwaresettings.md#environments-cfg-softwaresettings-console), but you should not store it in source control. Use the Elastic Beanstalk console to set these properties directly on the environment.

**To update environment properties**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the navigation pane, choose **Configuration**.

1. Under **Software**, choose **Edit**.

1. For `Environment properties`, modify the following properties:
   + `AUTH_KEY` – The value chosen for `AUTH_KEY`.
   + `SECURE_AUTH_KEY` – The value chosen for `SECURE_AUTH_KEY`.
   + `LOGGED_IN_KEY` – The value chosen for `LOGGED_IN_KEY`.
   + `NONCE_KEY` – The value chosen for `NONCE_KEY`.
   + `AUTH_SALT` – The value chosen for `AUTH_SALT`.
   + `SECURE_AUTH_SALT` – The value chosen for `SECURE_AUTH_SALT`.
   + `LOGGED_IN_SALT` – The value chosen for `LOGGED_IN_SALT`.
   + `NONCE_SALT` — The value chosen for `NONCE_SALT`.

1. To save the changes choose **Apply** at the bottom of the page.

**Note**  
Setting the properties on the environment directly overrides the values in `wordpress.config`.

## Remove access restrictions
<a name="php-hawordpress-tutorial-updateenv"></a>

The sample project includes the configuration file `loadbalancer-sg.config`. It creates a security group and assigns it to the environment's load balancer, using the IP address that you configured in `dev.config`. It restricts HTTP access on port 80 to connections from your network. Otherwise, an outside party could potentially connect to your site before you have installed WordPress and configured your admin account.

Now that you've installed WordPress, remove the configuration file to open the site to the world.

**To remove the restriction and update your environment**

1. Delete the `.ebextensions/loadbalancer-sg.config` file from your project directory.

   ```
   ~/wordpress-beanstalk$ rm .ebextensions/loadbalancer-sg.config
   ```

1. Create a source bundle.

   ```
   ~/eb-wordpress$ zip ../wordpress-beanstalk-v2.zip -r * .[^.]*
   ```

Upload the source bundle to Elastic Beanstalk to deploy WordPress to your environment.

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

## Configure your Auto Scaling group
<a name="php-hawordpress-tutorial-autoscaling"></a>

Finally, configure your environment's Auto Scaling group with a higher minimum instance count. Run at least two instances at all times to prevent the web servers in your environment from being a single point of failure. This also allows you to deploy changes without taking your site out of service.

**To configure your environment's Auto Scaling group for high availability**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Capacity** configuration category, choose **Edit**.

1. In the **Auto Scaling group** section, set **Min instances** to **2**.

1. To save the changes choose **Apply** at the bottom of the page.

To support content uploads across multiple instances, the sample project uses Amazon EFS to create a shared file system. Create a post on the site and upload content to store it on the shared file system. View the post and refresh the page multiple times to hit both instances and verify that the shared file system is working.

## Upgrade WordPress
<a name="php-hawordpress-tutorial-upgrade"></a>

To upgrade to a new version of WordPress, back up your site and deploy it to a new environment.

**Important**  
Do not use the update functionality within WordPress or update your source files to use a new version. Both of these actions can result in your post URLs returning 404 errors even though they are still in the database and file system.

**To upgrade WordPress**

1. In the WordPress admin console, use the export tool to export your posts to an XML file.

1. Deploy and install the new version of WordPress to Elastic Beanstalk with the same steps that you used to install the previous version. To avoid downtime, you can create an environment with the new version.

1. On the new version, install the WordPress Importer tool in the admin console and use it to import the XML file containing your posts. If the posts were created by the admin user on the old version, assign them to the admin user on the new site instead of trying to import the admin user.

1. If you deployed the new version to a separate environment, do a [CNAME swap](using-features.CNAMESwap.md) to redirect users from the old site to the new site.

## Clean up
<a name="php-hawordpress-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

In addition, you can terminate database resources that you created outside of your Elastic Beanstalk environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the data to another instance later.

**To terminate your RDS DB instance**

1. Open the [Amazon RDS console](https://console.aws.amazon.com/rds).

1. Choose **Databases**.

1. Choose your DB instance.

1. Choose **Actions**, and then choose **Delete**.

1. Choose whether to create a snapshot, and then choose **Delete**.

## Next steps
<a name="php-hawordpress-tutorial-nextsteps"></a>

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

The sample application uses configuration files to configure PHP settings and create a table in the database, if it doesn't already exist. You can also use a configuration file to configure the security group settings of your instances during environment creation to avoid time-consuming configuration updates. See [Advanced environment customization with configuration files (`.ebextensions`)](ebextensions.md) for more information.

For development and testing, you might want to use the Elastic Beanstalk functionality for adding a managed DB instance directly to your environment. For instructions on setting up a database inside your environment, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

If you need a high-performance database, consider using [Amazon Aurora](https://aws.amazon.com/rds/aurora/). Amazon Aurora is a MySQL-compatible database engine that offers commercial database features at low cost. To connect your application to a different database, repeat the [security group configuration](php-ha-tutorial.md#php-hawrds-tutorial-database) steps and [update the RDS-related environment properties](php-ha-tutorial.md#php-hawrds-tutorial-configure). 

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.

# Deploying a high-availability Drupal website with an external Amazon RDS database to Elastic Beanstalk
<a name="php-hadrupal-tutorial"></a>

This tutorial walks you through the process of [launching an RDS DB instance](AWSHowTo.RDS.md) external to AWS Elastic Beanstalk. Then it describes configuring a high-availability environment running a Drupal website to connect to it. The website uses Amazon Elastic File System (Amazon EFS) as shared storage for uploaded files. Running a DB instance external to Elastic Beanstalk decouples the database from the lifecycle of your environment, and lets you connect to the same database from multiple environments, swap out one database for another, or perform a blue/green deployment without affecting your database.

**Topics**
+ [Prerequisites](#php-hadrupal-tutorial-prereqs)
+ [Launch a DB instance in Amazon RDS](#php-hadrupal-tutorial-database)
+ [Launch an Elastic Beanstalk environment](#php-hadrupal-tutorial-launch)
+ [Configure security settings and environment properties](#php-hadrupal-tutorial-configure)
+ [Configure and deploy your application](#php-hadrupal-tutorial-deploy)
+ [Install Drupal](#php-hadrupal-tutorial-install)
+ [Update Drupal configuration and remove access restrictions](#php-hadrupal-tutorial-updateenv)
+ [Configure your Auto Scaling group](#php-hadrupal-tutorial-autoscaling)
+ [Cleanup](#php-hadrupal-tutorial-cleanup)
+ [Next steps](#php-hadrupal-tutorial-nextsteps)

## Prerequisites
<a name="php-hadrupal-tutorial-prereqs"></a>

This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic Beanstalk console. If you haven't already, follow the instructions in [Learn how to get started with Elastic Beanstalk](GettingStarted.md) to launch your first Elastic Beanstalk environment.

To follow the procedures in this guide, you will need a command line terminal or shell to run commands. Commands are shown in listings preceded by a prompt symbol (\$1) and the name of the current directory, when appropriate.

```
~/eb-project$ this is a command
this is output
```

On Linux and macOS, you can use your preferred shell and package manager. On Windows you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.

The procedures in this tutorial for Amazon Relational Database Service (Amazon RDS) tasks assume that you are launching resources in a default [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC). All new accounts include a default VPC in each region. If you don't have a default VPC, the procedures will vary. See [Using Elastic Beanstalk with Amazon RDS](AWSHowTo.RDS.md) for instructions for EC2-Classic and custom VPC platforms.

The sample application uses Amazon EFS. It only works in AWS Regions that support Amazon EFS. To learn about supporting AWS Regions, see [Amazon Elastic File System Endpoints and Quotas](https://docs.aws.amazon.com/general/latest/gr/elasticfilesystem.html) in the *AWS General Reference*.

If the platform of your Elastic Beanstalk environment uses PHP 7.4 or earlier, we recommend that you use Drupal version 8.9.13 for this tutorial. For platforms installed with PHP 8.0 or later, we recommend that you use Drupal 9.1.5.

For more information about Drupal releases and the PHP versions that they support, see [PHP requirements](https://www.drupal.org/docs/system-requirements/php-requirements#php_required) on the Drupal website. The core versions that Drupal recommends are listed on the website [https://www.drupal.org/project/drupal](https://www.drupal.org/project/drupal). 

## Launch a DB instance in Amazon RDS
<a name="php-hadrupal-tutorial-database"></a>

To use an external database with an application running in Elastic Beanstalk, first launch a DB instance with Amazon RDS. When you launch an instance with Amazon RDS, it is completely independent of Elastic Beanstalk and your Elastic Beanstalk environments, and will not be terminated or monitored by Elastic Beanstalk.

Use the Amazon RDS console to launch a Multi-AZ **MySQL** DB instance. Choosing a Multi-AZ deployment ensures that your database will failover and continue to be available if the source DB instance goes out of service.

**To launch an RDS DB instance in a default VPC**

1. Open the [RDS console](https://console.aws.amazon.com/rds/home).

1. In the navigation pane, choose **Databases**.

1. Choose **Create database**.

1. Choose **Standard Create**.
**Important**  
Do not choose **Easy Create**. If you choose it, you can't configure the necessary settings to launch this RDS DB.

1. Under **Additional configuration**, for **Initial database name**, type **ebdb**. 

1. Review the default settings and adjust these settings according to your specific requirements. Pay attention to the following options:
   + **DB instance class** – Choose an instance size that has an appropriate amount of memory and CPU power for your workload.
   + **Multi-AZ deployment** – For high availability, set this to **Create an Aurora Replica/Reader node in a different AZ**.
   + **Master username** and **Master password** – The database username and password. Make a note of these settings because you will use them later.

1. Verify the default settings for the remaining options, and then choose **Create database**.

Next, modify the security group attached to your DB instance to allow inbound traffic on the appropriate port. This is the same security group that you will attach to your Elastic Beanstalk environment later, so the rule that you add will grant ingress permission to other resources in the same security group.

**To modify the inbound rules on the security group that's attached to your RDS instance**

1. Open the [ Amazon RDS console](https://console.aws.amazon.com/rds/home).

1. Choose **Databases**.

1. Choose the name of your DB instance to view its details.

1. In the **Connectivity** section, make a note of the **Subnets**, **Security groups**, and **Endpoint** that are displayed on this page. This is so you can use this information later.

1. Under **Security**, you can see the security group that's associated with the DB instance. Open the link to view the security group in the Amazon EC2 console.

1. In the security group details, choose **Inbound**.

1. Choose **Edit**.

1. Choose **Add Rule**.

1. For **Type**, choose the DB engine that your application uses.

1. For **Source**, type **sg-** to view a list of available security groups. Choose the security group that's associated with the Auto Scaling group that's used with your Elastic Beanstalk environment. This is so that Amazon EC2 instances in the environment can have access to the database.  
![\[Screen image to edit the inbound rules for a security group in the Amazon EC2 console.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/ec2-securitygroup-rds.png)

1. Choose **Save**.

Creating a DB instance takes about 10 minutes. In the meantime, launch your Elastic Beanstalk environment.

## Launch an Elastic Beanstalk environment
<a name="php-hadrupal-tutorial-launch"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. Choose the **PHP** platform and accept the default settings and sample code. After you launch the environment, you can configure the environment to connect to the database, then deploy the Drupal code to the environment.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about 5 minutes and creates the following resources:
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **CloudFormation stack** – Elastic Beanstalk uses CloudFormation to launch the resources in your environment and propagate configuration changes. The resources are defined in a template that you can view in the [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+ **Domain name** – A domain name that routes to your web app in the form **subdomain*.*region*.elasticbeanstalk.com*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains. The RDS DB instance that you launched is outside of your environment, so you are responsible for managing its lifecycle.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Configure security settings and environment properties
<a name="php-hadrupal-tutorial-configure"></a>

Add the security group of your DB instance to your running environment. This procedure causes Elastic Beanstalk to reprovision all instances in your environment with the additional security group attached.

**To add a security group to your environment**
+ Do one of the following:
  + To add a security group using the Elastic Beanstalk console

    1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

    1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

    1. In the navigation pane, choose **Configuration**.

    1. In the **Instances** configuration category, choose **Edit**.

    1. Under **EC2 security groups**, choose the security group to attach to the instances, in addition to the instance security group that Elastic Beanstalk creates.

    1. To save the changes choose **Apply** at the bottom of the page.

    1. Read the warning, and then choose **Confirm**.
  + To add a security group using a [configuration file](ebextensions.md), use the [https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/security-configuration/securitygroup-addexisting.config](https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/security-configuration/securitygroup-addexisting.config) example file.

Next, use environment properties to pass the connection information to your environment. The sample application uses a default set of properties that match the ones that Elastic Beanstalk configures when you provision a database within your environment.

**To configure environment properties for an Amazon RDS DB instance**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

1. In the **Environment properties** section, define the variables that your application reads to construct a connection string. For compatibility with environments that have an integrated RDS DB instance, use the following names and values. You can find all values, except for your password, in the [RDS console](https://console.aws.amazon.com/rds/home).    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/php-hadrupal-tutorial.html)  
![\[Environment properties configuration section with RDS properties added\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/environment-cfg-envprops-rds.png)

1. To save the changes choose **Apply** at the bottom of the page.

After installing Drupal, you need to connect to the instance with SSH to retrieve some configuration details. Assign an SSH key to your environment's instances.

**To configure SSH**

1. If you haven't previously created a key pair, open the [key pairs page](https://console.aws.amazon.com/ec2/v2/home#KeyPairs) of the Amazon EC2 console and follow the instructions to create one.

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. Under **Security**, choose **Edit**.

1. For **EC2 key pair**, choose your key pair.

1. To save the changes choose **Apply** at the bottom of the page.

## Configure and deploy your application
<a name="php-hadrupal-tutorial-deploy"></a>

To create a Drupal project for Elastic Beanstalk, download the Drupal source code and combine it with the files in the [aws-samples/eb-php-drupal](https://github.com/aws-samples/eb-php-drupal) repository on GitHub.

**To create a Drupal project**

1. Run the follwing command to download Drupal from *www.drupal.org/download*. To learn more about downloads, see the [the Drupal website](https://www.drupal.org/download).

   If the platform of your Elastic Beanstalk environment uses PHP 7.4 or earlier, we recommend that you download Drupal version 8.9.13 for this tutorial. You can run the following command to download it.

   ```
   ~$ curl https://ftp.drupal.org/files/projects/drupal-8.9.13.tar.gz -o drupal.tar.gz
   ```

   If your platform uses PHP 8.0 or later, we recommend that you download Drupal 9.1.5. You can use this command to download it.

   ```
   ~$ curl https://ftp.drupal.org/files/projects/drupal-9.1.5.tar.gz -o drupal.tar.gz
   ```

   For more information about Drupal releases and the PHP versions that they support, see [PHP requirements](https://www.drupal.org/docs/system-requirements/php-requirements#php_required) in the official Drupal documentation. The core versions that Drupal recommends are listed on [the Drupal website](https://www.drupal.org/project/drupal).

1. Use the following command to download the configuration files from the sample repository:

   ```
   ~$ wget https://github.com/aws-samples/eb-php-drupal/releases/download/v1.1/eb-php-drupal-v1.zip
   ```

1. Extract Drupal and change the name of the folder.

   If you downloaded Drupal 8.9.13:

   ```
    ~$ tar -xvf drupal.tar.gz
    ~$ mv drupal-8.9.13 drupal-beanstalk
    ~$ cd drupal-beanstalk
   ```

   If you downloaded Drupal 9.1.5:

   ```
    ~$ tar -xvf drupal.tar.gz
    ~$ mv drupal-9.1.5 drupal-beanstalk
    ~$ cd drupal-beanstalk
   ```

1. Extract the configuration files over the Drupal installation.

   ```
    ~/drupal-beanstalk$ unzip ../eb-php-drupal-v1.zip
     creating: .ebextensions/
     inflating: .ebextensions/dev.config
     inflating: .ebextensions/drupal.config
     inflating: .ebextensions/efs-create.config
     inflating: .ebextensions/efs-filesystem.template
     inflating: .ebextensions/efs-mount.config
     inflating: .ebextensions/loadbalancer-sg.config
     inflating: LICENSE
     inflating: README.md
     inflating: beanstalk-settings.php
   ```

Verify that the structure of your `drupal-beanstalk` folder is correct, as shown.

```
drupal-beanstalk$ tree -aL 1
.
├── autoload.php
├── beanstalk-settings.php
├── composer.json
├── composer.lock
├── core
├── .csslintrc
├── .ebextensions
├── .ebextensions
├── .editorconfig
├── .eslintignore
├── .eslintrc.json
├── example.gitignore
├── .gitattributes
├── .htaccess
├── .ht.router.php
├── index.php
├── LICENSE
├── LICENSE.txt
├── modules
├── profiles
├── README.md
├── README.txt
├── robots.txt
├── sites
├── themes
├── update.php
├── vendor
└── web.config
```

The `beanstalk-settings.php` file from the project repo uses the environment variables that you defined in the previous step to configure the database connection. The `.ebextensions` folder contains configuration files that create additional resources within your Elastic Beanstalk environment.

The configuration files require modification to work with your account. Replace the placeholder values in the files with the appropriate IDs and create a source bundle.

**To update configuration files and create a source bundle.**

1. Modify the configuration files as follows.
   + `.ebextensions/dev.config` – restricts access to your environment to your IP address to protect it during the Drupal installation process. Replace the placeholder IP address near the top of the file with your public IP address.
   + `.ebextensions/efs-create.config` – creates an EFS file system and mount points in each Availability Zone / subnet in your VPC. Identify your default VPC and subnet IDs in the [Amazon VPC console](https://console.aws.amazon.com/vpc/home#subnets:filter=default).

1. Create a [source bundle](applications-sourcebundle.md) containing the files in your project folder. The following command creates a source bundle named `drupal-beanstalk.zip`. It excludes files in the `vendor` folder, which take up a lot of space and are not necessary for deploying your application to Elastic Beanstalk.

   ```
   ~/eb-drupal$ zip ../drupal-beanstalk.zip -r * .[^.]* -x "vendor/*"
   ```

Upload the source bundle to Elastic Beanstalk to deploy Drupal to your environment.

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

## Install Drupal
<a name="php-hadrupal-tutorial-install"></a>

**To complete your Drupal installation**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose the environment URL to open your site in a browser. You are redirected to a Drupal installation wizard because the site has not been configured yet.

1. Perform a standard installation with the following settings for the database:
   + **Database name** – The **DB Name** shown in the Amazon RDS console.
   + **Database username and password** – The **Master Username** and **Master Password** values you entered when creating your database.
   + **Advanced Options > Host** – The **Endpoint** of the DB instance shown in the Amazon RDS console.

Installation takes about a minute to complete.

## Update Drupal configuration and remove access restrictions
<a name="php-hadrupal-tutorial-updateenv"></a>

The Drupal installation process created a file named `settings.php` in the `sites/default` folder on the instance. You need this file in your source code to avoid resetting your site on subsequent deployments, but the file currently contains secrets that you don't want to commit to source. Connect to the application instance to retrieve information from the settings file.

**To connect to your application instance with SSH**

1. Open the [instances page](https://console.aws.amazon.com/ec2/v2/home#Instances:sort=tag:Name) of the Amazon EC2 console.

1. Choose the application instance. It is the one named after your Elastic Beanstalk environment.

1. Choose **Connect**.

1. Follow the instructions to connect the instance with SSH. The command looks similar to the following.

   ```
   $ ssh -i ~/.ssh/mykey ec2-user@ec2-00-55-33-222.us-west-2.compute.amazonaws.com
   ```

Get the sync directory id from the last line of the settings file.

```
[ec2-user ~]$ tail -n 1 /var/app/current/sites/default/settings.php
$config_directories['sync'] = 'sites/default/files/config_4ccfX2sPQm79p1mk5IbUq9S_FokcENO4mxyC-L18-4g_xKj_7j9ydn31kDOYOgnzMu071Tvc4Q/sync';
```

The file also contains the sites current hash key, but you can ignore the current value and use your own.

Assign the sync directory path and hash key to environment properties. The customized settings file from the project repo reads these properties to configure the site during deployment, in addition to the database connection properties that you set earlier.

**Drupal configuration properties**
+ `SYNC_DIR` – The path to the sync directory.
+ `HASH_SALT` – Any string value that meets [environment property requirements](environments-cfg-softwaresettings.md#environments-cfg-softwaresettings-console).

**To configure environment variables in the Elastic Beanstalk console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

1. Scroll down to **Runtime environment variables**.

1. Select **Add environment variable**.

1. For **Source** select **Plain text**.
**Note**  
The **Secrets Manager** and **SSM Parameter Store** values in the drop-down are for configuring environment variables as secrets to store sensitive data, such as credentials and API keys. For more information, see [Using Elastic Beanstalk with AWS Secrets Manager and AWS Systems Manager Parameter Store](AWSHowTo.secrets.md). 

1. Enter the **Environment variable name** and **Environment variable value** pairs.

1. If you need to add more variables repeat **Step 6** through **Step 8**.

1. To save the changes choose **Apply** at the bottom of the page.

Finally, the sample project includes a configuration file (`loadbalancer-sg.config`) that creates a security group and assigns it to the environment's load balancer, using the IP address that you configured in `dev.config` to restrict HTTP access on port 80 to connections from your network. Otherwise, an outside party could potentially connect to your site before you have installed Drupal and configured your admin account.

**To update Drupal's configuration and remove access restrictions**

1. Delete the `.ebextensions/loadbalancer-sg.config` file from your project directory.

   ```
   ~/drupal-beanstalk$ rm .ebextensions/loadbalancer-sg.config
   ```

1. Copy the customized `settings.php` file into the sites folder.

   ```
   ~/drupal-beanstalk$ cp beanstalk-settings.php sites/default/settings.php
   ```

1. Create a source bundle.

   ```
   ~/eb-drupal$ zip ../drupal-beanstalk-v2.zip -r * .[^.]* -x "vendor/*"
   ```

Upload the source bundle to Elastic Beanstalk to deploy Drupal to your environment.

**To deploy a source bundle**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

## Configure your Auto Scaling group
<a name="php-hadrupal-tutorial-autoscaling"></a>

Finally, configure your environment's Auto Scaling group with a higher minimum instance count. Run at least two instances at all times to prevent the web servers in your environment from being a single point of failure, and to allow you to deploy changes without taking your site out of service.

**To configure your environment's Auto Scaling group for high availability**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Capacity** configuration category, choose **Edit**.

1. In the **Auto Scaling group** section, set **Min instances** to **2**.

1. To save the changes choose **Apply** at the bottom of the page.

To support content uploads across multiple instances, the sample project uses Amazon Elastic File System to create a shared file system. Create a post on the site and upload content to store it on the shared file system. View the post and refresh the page multiple times to hit both instances and verify that the shared file system is working.

## Cleanup
<a name="php-hadrupal-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

In addition, you can terminate database resources that you created outside of your Elastic Beanstalk environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the data to another instance later.

**To terminate your RDS DB instance**

1. Open the [Amazon RDS console](https://console.aws.amazon.com/rds).

1. Choose **Databases**.

1. Choose your DB instance.

1. Choose **Actions**, and then choose **Delete**.

1. Choose whether to create a snapshot, and then choose **Delete**.

## Next steps
<a name="php-hadrupal-tutorial-nextsteps"></a>

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

The sample application uses configuration files to configure PHP settings and create a table in the database if it doesn't already exist. You can also use a configuration file to configure your instances' security group settings during environment creation to avoid time-consuming configuration updates. See [Advanced environment customization with configuration files (`.ebextensions`)](ebextensions.md) for more information.

For development and testing, you might want to use the Elastic Beanstalk functionality for adding a managed DB instance directly to your environment. For instructions on setting up a database inside your environment, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

If you need a high-performance database, consider using [Amazon Aurora](https://aws.amazon.com/rds/aurora/). Amazon Aurora is a MySQL-compatible database engine that offers commercial database features at low cost. To connect your application to a different database, repeat the [security group configuration](php-ha-tutorial.md#php-hawrds-tutorial-database) steps and [update the RDS-related environment properties](php-ha-tutorial.md#php-hawrds-tutorial-configure). 

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.