Hướng dẫn cài đặt Nginx với PHP5, PHP–FPM và MySQL trên CentOS 6.0

Quản Trị Mạng - Trong bài viết dưới đây, chúng tôi sẽ hướng dẫn các bạn cách cài đặt Nginx - thường gọi là engine x, đây là 1 hệ thống server HTTP mã nguồn mở, hoàn toàn miễn phí, hiệu suất hoạt động cao, độ ổn định cao, tổ hợp chức năng đa dạng, dễ dàng cấu hình, thiết lập và sử dụng ít tài nguyên hệ thống. Cụ thể, chúng ta sẽ cùng nhau tiến hành cài đặt Nginx trên server CentOS 6.0 với PHP5 hỗ trợ qua PHP – FPM và MySQL.

Trong bài thử nghiệm này, chúng ta sẽ dùng hostname server1.example.com với địa chỉ IP 192.168.0.100, tùy từng hệ thống khác nhau các bạn hãy thay đổi thông số kỹ thuật sao cho phù hợp. Bên cạnh đó, php-fpm không có sẵn trên repository chính thức của CentOS, nhưng lại có trên Remi RPM với cơ chế phụ thuộc vào EPEL repository, chúng ta có thể kích hoạt cả 2 repository như sau:

rpm --import https://fedoraproject.org/static/0608B895.txt
rpm -ivh http://download.fedora.redhat.com/pub/epel/6/i386/epel-release-6-5.noarch.rpm

rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

yum install yum-priorities

Sau đó, chỉnh sửa /etc/yum.repos.d/epel.repo...

vi /etc/yum.repos.d/epel.repo

Và thêm dòng priority=10 vào phần [epel]:

[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
priority=10
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
[…]

Làm tương tự như vậy với phần [remi] trong /etc/yum.repos.d/remi.repo, và thay đổi enabled thành 1:

vi /etc/yum.repos.d/remi.repo

[remi]
name=Les RPM de remi pour Enterprise Linux $releasever - $basearch
#baseurl=http://rpms.famillecollet.com/enterprise/$releasever/remi/$basearch/
mirrorlist=http://rpms.famillecollet.com/enterprise/$releasever/remi/mirror
enabled=1
priority=10
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi
failovermethod=priority

[remi-test]
name=Les RPM de remi en test pour Enterprise Linux $releasever - $basearch
#baseurl=http://rpms.famillecollet.com/enterprise/$releasever/test/$basearch/
mirrorlist=http://rpms.famillecollet.com/enterprise/$releasever/test/mirror
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Cài đặt MySQL 5:

Để tiến hành, chúng ta bắt đầu với câu lệnh:

yum install mysql mysql-server

Sau đó, tạo đường dẫn khởi động dành cho MySQL (và MySQL sẽ tự khởi động mỗi khi hệ thống hoạt động), đồng thời kích hoạt MySQL server:

chkconfig --levels 235 mysqld on
/etc/init.d/mysqld start

Kiểm tra hệ thống mạng đã ở trạng thái kích hoạt hay chưa, sử dụng lệnh:

netstat -tap | grep mysql

Và hệ thống của bạn sẽ hiển thị kết quả tương tự như dưới đây:

[root@server1 ~]# netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 2302/mysqld
[root@server1 ~]#

Nếu không, hãy chỉnh sửa file /etc/my.cnf và thêm chú thích tai phần skip-networking:

vi /etc/my.cnf

[...]
#skip-networking
[...]

Sau đó khởi động lại MySQL server:

/etc/init.d/mysqld restart

Chạy lệnh:

mysql_secure_installation

để khởi tạo mật khẩu cho tài khoản root (nếu không thì bất ai cũng có thể truy cập và sử dụng cơ sở dữ liệu MySQL):

[root@server1 ~]# 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): <-- nhấn ENTER
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] <-- nhấn ENTER
New password: <-- mật khẩu tài khoản root
Re-enter new password: <-- mật khẩu tài khoản root
Password updated successfully!
Reloading privilege tables..
... Success!


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] <-- nhấn ENTER
... 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] <-- nhấn ENTER
... 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] <-- nhấn ENTER
- 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] <-- nhấn ENTER
... 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!


[root@server1 ~]#


Cài đặt Nginx:

Về mặt kỹ thuật, Nginx đã có sẵn dưới dạng gói cài đặt – package dành cho CentOS 6.0 (từ EPEL) có thể được cài đặt như sau:

yum install nginx

Tiếp tục, tạo đường dẫn khởi động cho nginx và kích hoạt dịch vụ đi kèm:

chkconfig --levels 235 nginx on
/etc/init.d/nginx start

Sau đó, gõ địa chỉ IP của web server vào trình duyệt (ví dụ http://192.168.0.100), và chúng ta sẽ nhìn thấy màn hình hiển thị tương tự như dưới đây:

Cài đặt PHP5:

Về mặt bản chất, chúng ta có thể làm cho PHP5 hoạt động trong nginx qua PHP – FPM - FastCGI Process Manager, có thể thay thế chức năng của PHP FastCGI. Chúng ta có thể cài đặt php-fpm cùng với php-cli và một số module PHP5 giống như php-mysql, nếu người dùng muốn sử dụng MySQL từ các đoạn mã PHP như sau:

yum install php-fpm php-cli php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-eaccelerator php-magickwand php-magpierss php-mbstring php-mcrypt php-mssql php-shout php-snmp php-soap php-tidy

Sau đó, mở file /etc/php.ini và thiết lập cgi.fix_pathinfo=0:

vi /etc/php.ini

[...]
; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting
; of zero causes PHP to behave as before. Default is 1. You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; http://www.php.net/manual/en/ini.core.php#ini.cgi.fix-pathinfo
cgi.fix_pathinfo=0
[...]

Để tham khảo kỹ hơn về lý do tại sao các bạn phải làm như vậy, hãy truy cập vào đây. Bên cạnh đó, để tránh khỏi các lỗi thường gặp như:

[08-Aug-2011 18:07:08] PHP Warning: phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /usr/share/nginx/html/info.php on line 2

trong /var/log/php-fpm/www-error.log khi chúng ta tiến hành gọi mã PHP trong trình duyệt, các bạn hãy thiết lập date.timezone trong file /etc/php.ini như sau:

[...]
[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = "Europe/Berlin"
[…]

Để tìm đúng thông tin về múi giờ hệ thống đang sử dụng, gõ lệnh:

cat /etc/sysconfig/clock

[root@server1 nginx]# cat /etc/sysconfig/clock
ZONE="Europe/Berlin"
[root@server1 nginx]#

Tiếp theo, tạo đường dẫn khởi động cho php-fpm và kích hoạt dịch vụ này:

chkconfig --levels 235 php-fpm on
/etc/init.d/php-fpm start

PHP-FPM là 1 tiến trình daemon (với đoạn script /etc/init.d/php-fpm) có cơ chế hoạt động cùng với FastCGI server trên cổng 9000.

Thiết lập Nginx:

File thiết lập, cấu hình chính của nginx là /etc/nginx/nginx.conf, chúng ta có thể mở bằng lệnh:

vi /etc/nginx/nginx.conf

Bản chất quá trình thiết lập này tương đối dễ hiểu (các bạn có thể tham khảo thêm tại đâyđây). Trước tiên, chúng ta có thể tăng số lượng các tiến trình xử lý và thiết lập thông số keepalive_timeout về 1 giá trị phù hợp:

[...]
worker_processes 5;
[...]
keepalive_timeout 2;
[...]

Còn các virtual host đã được khởi tạo trong bộ container server {}, việc tiếp theo của chúng ta là chỉnh sửa giá trị mặc định vhost (trong /etc/nginx/nginx.conf) như sau:

[...]
server {
listen 80;
server_name _;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root /usr/share/nginx/html;
index index.php index.html index.htm;
}

error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
[…]

Thông số server_name _; sẽ biến phần này thành vhost mặc định (tuy nhiên, người sử dụng vẫn phải chỉ định rõ ràng giá trị hostname tương ứng, ví dụ như www.example.com). Ở chế độ mặc định, PHP-FPM sẽ luôn lắng nghe các tín hiệu trên cổng 9000, do vậy chúng ta phải thiết lập nginx kết nối tới 127.0.0.1:9000 đi kèm với fastcgi_pass 127.0.0.1:9000. Sau đó, khởi động lai nginx:

/etc/init.d/nginx restart

Tiếp theo, tạo mã PHP sau trong phần /usr/share/nginx/html...

vi /usr/share/nginx/html/info.php

<?php
phpinfo();
?>

Việc tiếp theo là gọi file đó ra qua trình duyệt (ví dụ http://192.168.0.100/info.php):

Chúng ta có thể thấy rằng PHP5 đã làm việc, và hoạt động qua FPM/FastCGI, được chỉ ra tại dòng Server API. Nếu kéo chuột xuống phía dưới, chúng ta sẽ thấy tất cả các module đã được kích hoạt sẵn trong PHP5, trong đó có bao gồm cả MySQL:

Mặt khác, PHP – FPM luôn "lắng nghe" các tín hiệu trên cổng 9000 qua địa chỉ 127.0.0.1 ở chế độ mặc định, và chúng ta cũng có thể thiết lập PHP-FPM sử dụng socket Unix để tránh hiện tượng quá tải TCP. Để thực hiện, các bạn hãy mở file cấu hình /etc/php-fpm.d/www.conf...

vi /etc/php-fpm.d/www.conf

và thay đổi dòng listen như dưới đây:

[...]
;listen = 127.0.0.1:9000
listen = /tmp/php5-fpm.sock
[...]

Sau đó, khởi động lại PHP-FPM:

/etc/init.d/php-fpm restart


Tiếp theo, tìm kiếm trong file cấu hình nginx với tất cả các giá trị của vhosts, thay đổi fastcgi_pass 127.0.0.1:9000; thành fastcgi_pass unix:/tmp/php5-fpm.sock;

vi /etc/nginx/nginx.conf

[...]
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass unix:/tmp/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
[...]

Cuối cùng, khởi động lại Nginx:

/etc/init.d/nginx restart

Chúc các bạn thành công!

Một số đường dẫn tham khảo:

- Nginx

- nginx Wiki

- PHP

- PHP-FPM

- MySQL

- CentOS

Thứ Tư, 17/08/2011 08:40
21 👨 6.104
0 Bình luận
Sắp xếp theo
    ❖ Tổng hợp