Ossian Story
article thumbnail


[WEB & WAS] Web Server 구축하기

(Apache & PHP & MariaDB)



WEB & DB Server 구성


WEB Server에는 Apache & PHP, DB Server에는 MariaDB로 구성하여 WEB Server와 DB Server를 나눈 형태로 구성합니다.





Apache (Web Server) 설치 및 환경설정


Yum을 통해 Apache를 설치합니다.

 - yum install -y httpd


[root@webserver ~]# yum install -y httpd
 
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
epel/x86_64/metalink                                                                          |  11 kB  00:00:00
 * base: repo1.sea.innoscale.net
 * epel: mirrors.cat.pdx.edu
 * extras: mirror.rackspace.com
 * updates: mirror.scalabledns.com
base                                                                                          | 3.6 kB  00:00:00
epel                                                                                          | 3.2 kB  00:00:00
...
Installed:
  httpd.x86_64 0:2.4.6-80.el7.centos.1
 
Dependency Installed:
  apr.x86_64 0:1.4.8-3.el7_4.1      apr-util.x86_64 0:1.5.2-6.el7     httpd-tools.x86_64 0:2.4.6-80.el7.centos.1
  mailcap.noarch 0:2.1.41-2.el7
 
Complete!




Apache 설치 완료 후 아래의 경로에서 Apache의 기본 설정을 변경합니다.

 - vi /etc/httpd/conf/httpd.conf


64 # running httpd, as with most system services.
65 #
66 User nobody   (apache > nobody로 변경)
67 Group nobody  (apache > nobody로 변경)
68
69 # 'Main' server configuration
70 #
....
93 # If your host doesn't have a registered DNS name, enter its IP address here.
94 #
95 #ServerName www.example.com:80
96 ServerName 10.146.0.7 (도메인 또는 Web Server IP 추가)



◆ apach > nobody로 변경

Apache 운영 시 보안요소를 강화하기 위해 최소 권한의 사용자ID와 그룹을 생성하는 것이 안전합니다.

대부분 이러한 경우에 "nobody"를 사용하며 인터렉티브한 로그인을 허락하지 않도록 설정합니다.

해당 값을 "nobody"로 설정할 경우 Root 권한으로 실행된 Apache의 하위 프로세스 실행을 해당 위치에서 지정한 사용자로 실행한다는 의미입니다.


◆ ServerName

Web Server가 해당 도메인 또는 IP를 사용한다는 것을 설정합니다.

만약 해당 항목을 설정하지 않으면 127.0.0.1로만 접속 됩니다.



기본 설정 완료 후 Apache 서비스를 시작합니다.

[root@webserver ~]# systemctl restart httpd
 
[root@webserver ~]# ps -ef | grep httpd
root     14495     1  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14496 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14497 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14499 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14500 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14502 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14503 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14504 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14505 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14506 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
nobody   14507 14495  0 07:13 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
root     14516  1123  0 07:13 pts/0    00:00:00 grep --color=auto httpd




Web browser에서 Web Server로 접근 가능한 IP로 접근할 경우 아래와 같이 Apache 서비스가 정상적으로 실행된 것을 확인할 수 있습니다.

 - 저의 테스트 환경에서는 CentOS의 방화벽(Firewall & iptables)서비스는 종료된 상태로 진행하였습니다.





PHP (Web Server) 설치 및 환경설정


Yum을 통해 php를 설치합니다.

 - yum install -y php php-mysql php-mbstring php-pdo php-gd


[root@webserver ~]# yum install -y php php-mysql php-mbstring php-pdo php-gd
 
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
....
Installed:
  php.x86_64 0:5.4.16-45.el7            php-gd.x86_64 0:5.4.16-45.el7       php-mbstring.x86_64 0:5.4.16-45.el7
  php-mysql.x86_64 0:5.4.16-45.el7      php-pdo.x86_64 0:5.4.16-45.el7
 
Dependency Installed:
  libX11.x86_64 0:1.6.5-1.el7            libX11-common.noarch 0:1.6.5-1.el7       libXau.x86_64 0:1.0.8-2.1.el7
  libXpm.x86_64 0:3.5.12-1.el7           libjpeg-turbo.x86_64 0:1.2.90-5.el7      libpng.x86_64 2:1.5.13-7.el7_2
  libxcb.x86_64 0:1.12-1.el7             libzip.x86_64 0:0.10.1-8.el7             php-cli.x86_64 0:5.4.16-45.el7
  php-common.x86_64 0:5.4.16-45.el7      t1lib.x86_64 0:5.1.2-14.el7
 
Complete!




php 설치 완료 후 아래의 경로에서 php의 기본 설정을 변경합니다.

 - vi /etc/httpd/conf/httpd.conf


[root@webserver ~]# vi /etc/httpd/conf/httpd.conf
 
161 # DirectoryIndex: sets the file that Apache will serve if a directory
162 # is requested.
163 #
164 <IfModule dir_module>
165     DirectoryIndex index.html index.htm index.php         (추가)
166 </IfModule>
167
168 #
....
270     # AddType allows you to add to or override the MIME configuration
271     # file specified in TypesConfig for specific file types.
272     #
273     #AddType application/x-gzip .tgz
274     AddType application/x-httpd-php .php .html .htm .inc   (추가)
275     AddType application/x-httpd-php-source .phps           (추가)




php 기본 설정 완료 후 테스트를 위하여 아래와 같은 경로에 파일을 생성 후 Apache 서비스를 재시작 합니다.


[root@webserver ~]# vi /var/www/html/phpinfo.php
 
# phpinfo.php 파일 내용
 
<?php phpinfo(); ?>
 
# Apache 서비스 재시작
systemctl restart httpd




Web Browser에서 "http://[Web-Server IP]/phpinfo.php"의 경로로 접속할 경우 PHP Version 정보가 표기된다면 정상적으로 구동된 것입니다.




MariaDB (DB Server) 설치 및 환경설정


Yum을 통해 MariaDB를 설치합니다.

 - yum install -y mariadb mariadb-server


[root@dbserver ~]# yum install -y mariadb mariadb-server
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.jaist.ac.jp
...
Installed:
  mariadb.x86_64 1:5.5.56-2.el7                         mariadb-server.x86_64 1:5.5.56-2.el7
 
Dependency Installed:
  libaio.x86_64 0:0.3.109-13.el7                           perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7
  perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7              perl-DBD-MySQL.x86_64 0:4.023-6.el7
  perl-DBI.x86_64 0:1.627-4.el7                            perl-Data-Dumper.x86_64 0:2.145-3.el7
  perl-IO-Compress.noarch 0:2.061-2.el7                    perl-Net-Daemon.noarch 0:0.48-5.el7
  perl-PlRPC.noarch 0:0.2020-14.el7
 
Complete!




MariaDB 설치 후 서비스 시작 및 초기 설정을 진행합니다.

- systemctl restart mariadb

- mysql_secure_installation


[root@dbserver ~]# systemctl restart mariadb
 
[root@dbserver ~]# mysql_secure_installation
 
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
 
In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.'
 
Enter current password for root (enter for none):    # 초기 패스워드가 없으므로 enter 입력
OK, successfully used password, moving on...
 
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
 
Set root password? [Y/n] y      # DB Root 패스워드 설정
New password:                    # 패스워드 입력
Re-enter new password:            # 패스워드 재 입력
Password updated successfully!
Reloading privilege tables..
 ... Success!
 
 
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.
 
Remove anonymous users? [Y/n] y    # 익명 사용자의 접근을 막을 것인지? 보안을 위해 막는 것을 권고
 ... Success!
 
Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.
 
Disallow root login remotely? [Y/n] y    # DB Root User의 원격접속을 막을 것인지? 보안을 위해 막는 것을 권고
 ... Success!
 
By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.
 
Remove test database and access to it? [Y/n] y    # Test로 생성된 데이터 베이스를 삭제할 것인지?
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!
 
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
 
Reload privilege tables now? [Y/n] y    # 현재 설정한 값을 적용할 것인지?
 ... Success!
 
Cleaning up...
 
All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!'




아래의 명령어로 MariaDB에 접근이 잘 된다면 정상적으로 설치가 완료된 것입니다.


[root@dbserver ~]# mysql -u root -p
 
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 5.5.56-MariaDB MariaDB Server
 
Copyright (c) 20002017, Oracle, MariaDB Corporation Ab and others.
 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)
 
MariaDB [(none)]>




MariaDB Database 생성 및 원격설정


사용할 데이터베이스를 생성합니다.

 - create database [Database Name];


MariaDB [(none)]> create database infra_account;
Query OK, 1 row affected (0.00 sec)
 
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| infra_account      |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)




생성된 데이터베이스 선택 및 계정 생성 & 데이터베이스 사용 권한을 부여합니다.


# mysql Database 선택
MariaDB [mysql]> use mysql;
Database changed
 
# 계정 생성
MariaDB [mysql]> create user '[계정명]'@'%' identified by '[비밀번호]';
Query OK, 0 rows affected (0.00 sec)
 
 
# 생성된 데이터베이스에 접근권한 부여
MariaDB [mysql]> grant all privileges on [데이터베이스명].* to '[계정명]'@'%';
Query OK, 0 rows affected (0.00 sec)
 
 
# 계정의 접근권한 확인
MariaDB [mysql]> show grants for 'infra_admin'@'%';
+------------------------------------------------------------------------------------------------------------+
| Grants for infra_admin@%                                                                                   |
+------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'infra_admin'@'%' IDENTIFIED BY PASSWORD '*994FC172DB76E7D5C7486EAF7907B6E5B54EEF3B' |
| GRANT ALL PRIVILEGES ON `infra_account`.* TO 'infra_admin'@'%'                                             |
+------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)
 
# 변경사항 저장 및 반영
MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)




신규로 생성된 계정으로 접속이 잘 되는지 확인합니다.


MariaDB [mysql]> exit
Bye
[root@dbserver ~]# mysql -u infra_admin -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 5.5.56-MariaDB MariaDB Server
 
Copyright (c) 20002017, Oracle, MariaDB Corporation Ab and others.
 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 
MariaDB [(none)]>




mysql port(3306)가 Listen 상태인지 확인합니다.


[root@infra-db ~]# netstat -anpt | grep 3306
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      1510/mysqld




WEB Server에서 Telnet을 통해 DB Server의 3306 Port로 접근이 가능한지 확인합니다.


[root@webserver ~]# telnet 10.146.0.8 3306
Trying 10.146.0.8...
Connected to 10.146.0.8.
Escape character is '^]'.
R
5.5.56-MariaDB'6wvk9u▒wJL{I9"?Sd}gmysql_native_password





Web Server & DB Server PHP를 통한 Mariadb 연결


Web Server의 "/var/www/html/config.php" 경로에 아래와 같은 DB Connection Config php 파일을 생성합니다.


[root@webserver ~]# vi /var/www/html/config.php
 
 
<?php
$mysql_hostname = '[DB Server IP Address or DomainName]';
$mysql_username = '[DB 계정명]';
$mysql_password = '[DB 계정의 비밀번호]';
$mysql_database = '[접근할 데이터베이스명]';
$mysql_port = '3306';
$mysql_charset = 'utf8';
 
 
//1. DB 연결
$connect = mysqli_connect($mysql_hostname, $mysql_username, $mysql_password, $mysql_database);
mysqli_select_db($connect, $mysql_database) or die('DB 선택 실패');
?>




Web Browser에서 "http://[Web-Server IP]/config.php"의 경로로 접속할 경우 빈 페이지가 보인다면 Web Server & DB Server간의 PHP를 통한 DB Connection이 정상적으로 완료된 것입니다.




만약 아래와 같이 에러메시지가 발생될 경우 아래의 사항을 확인합니다.

 - Web Server & DB Server의 SELINUX가 Disabled 되어있는지 확인합니다.

 - Config.php 파일의 계정 또는 Database등의 정보가 잘 입력되었는지 확인합니다.





profile

Ossian Story

@ossians