

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 教學：建立 Web 伺服器和 Amazon RDS 資料庫執行個體
<a name="TUT_WebAppWithRDS"></a>

本教學課程說明如何安裝支援 PHP 的 Apache Web 伺服器，並建立 MariaDB、MySQL 或 PostgreSQL 資料庫。Web 伺服器會在使用 Amazon Linux 2023 的 Amazon EC2 執行個體上執行，而且您可以選擇 MySQL 或 PostgreSQL 資料庫執行個體。Amazon EC2 執行個體和 資料庫執行個體都會在以 Amazon VPC 服務為基礎的 Virtual Private Cloud (VPC) 中執行。

**重要**  
建立 AWS 帳戶無需付費。不過，透過完成本教學課程，您可能會因為使用 AWS 的資源而產生費用。如果不再需要這些資源，您可以在完成教學課程後刪除這些資源。

**注意**  
本教學課程使用 Amazon Linux 2023，可能不適用於其他 Linux 版本。

在後續的教學課程中，您會為 AWS 帳戶建立使用預設 VPC、子網路和安全群組的 EC2 執行個體。本教學課程向您介紹如何建立資料庫執行個體，並自動設定與您建立的 EC2 執行個體的連線。然後，本教學課程將向您展示如何在 EC2 執行個體上安裝 Web 伺服器。您可以使用資料庫執行個體端點，將 Web 伺服器連線到 VPC 中的資料庫執行個體。

1. [啟動 EC2 執行個體以與資料庫執行個體連線](CHAP_Tutorials.WebServerDB.LaunchEC2.md)

1. [建立 Amazon RDS 資料庫執行個體](CHAP_Tutorials.WebServerDB.CreateDBInstance.md)

1. [在您的 EC2 執行個體上安裝 Web 伺服器](CHAP_Tutorials.WebServerDB.CreateWebServer.md)

下圖顯示此教學課程完成時的組態。

![\[單一 VPC 案例\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/con-VPC-sec-grp.png)


**注意**  
完成教學課程後，在您的 VPC 中，每個可用區域都有一個公有子網路和私有子網路。本教學課程使用 的預設 VPC， AWS 帳戶 並自動設定 EC2 執行個體與資料庫執行個體之間的連線。如果您想改為針對此案例設定新的 VPC，請完成 [教學課程：建立要與資料庫執行個體搭配使用的 VPC (僅限 IPv4)](CHAP_Tutorials.WebServerDB.CreateVPC.md) 中的任務。

# 啟動 EC2 執行個體以與資料庫執行個體連線
<a name="CHAP_Tutorials.WebServerDB.LaunchEC2"></a>

在 VPC 的公有子網路中建立 Amazon EC2 執行個體。

**啟動 EC2 執行個體**

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/)：// 開啟 Amazon EC2 主控台。

1. 在 的右上角 AWS 管理主控台，選擇您要建立 EC2 執行個體的 AWS 區域 。

1. 選擇 **EC2 Dashboard (EC2 儀表板)**，然後選擇 **Launch Instance (啟動執行個體)**，如下所示。  
![\[EC2 儀表板\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_11.png)

1. 在**啟動執行個體**頁面中選擇下列設定。

   1. 在 **Name and tags** (名稱與標籤) 下，對於 **Name** (名稱)，輸入 **tutorial-ec2-instance-web-server**。

   1. 在**應用程式和作業系統映像 (Amazon Machine Image)** 中，選擇 **Amazon Linux**，然後選擇 **Amazon Linux 2023 AMI**。保留其他選項的預設值。  
![\[選擇 Amazon Machine Image\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_12.png)

   1. 在**Instance type** (執行個體類型) 下，選擇 **t2.micro**。

   1. 在 **Key pair (login)** (金鑰對 (登入)) 下，選擇 **Key pair name** (金鑰對名稱)，以使用現有金鑰對。若要為 Amazon EC2 執行個體建立新的金鑰對，請選擇 **Create new key pair** (建立新的金鑰對)，然後使用 **Create key pair** (建立金鑰對) 視窗來建立金鑰對。

      如需有關建立新的金鑰對的詳細資訊，請參閱《Amazon EC2 使用者指南》**中的[建立金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#create-a-key-pair)。

   1. 在 **Network settings** (網路設定) 下設定這些值，其他值則維持預設值：
      + 對於 **Allow SSH traffic from** (允許 SSH 流量來自)，選擇 EC2 執行個體做為 SSH 的連線來源。

        如果顯示的 IP 地址對 SSH 連線而言是正確的，您可以選擇 **My IP** (我的 IP)。

        否則，您可以決定用於使用 Secure Shell (SSH) 連線至 VPC 中 EC2 執行個體的 IP 地址。若要判斷公有 IP 地址，您可以在不同的瀏覽器視窗或索引標籤中使用 [https://checkip.amazonaws.com](https://checkip.amazonaws.com) 中的服務。IP 地址的範例為 `203.0.113.25/32`。

        在許多情況下，您可能透過網際網路服務供應商 (ISP) 或是從沒有靜態 IP 地址的防火牆進行連線。若是如此，請務必確定用戶端電腦所使用的 IP 地址範圍。
**警告**  
如果您使用 `0.0.0.0/0` 進行 SSH 存取，則可讓所有 IP 地址使用 SSH 存取您的公有執行個體。通常在測試環境中短暫使用此方法是沒有問題的，但在生產環境則不安全。在生產環境中，您應只授權特定 IP 地址或特定範圍的地址可使用 SSH 存取您的執行個體。
      + 開啟 **Allow HTTPs traffic from the internet** (允許來自網際網路的 HTTPS 流量)。
      + 開啟 **Allow HTTP traffic from the internet** (允許來自網際網路的 HTTP 流量)。  
![\[設定執行個體詳細資訊\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_14.png)

   1. 讓剩餘區段保留預設值。

   1. 檢閱 **Summary** (摘要) 面板中執行個體組態的摘要，並在準備就緒時選擇 **Launch instance** (啟動執行個體)。

1. 在**啟動狀態**頁面上，記下新的 EC2 執行個體的識別碼，例如：`i-1234567890abcdef0`。  
![\[啟動狀態頁面上的 EC2 執行個體識別符。\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/getting-started-ec2-id.png)

1. 選擇 EC2 執行個體識別符，以開啟 EC2 執行個體清單，然後選取您的 EC2 執行個體。

1. 在**詳細資訊**索引標籤中，請記下以下值，當您使用 SSH 進行連線時需要這些值：

   1. 在**執行個體摘要**中，記下**公用 IPv4 DNS** 的值。  
![\[執行個體頁面的詳細資訊索引標籤上的 EC2 公用 DNS 名稱。\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/easy-create-ec2-public-dns.png)

   1. 在**執行個體詳細資訊**中，記下**金鑰對名稱**的值。  
![\[執行個體頁面的詳細資訊索引標籤上的 EC2 金鑰對名稱。\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/easy-create-ec2-key-pair.png)

1. 繼續之前，等待執行個體的 **Instance Status ** (執行個體狀態) 顯示為 **Running** (執行中)。

1. 完成 [建立 Amazon RDS 資料庫執行個體](CHAP_Tutorials.WebServerDB.CreateDBInstance.md)。

# 建立 Amazon RDS 資料庫執行個體
<a name="CHAP_Tutorials.WebServerDB.CreateDBInstance"></a>

建立 RDS for MariaDB、RDS for MySQL 或 RDS for PostgreSQL 資料庫執行個體，以維護 Web 應用程式所使用的資料。

------
#### [ RDS for MariaDB ]

**若要建立 MariaDB 執行個體**

1. 登入 AWS 管理主控台，開啟位於 [https://console.aws.amazon.com/rds/](https://console.aws.amazon.com/rds/) 的 Amazon RDS 主控台。

1. 在 AWS 管理主控台 右上角中，核取 AWS 區域。它應與您已在其中建立 EC2 執行個體的區域相同。

1. 在導覽窗格中，選擇 **Databases** (資料庫)。

1. 選擇 **Create database** (建立資料庫)。

1. 在**建立資料庫**頁面上，選擇**標準建立**。

1. 在**引擎選項**中，選擇 **MariaDB**。  
![\[選取引擎類型\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/tutorial-create-mariadb.png)

1. 在**範本**中，選擇**免費方案**或**沙盒**。免費方案帳戶的**免費方案**隨即顯示。付費方案帳戶的**沙盒**隨即顯示。  
![\[選取範本\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/tutorial-create-template.png)

1. 在 **Availability and durability** (可用性與耐久性) 區段中，保留預設值。

1. 在 **Settings (設定)** 區段中，設定這些值：
   + **DB instance identifier** (資料庫執行個體識別符) – 輸入 **tutorial-db-instance**。
   + **Master username** (主要使用者名稱) – 輸入 **tutorial\$1user**。
   + **Auto generate a password** (自動產生密碼) – 保持選項關閉。
   + **Master password** (主要密碼) – 輸入密碼。
   + **Confirm password (確認密碼)** – 重新輸入密碼。  
![\[設定區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Settings.png)

1. 在 **Instance configuration** (執行個體組態) 區段中，設定這些值：
   + **Burstable classes (includes t classes)** (高載類別 (包括 t 類別))
   + **db.t3.micro**  
![\[執行個體組態區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_DB_instance_micro.png)

1. 在 **Storage** (儲存) 區段中，保留預設值。

1. 在 **Connectivity** (連線能力) 區段中，設定這些值，並且其他值都維持預設值：
   + 對於 **Compute resource** (運算資源)，選擇 **Connect to an EC2 compute resource** (連線至 EC2 運算資源)。
   + 對於 **EC2 instance** (EC2 執行個體)，選擇之前建立的 EC2 執行個體，例如 **tutorial-ec2-instance-web-server**。  
![\[連線能力區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Connectivity.png)

1. 在 **Database authentication** (資料庫身分驗證) 區段中，請確定已選取 **Password authentication** (密碼身分驗證)。

1. 在 **Additional configuration (其他設定)** 區段中，輸入 **sample** 做為 **Initial database name (初始資料庫名稱)**。其他選項都保留預設設定。

1. 若要建立 MariaDB 執行個體，請選擇**建立資料庫**。

   您的新資料庫執行個體會出現在 **Databases** (資料庫) 清單中，狀態為 **Creating** (建立中)。

1. 等待新資料庫執行個體的 **Status (狀態)** 顯示為 **available (可用)**。接著，選擇資料庫執行個體的名稱，以顯示其詳細資訊。

1. 在 **Connectivity & security (連線能力與安全性)** 區段中，檢視資料庫執行個體的 **Endpoint (端點)** 和 **Port (連接埠)**。  
![\[資料庫執行個體詳細資訊\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Endpoint_Port.png)

   記下資料庫執行個體的端點和連接埠。您會使用此資訊，將 Web 伺服器連接至資料庫執行個體。

1. 完成 [在您的 EC2 執行個體上安裝 Web 伺服器](CHAP_Tutorials.WebServerDB.CreateWebServer.md)。

------
#### [ RDS for MySQL ]

**建立 MySQL 資料庫執行個體**

1. 登入 AWS 管理主控台，開啟位於 [https://console.aws.amazon.com/rds/](https://console.aws.amazon.com/rds/) 的 Amazon RDS 主控台。

1. 在 AWS 管理主控台 右上角中，核取 AWS 區域。它應與您已在其中建立 EC2 執行個體的區域相同。

1. 在導覽窗格中，選擇 **Databases** (資料庫)。

1. 選擇 **Create database** (建立資料庫)。

1. 在**建立資料庫**頁面上，選擇**標準建立**。

1. 在**引擎選項** 中，選擇 **MySQL**。  
![\[選取引擎類型\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/tutorial-create-mysql.png)

1. 在**範本**中，選擇**免費方案**或**沙盒**。免費方案帳戶的**免費方案**隨即顯示。付費方案帳戶的**沙盒**隨即顯示。  
![\[選取範本\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/tutorial-create-template.png)

1. 在 **Availability and durability** (可用性與耐久性) 區段中，保留預設值。

1. 在 **Settings (設定)** 區段中，設定這些值：
   + **DB instance identifier** (資料庫執行個體識別符) – 輸入 **tutorial-db-instance**。
   + **Master username** (主要使用者名稱) – 輸入 **tutorial\$1user**。
   + **Auto generate a password** (自動產生密碼) – 保持選項關閉。
   + **Master password** (主要密碼) – 輸入密碼。
   + **Confirm password (確認密碼)** – 重新輸入密碼。  
![\[設定區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Settings.png)

1. 在 **Instance configuration** (執行個體組態) 區段中，設定這些值：
   + **Burstable classes (includes t classes)** (高載類別 (包括 t 類別))
   + **db.t3.micro**  
![\[執行個體組態區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_DB_instance_micro.png)

1. 在 **Storage** (儲存) 區段中，保留預設值。

1. 在 **Connectivity** (連線能力) 區段中，設定這些值，並且其他值都維持預設值：
   + 對於 **Compute resource** (運算資源)，選擇 **Connect to an EC2 compute resource** (連線至 EC2 運算資源)。
   + 對於 **EC2 instance** (EC2 執行個體)，選擇之前建立的 EC2 執行個體，例如 **tutorial-ec2-instance-web-server**。  
![\[連線能力區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Connectivity.png)

1. 在 **Database authentication** (資料庫身分驗證) 區段中，請確定已選取 **Password authentication** (密碼身分驗證)。

1. 在 **Additional configuration (其他設定)** 區段中，輸入 **sample** 做為 **Initial database name (初始資料庫名稱)**。其他選項都保留預設設定。

1. 若要建立 MySQL 資料庫執行個體，請選擇 **Create database** (建立資料庫)。

   您的新資料庫執行個體會出現在 **Databases** (資料庫) 清單中，狀態為 **Creating** (建立中)。

1. 等待新資料庫執行個體的 **Status (狀態)** 顯示為 **available (可用)**。接著，選擇資料庫執行個體的名稱，以顯示其詳細資訊。

1. 在 **Connectivity & security (連線能力與安全性)** 區段中，檢視資料庫執行個體的 **Endpoint (端點)** 和 **Port (連接埠)**。  
![\[資料庫執行個體詳細資訊\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Endpoint_Port.png)

   記下資料庫執行個體的端點和連接埠。您會使用此資訊，將 Web 伺服器連接至資料庫執行個體。

1. 完成 [在您的 EC2 執行個體上安裝 Web 伺服器](CHAP_Tutorials.WebServerDB.CreateWebServer.md)。

------
#### [ RDS for PostgreSQL ]

**若要建立 PostgreSQL 資料庫執行個體**

1. 登入 AWS 管理主控台，開啟位於 [https://console.aws.amazon.com/rds/](https://console.aws.amazon.com/rds/) 的 Amazon RDS 主控台。

1. 在 AWS 管理主控台 右上角中，核取 AWS 區域。它應與您已在其中建立 EC2 執行個體的區域相同。

1. 在導覽窗格中，選擇 **Databases** (資料庫)。

1. 選擇 **Create database** (建立資料庫)。

1. 在**建立資料庫**頁面上，選擇**標準建立**。

1. 針對**引擎選項**，選擇 **PostgreSQL**。  
![\[選取引擎類型\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/tutorial-create-postgres.png)

1. 在**範本**中，選擇**免費方案**或**沙盒**。免費方案帳戶的**免費方案**隨即顯示。付費方案帳戶的**沙盒**隨即顯示。  
![\[選取範本\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/tutorial-create-template.png)

1. 在 **Availability and durability** (可用性與耐久性) 區段中，保留預設值。

1. 在 **Settings (設定)** 區段中，設定這些值：
   + **DB instance identifier** (資料庫執行個體識別符) – 輸入 **tutorial-db-instance**。
   + **Master username** (主要使用者名稱) – 輸入 **tutorial\$1user**。
   + **Auto generate a password** (自動產生密碼) – 保持選項關閉。
   + **Master password** (主要密碼) – 輸入密碼。
   + **Confirm password (確認密碼)** – 重新輸入密碼。  
![\[設定區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Settings.png)

1. 在 **Instance configuration** (執行個體組態) 區段中，設定這些值：
   + **Burstable classes (includes t classes)** (高載類別 (包括 t 類別))
   + **db.t3.micro**  
![\[執行個體組態區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_DB_instance_micro.png)

1. 在 **Storage** (儲存) 區段中，保留預設值。

1. 在 **Connectivity** (連線能力) 區段中，設定這些值，並且其他值都維持預設值：
   + 對於 **Compute resource** (運算資源)，選擇 **Connect to an EC2 compute resource** (連線至 EC2 運算資源)。
   + 對於 **EC2 instance** (EC2 執行個體)，選擇之前建立的 EC2 執行個體，例如 **tutorial-ec2-instance-web-server**。  
![\[連線能力區段\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Connectivity.png)

1. 在 **Database authentication** (資料庫身分驗證) 區段中，請確定已選取 **Password authentication** (密碼身分驗證)。

1. 在 **Additional configuration (其他設定)** 區段中，輸入 **sample** 做為 **Initial database name (初始資料庫名稱)**。其他選項都保留預設設定。

1. 若要建立 PostgreSQL 資料庫執行個體，請選擇**建立資料庫**。

   您的新資料庫執行個體會出現在 **Databases** (資料庫) 清單中，狀態為 **Creating** (建立中)。

1. 等待新資料庫執行個體的 **Status (狀態)** 顯示為 **available (可用)**。接著，選擇資料庫執行個體的名稱，以顯示其詳細資訊。

1. 在 **Connectivity & security (連線能力與安全性)** 區段中，檢視資料庫執行個體的 **Endpoint (端點)** 和 **Port (連接埠)**。  
![\[資料庫執行個體詳細資訊\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Endpoint_Port_postgres.png)

   記下資料庫執行個體的端點和連接埠。您會使用此資訊，將 Web 伺服器連接至資料庫執行個體。

1. 完成 [在您的 EC2 執行個體上安裝 Web 伺服器](CHAP_Tutorials.WebServerDB.CreateWebServer.md)。

------

# 在您的 EC2 執行個體上安裝 Web 伺服器
<a name="CHAP_Tutorials.WebServerDB.CreateWebServer"></a>

您在 EC2; 中的 Linux 執行個體上安裝 Web 伺服器[啟動 EC2 執行個體以與資料庫執行個體連線](CHAP_Tutorials.WebServerDB.LaunchEC2.md)。Web 伺服器將連接至在中建立的 Amazon RDS 資料庫執行個體 [建立 Amazon RDS 資料庫執行個體](CHAP_Tutorials.WebServerDB.CreateDBInstance.md)。

## 使用 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
   ```

   例如，假設 `ec2-database-connect-key-pair.pem` 存放在 Linux 上 的 `/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) 存取連線至 Web 伺服器的 IP 地址的規則。
**注意**  
只有當文件根目錄 `/var/www/html` 中沒有內容時，Apache 測試頁面才會出現。當您將內容新增至文件根目錄之後，您的內容會出現在 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>

接下來，您需要將內容新增至 Apache Web 伺服器 (連接到 Amazon RDS資料庫執行個體)。

**將內容新增至連接到資料庫執行個體的 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_instance_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`，以驗證 Web 伺服器是否成功連接至執行個體，例如：`http://ec2-12-345-67-890.us-west-2.compute.amazonaws.com/SamplePage.php`。

您可以使用 `SamplePage.php` 將資料新增至資料庫執行個體。您新增的資料將會顯示在頁面上。若要驗證資料是否已插入資料表中，請在 Amazon EC2 執行個體上安裝 MySQL 用戶端。然後連線至資料庫執行個體，並查詢資料表。

如需安裝 MySQL 用戶端和連接至資料庫執行個體的相關資訊，請參閱[連線至您的 MySQL 資料庫執行個體](USER_ConnectToInstance.md)。

為確保資料庫執行個體盡可能安全，請確認 VPC 以外的來源無法連線到資料庫執行個體。

測試完 Web 伺服器和資料庫之後，您應該刪除資料庫執行個體和 Amazon EC2 執行個體。
+ 若要刪除資料庫執行個體，請遵循 [刪除資料庫執行個體](USER_DeleteInstance.md) 中的指示。您不需要建立最終快照。
+ 若要終止 Amazon EC2 執行個體。請按照*《Amazon EC2 使用指南》*中[終止執行個體](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html)的指示進行操作。