

# 在 EC2 实例上安装 Web 服务器
<a name="CHAP_Tutorials.WebServerDB.CreateWebServer"></a>

在您在[启动 EC2 实例以连接数据库集群](CHAP_Tutorials.WebServerDB.LaunchEC2.md)中创建的 EC2 实例上安装 Web 服务器。Web 服务器连接到您在[创建 Amazon Aurora 数据库集群](CHAP_Tutorials.WebServerDB.CreateDBCluster.md)中创建的 Amazon Aurora 数据库集群。

## 使用 PHP 和 MariaDB 安装 Apache Web 服务器
<a name="CHAP_Tutorials.WebServerDB.CreateWebServer.Apache"></a>

连接到 EC2 实例并安装 Web 服务器。

**连接到 EC2 实例并安装带有 PHP 的 Apache Web 服务器**

1. 按照《Amazon EC2 用户指南》**中的[连接到 Linux 实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html)中的步骤操作，连接到您之前创建的 EC2 实例。

   建议您使用 SSH 连接到 EC2 实例。如果 SSH 客户端实用程序安装在 Windows、Linux 或 Mac 上，则可以使用以下命令格式连接到该实例：

   ```
   ssh -i location_of_pem_file ec2-user@ec2-instance-public-dns-name
   ```

   例如，假设在 Linux 上 `ec2-database-connect-key-pair.pem` 存储在 `/dir1` 中，而 EC2 实例的公有 IPv4 DNS 为 `ec2-12-345-678-90.compute-1.amazonaws.com`。SSH 命令将如下所示：

   ```
   ssh -i /dir1/ec2-database-connect-key-pair.pem ec2-user@ec2-12-345-678-90.compute-1.amazonaws.com
   ```

1. 通过更新 EC2 实例上的软件，获取最新的错误修复和安全更新。要执行此操作，请使用以下命令。
**注意**  
`-y` 选项安装更新时不提示确认。要在安装前检查更新，请忽略该选项。

   ```
   sudo dnf update -y
   ```

1. 更新完成后，使用以下命令安装 Apache Web 服务器、PHP 和 MariaDB 或 PostgreSQL 软件。此命令同时安装多个软件包和相关依赖项。

------
#### [ MariaDB & MySQL ]

   ```
   sudo dnf install -y httpd php php-mysqli mariadb105
   ```

------
#### [ PostgreSQL ]

   ```
   sudo dnf install -y httpd php php-pgsql postgresql15
   ```

------

   如果您收到错误，则您的实例可能不是使用 Amazon Linux 2023 AMI 启动的。您可能使用的是 Amazon Linux 2 AMI。您可以使用以下命令查看 Amazon Linux 的版本。

   ```
   cat /etc/system-release
   ```

   有关更多信息，请参阅[更新实例软件](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/install-updates.html)。

1. 使用下面所示的命令启动 Web 服务器。

   ```
   sudo systemctl start httpd
   ```

   您可以测试 Web 服务器是否已正确安装和启动。为此，请在 Web 浏览器的地址栏中输入 EC2 实例的公有域名系统 (DNS) 名称，例如：`http://ec2-42-8-168-21.us-west-1.compute.amazonaws.com`。如果 Web 服务器正在运行，您将看到 Apache 测试页面。

   如果您没有看到 Apache 测试页面，请检查您在[教程：创建 VPC 以用于数据库集群（仅限 IPv4）](CHAP_Tutorials.WebServerDB.CreateVPC.md)中创建的 VPC 安全组的入站规则。确保入站规则包括一条允许 HTTP（端口 80）访问 IP 地址以连接到 Web 服务器的规则。
**注意**  
Apache 测试页面仅在文档根目录 `/var/www/html` 中无内容时才显示。将内容添加到文档根目录后，您的内容将显示在 EC2 实例的公有 DNS 地址处。在此之前，它出现在 Apache 测试页面上。

1. 使用 `systemctl` 命令配置 Web 服务器以使其在每次系统启动时启动。

   ```
   sudo systemctl enable httpd
   ```

要允许 `ec2-user` 在 Apache Web 服务器的默认根目录中管理文件，请修改 `/var/www` 目录的所有权和权限。有多种方式可以完成此任务。在本教程中，可将 `ec2-user` 添加到 `apache` 组，将 `apache` 目录的所有权授予 `/var/www` 组，并为该组指定写入权限。

**设置 Apache Web 服务器的文件权限**

1. 将 `ec2-user` 用户添加到 `apache` 组。

   ```
   sudo usermod -a -G apache ec2-user
   ```

1. 注销以刷新您的权限并包含新的 `apache` 组。

   ```
   exit
   ```

1. 再重新登录并使用 `apache` 命令验证 `groups` 组是否存在。

   ```
   groups
   ```

   输出看上去类似于以下内容：

   ```
   ec2-user adm wheel apache systemd-journal
   ```

1. 将 `/var/www` 目录的组所有权及其内容更改到 `apache` 组。

   ```
   sudo chown -R ec2-user:apache /var/www
   ```

1. 更改 `/var/www` 及其子目录的目录权限，以添加组写入权限并设置未来创建的子目录上的组 ID。

   ```
   sudo chmod 2775 /var/www
   find /var/www -type d -exec sudo chmod 2775 {} \;
   ```

1. 递归地更改 `/var/www` 目录及其子目录中的文件的权限，以添加组写入权限。

   ```
   find /var/www -type f -exec sudo chmod 0664 {} \;
   ```

现在，`ec2-user`（和 `apache` 组的任何将来成员）可以添加、删除和编辑 Apache 文档根目录中的文件。这使您可以添加内容，例如静态网站或 PHP 应用程序。

**注意**  
运行 HTTP 协议的 Web 服务器不为其发送或接收的数据提供传输安全。当您使用 Web 浏览器连接 HTTP 服务器时，窃取者可在沿网络路径的任何位置看到许多信息。这些信息包括您访问的 URL、您接收的网页内容以及任何 HTML 表单的内容（包括密码）。  
保护您的 Web 服务器的最佳实践是安装对于 HTTPS（HTTP Secure）的支持。此协议利用 SSL/TLS 加密保护您的数据。有关更多信息，请参阅在*Amazon EC2用户指南*中的[教程：使用 Amazon Linux AMI 配置 SSL/TLS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/SSL-on-amazon-linux-ami.html)。

## 将您的 Apache Web 服务器连接到数据库集群
<a name="CHAP_Tutorials.WebServerDB.CreateWebServer.PHPContent"></a>

接着，将内容添加到连接到 Amazon Aurora 数据库集群的 Apache Web 服务器。

**将内容添加到连接到数据库集群的 Apache Web 服务器**

1. 在仍连接到 EC2 实例时，将目录更改到 `/var/www` 并创建名为 `inc` 的新子目录。

   ```
   cd /var/www
   mkdir inc
   cd inc
   ```

1. 在名为 `inc` 的 `dbinfo.inc` 目录中新建文件，然后通过调用 nano（或您选择的编辑器）编辑文件。

   ```
   >dbinfo.inc
   nano dbinfo.inc
   ```

1. 将以下内容添加到 `dbinfo.inc` 文件。在这里，*db\$1instance\$1endpoint* 是数据库实例的不带端口的数据库实例端点。
**注意**  
我们建议将用户名和密码信息放在不属于 Web 服务器的文档根目录的文件夹中。这样做会减少您的安全信息被泄露的可能性。  
确保在应用程序中将 `master password` 更改为合适的密码。

   ```
   <?php
   
   define('DB_SERVER', 'db_cluster_writer_endpoint');
   define('DB_USERNAME', 'tutorial_user');
   define('DB_PASSWORD', 'master password');
   define('DB_DATABASE', 'sample');
   ?>
   ```

1. 保存并关闭 `dbinfo.inc` 文件。如果您使用的是 nano，请使用 Ctrl\$1S 和 Ctrl\$1X 保存并关闭文件。

1. 将目录更改为 `/var/www/html`。

   ```
   cd /var/www/html
   ```

1. 在名为 `html` 的 `SamplePage.php` 目录中新建文件，然后通过调用 nano（或您选择的编辑器）编辑文件。

   ```
   >SamplePage.php
   nano SamplePage.php
   ```

1. 将以下内容添加到 `SamplePage.php` 文件：

------
#### [ MariaDB & MySQL ]

   ```
   <?php include "../inc/dbinfo.inc"; ?>
   <html>
   <body>
   <h1>Sample page</h1>
   <?php
   
     /* Connect to MySQL and select the database. */
     $connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
   
     if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
   
     $database = mysqli_select_db($connection, DB_DATABASE);
   
     /* Ensure that the EMPLOYEES table exists. */
     VerifyEmployeesTable($connection, DB_DATABASE);
   
     /* If input fields are populated, add a row to the EMPLOYEES table. */
     $employee_name = htmlentities($_POST['NAME']);
     $employee_address = htmlentities($_POST['ADDRESS']);
   
     if (strlen($employee_name) || strlen($employee_address)) {
       AddEmployee($connection, $employee_name, $employee_address);
     }
   ?>
   
   <!-- Input form -->
   <form action="<?PHP echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
     <table border="0">
       <tr>
         <td>NAME</td>
         <td>ADDRESS</td>
       </tr>
       <tr>
         <td>
           <input type="text" name="NAME" maxlength="45" size="30" />
         </td>
         <td>
           <input type="text" name="ADDRESS" maxlength="90" size="60" />
         </td>
         <td>
           <input type="submit" value="Add Data" />
         </td>
       </tr>
     </table>
   </form>
   
   <!-- Display table data. -->
   <table border="1" cellpadding="2" cellspacing="2">
     <tr>
       <td>ID</td>
       <td>NAME</td>
       <td>ADDRESS</td>
     </tr>
   
   <?php
   
   $result = mysqli_query($connection, "SELECT * FROM EMPLOYEES");
   
   while($query_data = mysqli_fetch_row($result)) {
     echo "<tr>";
     echo "<td>",$query_data[0], "</td>",
          "<td>",$query_data[1], "</td>",
          "<td>",$query_data[2], "</td>";
     echo "</tr>";
   }
   ?>
   
   </table>
   
   <!-- Clean up. -->
   <?php
   
     mysqli_free_result($result);
     mysqli_close($connection);
   
   ?>
   
   </body>
   </html>
   
   
   <?php
   
   /* Add an employee to the table. */
   function AddEmployee($connection, $name, $address) {
      $n = mysqli_real_escape_string($connection, $name);
      $a = mysqli_real_escape_string($connection, $address);
   
      $query = "INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES ('$n', '$a');";
   
      if(!mysqli_query($connection, $query)) echo("<p>Error adding employee data.</p>");
   }
   
   /* Check whether the table exists and, if not, create it. */
   function VerifyEmployeesTable($connection, $dbName) {
     if(!TableExists("EMPLOYEES", $connection, $dbName))
     {
        $query = "CREATE TABLE EMPLOYEES (
            ID int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            NAME VARCHAR(45),
            ADDRESS VARCHAR(90)
          )";
   
        if(!mysqli_query($connection, $query)) echo("<p>Error creating table.</p>");
     }
   }
   
   /* Check for the existence of a table. */
   function TableExists($tableName, $connection, $dbName) {
     $t = mysqli_real_escape_string($connection, $tableName);
     $d = mysqli_real_escape_string($connection, $dbName);
   
     $checktable = mysqli_query($connection,
         "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = '$t' AND TABLE_SCHEMA = '$d'");
   
     if(mysqli_num_rows($checktable) > 0) return true;
   
     return false;
   }
   ?>
   ```

------
#### [ PostgreSQL ]

   ```
   <?php include "../inc/dbinfo.inc"; ?>
   
   <html>
   <body>
   <h1>Sample page</h1>
   <?php
   
   /* Connect to PostgreSQL and select the database. */
   $constring = "host=" . DB_SERVER . " dbname=" . DB_DATABASE . " user=" . DB_USERNAME . " password=" . DB_PASSWORD ;
   $connection = pg_connect($constring);
   
   if (!$connection){
    echo "Failed to connect to PostgreSQL";
    exit;
   }
   
   /* Ensure that the EMPLOYEES table exists. */
   VerifyEmployeesTable($connection, DB_DATABASE);
   
   /* If input fields are populated, add a row to the EMPLOYEES table. */
   $employee_name = htmlentities($_POST['NAME']);
   $employee_address = htmlentities($_POST['ADDRESS']);
   
   if (strlen($employee_name) || strlen($employee_address)) {
     AddEmployee($connection, $employee_name, $employee_address);
   }
   
   ?>
   
   <!-- Input form -->
   <form action="<?PHP echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
     <table border="0">
       <tr>
         <td>NAME</td>
         <td>ADDRESS</td>
       </tr>
       <tr>
         <td>
       <input type="text" name="NAME" maxlength="45" size="30" />
         </td>
         <td>
       <input type="text" name="ADDRESS" maxlength="90" size="60" />
         </td>
         <td>
       <input type="submit" value="Add Data" />
         </td>
       </tr>
     </table>
   </form>
   <!-- Display table data. -->
   <table border="1" cellpadding="2" cellspacing="2">
     <tr>
       <td>ID</td>
       <td>NAME</td>
       <td>ADDRESS</td>
     </tr>
   
   <?php
   
   $result = pg_query($connection, "SELECT * FROM EMPLOYEES");
   
   while($query_data = pg_fetch_row($result)) {
     echo "<tr>";
     echo "<td>",$query_data[0], "</td>",
          "<td>",$query_data[1], "</td>",
          "<td>",$query_data[2], "</td>";
     echo "</tr>";
   }
   ?>
   </table>
   
   <!-- Clean up. -->
   <?php
   
     pg_free_result($result);
     pg_close($connection);
   ?>
   </body>
   </html>
   
   
   <?php
   
   /* Add an employee to the table. */
   function AddEmployee($connection, $name, $address) {
      $n = pg_escape_string($name);
      $a = pg_escape_string($address);
      echo "Forming Query";
      $query = "INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES ('$n', '$a');";
   
      if(!pg_query($connection, $query)) echo("<p>Error adding employee data.</p>"); 
   }
   
   /* Check whether the table exists and, if not, create it. */
   function VerifyEmployeesTable($connection, $dbName) {
     if(!TableExists("EMPLOYEES", $connection, $dbName))
     {
        $query = "CREATE TABLE EMPLOYEES (
            ID serial PRIMARY KEY,
            NAME VARCHAR(45),
            ADDRESS VARCHAR(90)
          )";
   
        if(!pg_query($connection, $query)) echo("<p>Error creating table.</p>"); 
     }
   }
   /* Check for the existence of a table. */
   function TableExists($tableName, $connection, $dbName) {
     $t = strtolower(pg_escape_string($tableName)); //table name is case sensitive
     $d = pg_escape_string($dbName); //schema is 'public' instead of 'sample' db name so not using that
   
     $query = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = '$t';";
     $checktable = pg_query($connection, $query);
   
     if (pg_num_rows($checktable) >0) return true;
     return false;
   
   }
   ?>
   ```

------

1. 保存并关闭 `SamplePage.php` 文件。

1. 打开 Web 浏览器并浏览到 `http://EC2 instance endpoint/SamplePage.php`（例如：`http://ec2-12-345-67-890.us-west-2.compute.amazonaws.com/SamplePage.php`）来验证 Web 服务器是否已成功连接到数据库集群。

您可以使用 `SamplePage.php` 将数据添加到数据库集群。您添加的数据之后将显示在该页面上。要验证数据是否已插入到表中，请在 Amazon EC2 实例上安装 MySQL 客户端。然后，连接到数据库集群并查询表。

有关连接到数据库集群的更多信息，请参阅 [连接到 Amazon Aurora 数据库集群](Aurora.Connecting.md)。

要确保您的数据库集群尽可能安全，请验证 VPC 外部的源是否无法连接到您的数据库集群。

在您完成 Web 服务器和数据库测试后，应删除您的数据库集群 和 Amazon EC2 实例。
+ 要删除数据库集群，请按照 [删除 Aurora 数据库集群和数据库实例](USER_DeleteCluster.md) 中的说明操作。您无需创建最终快照。
+ 要终止 Amazon EC2 实例，请按照 *Amazon EC2 用户指南*中的[终止实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html)中的说明操作。