LAMP(Linux Apache MySQL PHP) 환경 구축

Apache, MySQL, PHP 설치

이 문서에서는 동적인 웹 사이트 운영을 위한 기본 구성요소를 설치한다. 그러나 모든 것을 설치하지는 않는다. Wordpress 를 예시로 하여, 운영하고자 않는 웹프로그램에 맞는 서버를 구성할 것이다.

불필요한 것이 많을 수록, 서버는 무거워 지고, 보안 취약점도 늘어난다. 추후에 성능 튜닝하기에도 번거롭다. 따라서 웹서버를 구성할때에는 반드시 설치할 웹프로그램의 요구사항을 미리 확인하고, 최소 구성상태에서 시작하자.

MySQL - 가장 많이 쓰이는 오픈소스 Database

MySQL 설치와 초기 설정

먼저 MySQL을 설치 할 수 있는 검색해본다.
yum --enablerepo=remi,remi-test list mysql mysql-server
[root@db2 ~]# yum --enablerepo=remi,remi-test list mysql mysql-server
Loaded plugins: fastestmirror, presto
Loading mirror speeds from cached hostfile
Excluding mirror: mirror.khlug.org
Excluding mirror: data.nicehosting.co.kr
 * base: www.ftp.ne.jp
Excluding mirror: mirror.khlug.org
Excluding mirror: data.nicehosting.co.kr
 * extras: www.ftp.ne.jp
 * remi: iut-info.univ-reims.fr
 * remi-test: iut-info.univ-reims.fr
Excluding mirror: mirror.khlug.org
Excluding mirror: data.nicehosting.co.kr
 * updates: www.ftp.ne.jp
base                                                     | 3.7 kB     00:00
extras                                                   | 3.5 kB     00:00
remi                                                     | 2.9 kB     00:00
remi/primary_db                                          | 220 kB     00:02
remi-test                                                | 2.9 kB     00:00
remi-test/primary_db                                     |  60 kB     00:01
updates                                                  | 3.5 kB     00:00
Available Packages
mysql.x86_64                           5.5.19-1.el6.remi                    remi
mysql-server.x86_64                    5.5.19-1.el6.remi                    remi

remi Repo를 통해서 5.5.19 최신 버전을 사용할 수 있다. 이제 설치해보도록 한다.

yum --enablerepo=remi,remi-test install mysql mysql-server
[root@db2 ~]# yum --enablerepo=remi,remi-test install mysql mysql-server
Loaded plugins: fastestmirror, presto
Loading mirror speeds from cached hostfile
Excluding mirror: mirror.khlug.org
Excluding mirror: data.nicehosting.co.kr
 * base: www.ftp.ne.jp
Excluding mirror: mirror.khlug.org
Excluding mirror: data.nicehosting.co.kr
 * extras: www.ftp.ne.jp
 * remi: iut-info.univ-reims.fr
 * remi-test: iut-info.univ-reims.fr
Excluding mirror: mirror.khlug.org
Excluding mirror: data.nicehosting.co.kr
 * updates: www.ftp.ne.jp
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package mysql.x86_64 0:5.5.19-1.el6.remi will be installed

... 중략 ...

warning: rpmts_HdrFromFdno: Header V3 DSA/SHA1 Signature, key ID 00f97f56: NOKEY
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi
Importing GPG key 0x00F97F56:
 Userid : Remi Collet <RPMS@FamilleCollet.com>
 Package: remi-release-6-1.el6.remi.noarch (installed)
 From   : /etc/pki/rpm-gpg/RPM-GPG-KEY-remi
Is this ok [y/N]: y
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Warning: RPMDB altered outside of yum.
** Found 1 pre-existing rpmdb problem(s), 'yum check' output follows:
kernel-2.6.32-220.el6.x86_64 has missing requires of kernel-firmware >= ('0', '2.6.32', '220.el6')
  Installing : mysql-libs-5.5.19-1.el6.remi.x86_64                         1/12

WARNING : This MySQL RPM is not an official Fedora/Redhat build and it
overrides the official one. Don't file bugs on Fedora Project nor Redhat.
Use dedicated forums http://forums.famillecollet.com/

  Installing : 1:perl-Pod-Escapes-1.04-119.el6_1.1.x86_64                  2/12
  Installing : 1:perl-Module-Pluggable-3.90-119.el6_1.1.x86_64             3/12
  Installing : 1:perl-Pod-Simple-3.13-119.el6_1.1.x86_64                   4/12
  Installing : 4:perl-libs-5.10.1-119.el6_1.1.x86_64                       5/12
  Installing : 3:perl-version-0.77-119.el6_1.1.x86_64                      6/12
  Installing : 4:perl-5.10.1-119.el6_1.1.x86_64                            7/12
  Installing : perl-DBI-1.609-4.el6.x86_64                                 8/12
  Installing : mysql-5.5.19-1.el6.remi.x86_64                              9/12
  Installing : compat-mysql51-5.1.54-1.el6.remi.x86_64                    10/12
  Installing : perl-DBD-MySQL-4.013-3.el6.x86_64                          11/12
  Installing : mysql-server-5.5.19-1.el6.remi.x86_64                      12/12

Installed:
  mysql.x86_64 0:5.5.19-1.el6.remi    mysql-server.x86_64 0:5.5.19-1.el6.remi

Dependency Installed:
  compat-mysql51.x86_64 0:5.1.54-1.el6.remi
  mysql-libs.x86_64 0:5.5.19-1.el6.remi
  perl.x86_64 4:5.10.1-119.el6_1.1
  perl-DBD-MySQL.x86_64 0:4.013-3.el6
  perl-DBI.x86_64 0:1.609-4.el6
  perl-Module-Pluggable.x86_64 1:3.90-119.el6_1.1
  perl-Pod-Escapes.x86_64 1:1.04-119.el6_1.1
  perl-Pod-Simple.x86_64 1:3.13-119.el6_1.1
  perl-libs.x86_64 4:5.10.1-119.el6_1.1
  perl-version.x86_64 3:0.77-119.el6_1.1

Complete!

설치가 되었지만 몇가지 설정해주어야 할 것이 있다.

[root@db2 ~]# /etc/init.d/mysqld start
Initializing MySQL database:  Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h db2.i-pharm.org password 'new-password'

Alternatively you can run:
/usr/bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd /usr/mysql-test ; perl mysql-test-run.pl

Please report any problems with the /usr/bin/mysqlbug script!

                                                           [  OK  ]
Starting mysqld:                                           [  OK  ]

[root@db2 ~]#

mysql을 실행하면 별다른 인증과정 없이 접속할 수 있다.

mysql 데이타베이스의 root 계정은 리눅스 운영체제의 root 계정과는 별도의 비밀번호이다.

[root@db2 ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.19 MySQL Community Server (GPL) by Remi

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> Bye

암호 입력없이 그냥 접속이 되는 것인 상당히 위험하므로, 반드시 암호를 설정한다.

작은따옴표도 입력해야 한다.

[root@db2 ~]# /usr/bin/mysqladmin -u root password '암호'


[root@db2 ~]# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)


[root@db2 ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.5.19 MySQL Community Server (GPL) by Remi

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> Bye

mysql_secure_installation 명령을 이용하면 더 간단히 설정할 수 도 있다.

[root@db2 ~]# /usr/bin/mysql_secure_installation




NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!


In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, 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 MySQL
root user without the proper authorisation.

You already have a root password set, so you can safely answer 'n'.

Change the root password? [Y/n] n
 ... skipping.

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL 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
 ... Success!

By default, MySQL 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
 - 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 MySQL
installation should now be secure.

Thanks for using MySQL!

Database 생성 및 사용자 생성

새로운 사용자 생성

CREATE USER wordpress@localhost IDENTIFIED BY "some_good_password_for_wordpress";

새로운 데이타베이스 생성

CREATE DATABASE wordpress_blog;

필요한 권한 설정

GRANT ALL ON wordpress_blog.* TO wordpress@localhost;

권한 설정 적용

FLUSH PRIVILEGES;

Apache, PHP 설치

패키지 설치 및 초기설정

yum --enablerepo=remi install httpd php php-common php-pear php-pdo php-mysql php-gd php-mbstring php-mcrypt php-xml
-------------------- 
설치 화면 들어가야함
--------------------

우선 PHP가 동작하지는 확인한다.

/var/www/html/test.php
<?php
phpinfo();
?>

http://localhost/test.php 에 접속해서 다음과 같이 나오면, 정상이다.

phpinfo-5.3.6

PHP 동작을 확인하였으니, 이제 PHP로 작성된 프로그램을 웹서버해서 실행할 수 있는 준비가 된것이다. 웹서버에서 프로그램 관리가 좀 더 수월하기 위해 별도의 설정파일을 추가하여 설정하자.

Wordpress 용 설정파일 추가

/etc/httpd/conf.d/wordpress.conf
<VirtualHost *:80>
  ServerAdmin test@crystaljjun.kr
  DocumentRoot /var/www/html/wordpress
  ServerName crystaljjun.kr
 
  # Logging
  ErrorLog /var/log/httpd/wordpress-error-log
  CustomLog /var/log/httpd/wordpress-acces-log common
</VirtualHost>

추가한 설정파일을 적용하기 위해서 httpd 를 재시작한다.

service httpd restart
또는
/etc/init.d/httpd restart
이제 Wordpress를 설치하도록 하자. 최신 버전인 3.3.1을 http://wordpress.org/download/ 에서 다운로드 한다.
wget http://wordpress.org/latest.tar.gz

해킹에 악용될 수 있는 버전 정보를 감추도록 설정한다.

웹서버 버전 정보가 표시되지 않게 한다.

vi /etc/httpd/conf/httpd.conf
ServerTokens Prod
ServerSignature Off

PHP에서 버전정보가 표시되지 않게 한다.

vi /etc/php.ini
expose_php = Off

expose-php-before-after-thumb-485x145

참고자료 : http://mark.koli.ch/2009/04/howto-set-expose-phpoff-in-phpini-to-hide-php-version-in-http-headers.html

PhpSecInfo :

http://phpsec.org/projects/phpsecinfo/index.html

유용한 설정

cronolog를 설치하고, 로그를 일일 또는 월단위로 저장되게 설정하면 로그파일 관리하기가 편리해진다. 
또한 log파일이 비대해져서 시스템에 영향을 미칠때 손쉽게 오래된 일자의 file만 처리하면 된다.
일별로 로그 저장
CustomLog "|/usr/sbin/cronolog /var/log/apache2/access_log_%Y%m%d" combined
ErrorLog "|/usr/sbin/cronolog /var/log/apache2/error_log_%Y%m%d"

월별로 로그 저장
CustomLog "|/usr/sbin/cronolog /var/log/apache2/access_log_%Y%m" combined
ErrorLog "|/usr/sbin/cronolog /var/log/apache2/error_log_%Y%m"