/* ========================================================
NAME : Linux_Centos_APM_Install
DATE : 2019.02.05
E-MAIL : rf114@daum.net
URL : http://www.rf114.com

[LISENCE]
This program is free web source from RF114.com
This is not commercial lisence and as modify as possiable
to this contents include.
[SITE]
https://aeac.tistory.com/21
======================================================== */
방화벽
----------------------------------------------------------- 

/etc/firewalld/zones/public.xml 

<?xml version="1.0" encoding="utf-8"?>

<zone>
  <short>Public</short>
  <description>For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accept
ed.</description>
  <service name="dhcpv6-client"/>
  <service name="http"/>
  <service name="ssh"/>
  <service name="https"/>
</zone>

firewall-cmd --reload

-----------------------------------------------------------
■ [APM] Apache, PHP7, MariaDB 10.1 Install(설치) Guide
-----------------------------------------------------------
1. 의존성 라이브러리 설치
-----------------------------------------------------------
□ 아래는 라이브러리가 설치되어있는지 확인해보는 부분이며 APM에 꼭 필요한 패키지가 있습니다.
-----------------------------------------------------------
[root@localhost ~]# rpm -qa libjpeg* libpng* freetype* gd-* gcc gcc-c++ gdbm-devel libtermcap-devel
libpng-1.5.13-7.el7_2.x86_64
gcc-c++-4.8.5-11.el7.x86_64
freetype-2.4.11-12.el7.x86_64
libjpeg-turbo-1.2.90-5.el7.x86_64
libpng12-1.2.50-10.el7.x86_64
gcc-4.8.5-11.el7.x86_64

-----------------------------------------------------------
□ Yum 으로 아래의 필요한 라이브러리를 한번에 전부 설치합니다.
   (한번에 관련된 의존성도 같이 설치가 됩니다.)
-----------------------------------------------------------
[root@localhost ~]# yum install libjpeg* libpng* freetype* gd-* gcc gcc-c++ gdbm-devel libtermcap-devel

-----------------------------------------------------------
2. [APM] Apache, PHP, MariaDB 설치 [순서는 : Apache, Maria, PHP 진행]
-----------------------------------------------------------
□ 아파치(Apache 2.4) 설치
-----------------------------------------------------------
[root@localhost ~]# yum install httpd

- 마리아(Maria DB 10.1) 설치
- 배포사이트 : http://mariadb.org/
- 버전별 셋팅방법 : http://downloads.mariadb.org/mariadb/repositories/
- 먼저 Yum 저장소 생성
[root@localhost ~]# vi /etc/yum.repos.d/MariaDB.repo

# MariaDB 10.1 CentOS repository list 
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
:wq (저장)

[root@localhost ~]# yum install MariaDB-server MariaDB-client

-----------------------------------------------------------
□ PHP 7 설치
-----------------------------------------------------------
먼저 Yum 저장소 생성
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

-----------------------------------------------------------
□ 이후 설치
-----------------------------------------------------------
yum install php70w

-----------------------------------------------------------
□ 관련 PHP7 패키지 설치 (자주 쓰이는것을 골라봤습니다.)
-----------------------------------------------------------
[root@localhost ~]# yum install php70w-mysql php70w-pdo php70w-pgsql php70w-odbc php70w-mbstring php70w-mcrypt php70w-gd
[root@localhost ~]# yum install php70w-pear php70w-pdo_dblib php70w-pecl-imagick php70w-pecl-imagick-devel php70w-xml php70w-xmlrpc

다음 명령어로 php7 관련 패키지 설치할수 있는 리스트들을 확인할수 있습니다. 
위 설치외에 필요한 패키지가 있다면 추가로 설치하면 됩니다.
yum search php70w

-----------------------------------------------------------
□ 설치 확인 및 버전확인
-----------------------------------------------------------
httpd -v
mysql -V
 
-----------------------------------------------------------
■ [APM] Apache, PHP, MariaDB config(설정) 및 구동
-----------------------------------------------------------
1. 아파치(Apache) 설정 및 구동
-----------------------------------------------------------
□ 기본설정
-----------------------------------------------------------
[root@localhost ~]# vi /etc/httpd/conf/httpd.conf
.
.
     62 # User/Group: The name (or #number) of the user/group to run httpd as.
     63 # It is usually good practice to create a dedicated user and group for
     64 # running httpd, as with most system services.
     65 #
     66 User nobody      (apache → nobody 변경)
     67 Group nobody     (apache → nobody 변경)
.
.
     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 192.168.122.128:80   (도메인 또는 해당서버 IP 입력 추가)
.
.
:wq (저장)

[참고]
■ apache → nobody 변경
ROOT 권한으로 실행된 아파치의 하위 프로세스를 이곳에서 지정한 사용자로 실행한다는 의미, 
기본값으로 apache 또는 daemon 으로 되어있지만 대부분 nobody로 변경하여 이용한다. 약간 보안적인 의미를 포함

■ ServerName
자기 서버가 이 도메인을 사용한다는것을 알리기 위한 수단, 예를 들어
ServerName www.test.com:80 → 홈페이지 접속시 해당 도메인(http://www.test.com)으로 연결
ServerName 192.168.122.128:80 → 홈페이지 접속시 해당 도메인((http://192.168.122.128)으로 연결 (도메인이 없을경우 IP 입력)

■ IP는 자기서버 IP 셋팅
[root@localhost ~]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.223.129 (이부분)  netmask 255.255.255.0  broadcast 192.168.223.255
-----------------------------------------------------------
□ 방화벽 설정
-----------------------------------------------------------
; 환경설정이 완료가 되었으니 웹을 열기위해선 방화벽 80번 포트를 오픈해야합니다.
; [root@localhost ~]# vi /etc/sysconfig/iptables

# sample configuration for iptables service
# you can edit this manually or use system-config-firewall
# please do not ask us to add additional ports/services to this default configuration
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 81 -j ACCEPT (추가)
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
:wq (저장)

[참고]
■ iptables 에서 순서는 매우 중요합니다. 일반적으로 적용되는 순서는 위에서부터 아래로 순차적으로 읽어옵니다.
예를들어 추가한 맨 아래의 라인쪽에 추가를 하게되면 적용이 정상적으로 안됩니다.
이해가 안되실경우는 스크린샷 그대로 따라진행해주세요. 나중에 별도로 iptables 설명을 하도록 하겠습니다.
-----------------------------------------------------------
□ 방화벽 재시작
-----------------------------------------------------------
; [root@localhost ~]# service iptables restart
; Redirecting to /bin/systemctl restart  iptables.service

-----------------------------------------------------------
□ 적용 확인
-----------------------------------------------------------
; iptables -vnL
[root@localhost ~]# iptables -nL

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            state NEW tcp dpt:22
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            state NEW tcp dpt:80  (확인완료)
REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination  

-----------------------------------------------------------
□ 아파치 시작
-----------------------------------------------------------
[root@localhost ~]# systemctl start httpd

-----------------------------------------------------------
□ 부팅후 자동 실행 설정
-----------------------------------------------------------
[root@localhost ~]# systemctl enable httpd
Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.

-----------------------------------------------------------
□ 부팅후 자동 실행 설정(해제)
-----------------------------------------------------------
[root@localhost ~]# systemctl disable httpd
Removed symlink /etc/systemd/system/multi-user.target.wants/httpd.service.

-----------------------------------------------------------
□ Service 명령어 이용 가능
-----------------------------------------------------------
[root@localhost ~]# service httpd start(stop)

-----------------------------------------------------------
□ 아파치 구동 확인
-----------------------------------------------------------
[root@localhost ~]# ps -ef  | grep httpd
root      17652      1  0 13:46 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    17654  17652  0 13:46 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    17655  17652  0 13:46 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    17656  17652  0 13:46 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    17657  17652  0 13:46 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    17658  17652  0 13:46 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
root      17715   2983  0 13:51 pts/1    00:00:00 grep --color=auto httpd

-----------------------------------------------------------
2. PHP 환경설정 및 구동(경로)
-----------------------------------------------------------
□ 기본설정
-----------------------------------------------------------
[root@localhost ~]# 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>
.
.
    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  (추가)
:wq (저장)

[참고]
■ 실제 PHP환경설정을 관리하는 파일은 아래의 경로입니다.

[root@localhost ~]# vi /etc/php.ini

위 httpd.conf 쪽에 셋팅하는건 아파치에 php 관련 처리를 할수 있게 추가를 하는 부분입니다. 
php.ini 파일설정은 사용할려는 웹환경에 맞게튜닝을 해야하지만 현재는 기본셋팅으로 갑니다.
 나중에 따로 설명하도록 하겠습니다.

-----------------------------------------------------------
□ PHP 적용
-----------------------------------------------------------
- Yum 설치시 html 업로드 기본 디렉토리는 아래와 같습니다.
[root@localhost ~]# cd /var/www/html/

- 해당 경로에서 PHP의 정보를 보여주는 함수의 파일을 하나 생성합니다.
[root@localhost html]# vi /var/www/html/phpinfo.php

<?php phpinfo(); ?>
:wq (저장)

[root@localhost html]# ls  (파일생성 확인)
phpinfo.php

- PHP 환경설정을 적용하기위해 아파치(Apache)도 한번 재시작을 합니다.
[root@localhost html]# service httpd restart
Redirecting to /bin/systemctl restart  httpd.service

- 항상 아파치(Apache) 구동이 제대로 되고 있는지 확인합니다.
[root@localhost html]# ps -ef | grep httpd
root      18135      1  0 16:57 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    18137  18135  0 16:57 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    18138  18135  0 16:57 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    18139  18135  0 16:57 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    18140  18135  0 16:57 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    18141  18135  0 16:57 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
root      18143   2983  0 16:58 pts/1    00:00:00 grep --color=auto httpd

-----------------------------------------------------------
□ PHP 적용 확인 테스트
-----------------------------------------------------------
URL : http://192.168.223.129/phpinfo.php

-----------------------------------------------------------
3. Maria DB 구동 및 설정
-----------------------------------------------------------
□ Maria DB 구동 및 구동 확인
-----------------------------------------------------------
[root@localhost ~]# systemctl start mariadb
[root@localhost ~]# ps -ef | grep mysql
mysql     41093      1  1 19:48 ?        00:00:00 /usr/sbin/mysqld
root      41130  11663  0 19:49 pts/1    00:00:00 grep --color=auto mysql

-----------------------------------------------------------
□ Maria DB 기본설정 (DB가 구동된 상태에서 진행가능)
-----------------------------------------------------------
[root@localhost ~]# 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): 패스워드가 없기때문에 엔터

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  (익명의 접근을 막을것인지? 보안을 위해 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 원격을 막을것인지? 보안을 위해 Y 엔터)

 ... 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 용으로 생성된 데이터베이스를 삭제할것인가? Y 엔터)

 - 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 (현재 설정한 값을 적용할것인지? 당연히 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! (끝)

-----------------------------------------------------------
□ Maria DB 최종 접속 확인
-----------------------------------------------------------
[root@localhost ~]# mysql -u root -p
Enter password: 패스워드 입력  

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 10.1.21-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

[참고]
Maria(Mysql) 환경설정을 관리하는 파일은 아래의 경로입니다.
[root@localhost ~]# vi /etc/my.cnf

my.cnf 파일설정은 사용할려는 DB환경에 맞게 튜닝을 해야하지만 현재는 기본셋팅으로 갑니다. 
나중에 따로 설명하도록 하겠습니다.

-----------------------------------------------------------
 root 패스워드 변경
-----------------------------------------------------------
1. 쿼리를 사용한 방법

update mysql.user set password = password('패스워드') where user ='아이디' and host = '%'; 
flush privileges;
 
update mysql.user set password = password('root') where user = 'root' and host='%';
flush privileges;
 
set password for '아이디'@'%' = password('패스워드');
 
set password for 'root'@'%' = password('root');

grant usage on *.* to '아이디'@'%' identified by '패스워드';
grant usage on *.* to 'root'@'%' identified by 'root';

2. 커맨드를 사용한 방법

mysqladmin -uroot -p password ekdnjs@ekdnjs
