Chuyển đến nội dung chính

Cài đặt Nginx - PHP-FPM - Mysql centos 7

LEMP là một nhóm các phần mềm mã nguồn mở được cài trên máy chủ Webserver, được viết tắt từ Linux, NGINX (Engine x), MySQL, và PHP. LEMP tương tự như LAMP chỉ khác web server trên nền tảng Nginx thay vì Apache. Đặc điểm Nginx là một web server mã nguồn mở hoạt động nhanh và  ít tài nguyên hệ thống hơn Apache. Đối với các hệ thống nhẹ sự khác nhau giữa Apache và Nginx là không đáng kể, tuy nhiên ở các hệ thống nặng thì Nginx thể hiện sự vượt trội hơn rất nhiều so với Apache.
Dưới đây là các bước thực hiện cài đặt hoàn chỉnh LEMP.

Trước khi cài đặt các service ta cần update hệ thống cập nhật các bản vá mới nhất
[root@localhost ~]#  yum update -y
Bước 1: Cài đặt PHP
(Trong bài viết này hướng dẫn bạn cài đặt PHP version 7, với các phiên bản php khác người dùng thực hiện tương tự)
Cài đặt thêm gói epel và remi repository
[root@localhost ~]# rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

[root@localhost ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
Cài đặt PHP-FPM 7
[root@localhost ~]# yum --enablerepo=remi,remi-php72 install php-opcache php-pecl-apcu php-cli php-pear php-pdo php-mysqlnd php-pgsql php-pecl-mongodb php-pecl-redis php-pecl-memcache php-pecl-memcached php-gd php-mbstring php-mcrypt php-xml
Cài đặt xong khởi động dịch vụ PHP-FPM
[root@localhost ~]# systemctl start php-fpm
Có thể kiểm tra lại trạng thái hoạt động và phiên bản đang sử dụng bằng:
[root@localhost ~]# php-fpm -v
PHP 7.0.7 (fpm-fcgi) (built: May 28 2016 07:56:50)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies
Đặt chế độ tự khởi động dịch vụ khi khởi động hệ thống
[root@localhost ~]# systemctl enable php-fpm
Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.
Như vậy là hoàn thành cài đặt PHP 7 trên Centos 7
Đối với các phiên bản PHP thấp hơn muốn cấp lên PHP 7 thì cần thận trọng cân nhắc để đảm bảo việc update không ảnh hưởng tới hoạt động ổn định của hệ thống sau khi nâng cấp. Trong trường hợp bạn vẫn muốn nâng cấp,  bạn có thể thực hiện:

[root@localhost ~]# yum install yum-plugin-replace
[root@localhost ~]# yum replace php-common --replace-with=php70w-common
Bước 2: Cài đặt MySQL
Cài gói thêm gói repo
[root@localhost ~]#  yum install http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm
Liệt kê và Enable gói repo mysql.*
[root@localhost ~]# yum repolist enabled | grep "mysql.*-community.*"
Tiến hành cài đặt
[root@localhost ~]# yum install mysql-community-server -y
Chờ quá cài đặt thành công thì khởi động dịch vụ
[root@localhost ~]# systemctl start mysqld
Đặt chế độ khởi động dịch vụ mysql khi khởi động hệ thống
[root@localhost ~]# systemctl enable mysqld
Kiểm tra phiên bản MySQL vừa cài đặt
[root@localhost ~]# mysql -v
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.6.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Tiến hành đăng nhập vào MySQL và thiết đặt mật khẩu cho user root
[root@localhost ~]# 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.

Set root password? [Y/n] Y  <= Nhấp Y + Enter
New password:  <= Nhập mật khẩu mới cho tài khoản root 
Re-enter new password: <= Nhập lại mật khẩu
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] <= 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] <= ENTER
 ... 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] <= 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] <= ENTER
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MySQL!
Bước 3: Cài đặt NGINX
NGINX không có sẵn trên CentOS 7, để cài phiên bản mới nhất của NGINX trước tiên ta tạo 1 gói repo cho Nginx:
Tạo gói repo: nginx.repo với nội dung
[root@localhost ~]# vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/versionOS/$basearch/
gpgcheck=0
enabled=1
Trong đó thay versionOS bằng tên phiên số phiên bản tương ứng. Ví dụ: CentOS 7 thì thay versionOS bằng 7.
Sau đó lưu lại và bắt đầu cài đặt NGINX:
[root@localhost ~]# yum install nginx -y​
Cài đặt thành công ta có thể check phiên bản NGINX hiện tại là phiên bản nào bằng lệnh:
[root@localhost ~]# nginx -v
nginx version: nginx/1.10.1
Khởi động NGINX:
[root@localhost ~]# systemctl start nginx​
Đặt chế độ NGINX tự khởi động khi khởi động lại máy chủ:
[root@localhost ~]# systemctl enable nginx​
Chú ý mở port 80 trên Firewall:
[root@localhost ~]# firewall-cmd --permanent --add-port=80/tcp

[root@localhost ~]# firewall-cmd --reload
Truy nhập địa chỉ IP của server nếu xuất hiện màn hình như bên dưới là thành công: 
Bước 4: Cấu hình tạo virtual host trên NGINX
Các file sẽ cấu hình:
File /etc/nginx/nginx.conf - file cấu hình chung cho nginx
File /etc/nginx/conf.d/tên-file.conf - file cấu hình vhost  cho domain mong muốn.
Cấu hình file cấu hình chung :
[root@localhost ~]# vi /etc/nginx/nginx.conf

user  nginx; <= Gán quyền cho user nginx
worker_processes  1;  <= Cần chỉnh lại worker_processes bằng với số lượng CPU core bạn được sử dụng​
error_log  /var/log/nginx/error.log warn;  <= Cấu hình đường dẫn file error_log
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;   <= số kết nối tối đa tai 1 thời điểm; mặc định là 1024; trường hợp bạn muốn nâng cao hơn có thể tùy chỉnh nhưng không nên cao hơn quá 2048.
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main; <= Cấu hình log access
    sendfile        on;
    server_tokens off;   <= Cấu hình ẩn phiên bản nginx đang sử dụng

    #tcp_nopush     on;
    keepalive_timeout  65;

    #gzip  on;
    fastcgi_buffers         8 16k;
    fastcgi_buffer_size     32k;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout    300;
    fastcgi_read_timeout    300;
    include /etc/nginx/conf.d/*.conf; <= Đường dẫn gán file cấu hình virtual hosts cho từng site
}
Sau đó lưu lại cấu hình. Test lại kết quả bằng cách tạo thử 1 virtual host ảo cho domain demo.local.com
Vào thư mục conf.d và tạo 1 file demo.local.com.conf được copy từ file cấu hình mặc định default.conf
[root@localhost ~]# cd /etc/nginx/conf.d/
[root@localhost conf.d]# cp default.conf demo.local.com.conf
Chỉnh sửa lại file demo.local.com.conf
[root@localhost conf.d]# vi demo.local.com.conf
 server {
    listen       80 ; <= Port mặc định
    server_name  demo.local.com ; <= Nhập tên miền mong muốn
    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;
    location / {
        root   /home/demo.local.com/ ;  <= đường dẫn document root
        index  index.html index.htm index.php;
    try_files $uri $uri/ /index.php?;
    }
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /home/demo.local.com/; <= đường dẫn document root
    }

    # 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           /home/demo.local.com/; <= đường dẫn document root
        fastcgi_pass   127.0.0.1:9000; => Có thể cấu hình UNIX Socket nếu muốn
        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;
    #}
}
Lưu lại cấu hình và khởi động lại dịch vụ NGINX
[root@localhost demo.local.com]# systemctl restart nginx​
Tạo 1 thư mục gốc như đã cấu hình ở bước trên
[root@localhost nginx]# mkdir /home/demo.local.com
 Tạo 1 file test index.php
[root@localhost demo.local.com]# vi index.php
Trỏ tên miền demo.local.com về server  và kiểm tra kết quả, nếu được như bên dưới có nghĩa  bạn đã thực hiện thành công.
Config demo.local.com.conf
server {
 listen   80; ## listen for ipv4; this line is default and implied

 root /usr/share/nginx/html/demo.local.com/public;
 index index.php index.html index.htm;

 # Make site accessible from http://localhost/
 server_name demo.local.com;

 # Disable sendfile as per https://docs.vagrantup.com/v2/synced-folders/virtualbox.html
 sendfile off;

 # Add stdout logging
 #error_log /dev/stdout info;
 #access_log /dev/stdout;

 # block access to sensitive information about git
 location /.git {
           deny all;
           return 403;
        }

 location / {
  # First attempt to serve request as file, then
  # as directory, then fall back to index.html
  default_type application/json;
  try_files $uri $uri/ /index.php?$query_string;
 }

 error_page 404 /404.html;
        location = /404.html {
                root /var/www/errors;
                internal;
        }

        location ^~ /sad.svg {
            alias /var/www/errors/sad.svg;
            access_log off;
        }
        location ^~ /twitter.svg {
            alias /var/www/errors/twitter.svg;
            access_log off;
        }
        location ^~ /gitlab.svg {
            alias /var/www/errors/gitlab.svg;
            access_log off;
        }

 # pass the PHP scripts to FastCGI server listening on socket
 #
 location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #fastcgi_pass unix:/var/run/php-fpm.sock;
  fastcgi_pass 127.0.0.1:9000;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
  fastcgi_index index.php;
  include fastcgi_params;
 }

    location ~* \.(jpg|jpeg|gif|png|css|js|ico|webp|tiff|ttf|svg)$ {
            expires           5d;
    }

 # deny access to . files, for security
 #
 location ~ /\. {
        log_not_found off;
        deny all;
 }

 location ^~ /.well-known {
        allow all;
        auth_basic off;
    }

}
Edit file config permissive
[root@localhost ~]# vi /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=permissive
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted
Set permission 777 cho thư mục storage boostrap
[root@localhost ~]# cd /etc/php-fpm.d
[root@localhost ~]# vi www.conf
config apache -> nginx







Nhận xét

Bài đăng phổ biến từ blog này

Tổng quan Multi tenancy

Multi tenant là gì ? Multi-Tenant - Multi-tenancy có nghĩa là một phiên bản duy nhất của phần mềm và cơ sở hạ tầng hỗ trợ của nó phục vụ nhiều khách hàng. Mỗi khách hàng chia sẻ ứng dụng phần mềm và cũng chia sẻ một cơ sở dữ liệu. Dữ liệu của mỗi người khách hàng bị cô lập và vẫn vô hình đối với những khách hàng khác. Lợi ích của Multi tenant Chi phí thấp hơn thông qua tính kinh tế theo quy mô: Với nhiều khách hàng, nhân rộng có ý nghĩa cơ sở hạ tầng ít hơn nhiều so với giải pháp lưu trữ vì khách hàng mới có quyền truy cập vào cùng một phần mềm cơ bản. Hơn nữa, người dùng không cần bận tâm về việc cập nhật các tính năng và cập nhật mới, họ cũng không cần phải trả phí bảo trì hoặc chi phí khổng lồ. Các bản cập nhật là một phần của đăng ký hoặc, nếu phải trả bất kỳ khoản phí bảo trì nào, nó được chia sẻ bởi nhiều người thuê, do đó làm cho nó trở thành danh nghĩa (nhân tiện, bao gồm các bản cập nhật). Kiến trúc Multi tenant phục vụ hiệu quả tất cả mọi người từ các khách hàng

Multi tenant là gì ?

Bài toán hướng multi-tenancy trong thực tế gặp rất nhiều, nhưng có rất nhiều developer chưa nắm được khái niệm và cách thức hoạt động của các hệ thống thiết kế theo hướng này. Qua một thời gian nghiên cứu và phát triển các hệ thống, mình đúc rút một số kinh nghiệm muốn chia sẻ cho mọi người. Thực tế ta bắt gặp rất nhiều hệ thống sử dụng multi-tenacy vd: - Hệ thống quản lý cửa hàng cho phép nhiều đại lý có thể truy cập với những tài khoản độc lập, dữ liệu độc lập, nhưng cùng chung 1 hệ thống site. - Hệ thống quản lý công văn sử dụng trong tổng công ty và nhiều công ty con, cùng site nhưng dữ liệu độc lập. - Hệ thống quản lý dự án Jira - Hệ thống CRM của zoho, saleforce... Nhiều hệ thống sử dụng SQL server, Oracle ... thiết kế hệ thống multi-tenancy theo một trong các kiến trúc sau. Phương án I . Cùng chung một cơ sở dữ liệu (database), chia sẻ bảng (table) Tất cả các bảng liên quan đều có 1 khóa ngoại là ShopId. Dữ liệu sản phẩm của từng shop đều được lưu chung trong bả

THIẾT KẾ DATABASE THEO HƯỚNG MULTI-TENANCY

Phương án I. Cùng chung một cơ sở dữ liệu (database), chia sẻ bảng (table) Ví dụ: Một hệ thống quản lý cửa hàng, có bảng shop, bảng sản phẩm (product), bảng acccount Bảng shop Shop ( Id, Name, Notes) Bảng user User( Id, Name, UserName, Password, ShopId ) Bảng product Product ( Id int, Code varchar(50), Name varchar(255), ShopId) Tất cả các bảng liên quan đều có 1 khóa ngoại là ShopId. Dữ liệu sản phẩm của từng shop đều được lưu chung trong bảng Product, nhưng được phân biệt nhau bởi trường ShopId. Điểm mạnh: - Thiết kế lưu trữ đơn giản. - Dễ cho việc phát triển. - Không gặp phải vấn đề đồng bộ cấu trúc bảng trong quá trình phát triền. Nhược điểm: - Không độc lập database nên việc một shop có thể xem dữ liệu của shop khác nếu có quyền truy cập SQL, phân quyền trên SQL thực sự là vấn đề lớn. - Vấn đề backup, restore dữ liệu cho từng shop là gần như không thể, chỉ có thể backup cho tất cả. - Vấn đề phát sinh thực sự phức tạp khi dữ liệu phình