EC2(amazon-linux)와 DB 데이터베이스(mysql)에 연결

Jh Park·2022년 11월 9일

RK - 컨설팅 실무

목록 보기
2/4

https://docs.aws.amazon.com/ko_kr/AmazonRDS/latest/UserGuide/TUT_WebAppWithRDS.html

구축

코드

[ webserver 구축 ]
sudo su
yum update -y
amazon-linux-extras install php8.0 mariadb10.5
cat /etc/system-releas
yum install -y httpd
systemctl start httpd
systemctl enable httpd
usermod -a -G apache ec2-user
exit

groups
=> ec2-user adm wheel apache systemd-journal
sudo chown -R ec2-user:apache /var/www
sudo chmod 2775 /var/www
find /var/www -type d -exec sudo chmod 2775 {} \;
find /var/www -type f -exec sudo chmod 0664 {} \;

[DB 서버에 접속]
sudo mysql -h [RDS 엔드포인트] -u admin[생성시 id] -p 
create database sample

[DB 서버와의 연결 ]
cd /var/www
mkdir inc
ls
cd inc
sudo vi dbinfo.inc
cd /var/www/html
vi SamplePage.php
  • dbinfo.inc
<?php
define('DB_SERVER', 'db_instance_endpoint');
define('DB_USERNAME', 'tutorial_user');
define('DB_PASSWORD', 'master password');
define('DB_DATABASE', 'sample');
?>             
  • SamplePage.php
<?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;
}
?>    

설명

[ webserver 구축 ]

  • amazon-linux-extras install php8.0 mariadb10.5
    • cat /etc/system-releas
    • Amazon Linux 버전확인
  • yum install -y httpd
    • httpd설치
  • systemctl start httpd
    • httpd시작
  • systemctl enable httpd
    • 웹 서버가 시스템 부팅 때마다 httpd가 시작되도록 구성
  • usermod -a -G apache ec2-user
    • ec2-user 사용자를 apache 그룹에 추가
  • exit
    • 변경한 세팅을 적용하기 위해 재접속
  • groups
    • 사용자가 포함된 그룹 확인
    • ec2-user adm wheel apache systemd-journal
  • sudo chown -R ec2-user:apache /var/www
    • /var/www 디렉터리 및 해당 콘텐츠의 그룹 소유권을 apache 그룹으로 변경
  • sudo chmod 2775 /var/www
    • /var/www 및 그 하위 디렉터리의 디렉터리 권한을 변경해서 그룹 쓰기 권한을 추가
  • find /var/www -type d -exec sudo chmod 2775 {} \;
    • 나중에 생성될 하위 디렉터리에서 그룹 ID를 설정
  • find /var/www -type f -exec sudo chmod 0664 {} \;
    • /var/www 디렉터리 및 하위 디렉터리의 파일 권한을 계속 변경해서 그룹 쓰기 권한을 추가

0개의 댓글