2015年5月8日 星期五

在 CentOS 7 安裝 Nginx、PHP-FPM、MariaDB

  1. 設定 nginx repo
    CentOS 7 沒有內建的 nginx,
    所以先到 nginx 官網 http://nginx.org/en/linux_packages.html#stable,依照說明設定 yum  nginx repo
    設定的方式有兩種:

    第一種:使用rpm安裝
    找到 CentOS 7 的 nginx-release package 檔案連結,然後如下安裝
    rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
    安裝後,會自動產生 yum 的 repository 設定(在 /etc/yum.repos.d/nginx.repo),

    第二種:手動設定
    建立 nginx repo 設定檔
    vi /etc/yum.repos.d/nginx.repo
    
    內容如下(stable version 穩定版本),版本中的 "5"、"6"、"7", 分別對應到 5.x、6.x、7.x
    [nginx]
    name=nginx repo
    baseurl=http://nginx.org/packages/centos/7/$basearch/
    gpgcheck=1
    enabled=1
    
    因為我將 gpgcheck 設為 1,所以也須匯入nginx的簽章(GPG KEY) 不然安裝時會出現 Public key for nginx-*.rpm is not installed 的錯誤
    rpm --import http://nginx.org/keys/nginx_signing.key
    

    其他:
    列出所有已安裝的 GPG KEY
    $ rpm -qa gpg-pubkey*
    gpg-pubkey-f4a80eb5-53a7ff4b
    gpg-pubkey-00f97f56-467e318a
    gpg-pubkey-7bd9bf62-5762b5f8
    
    查看某個 GPG KEY 資訊
    $ rpm -qi gpg-pubkey-7bd9bf62-5762b5f8
    
  2. 安裝 nginx
    接下來便可以使用 yum 指令安裝 nginx
    yum install nginx
  3. 啟動 nginx
    以前用 chkconfig 管理服務,CentOS 7 改用 systemctl 管理系統服務
    查看 nginx 服務目前的啟動設定
    systemctl list-unit-files | grep nginx
    若是 disabled,可以改成開機自動啟動
    systemctl enable nginx
    立即啟動
    systemctl start nginx
    查看目前運作狀態
    systemctl status nginx

    若有設定防火牆,查看防火牆運行狀態
    firewall-cmd --state
    列出防火牆 public 的設定,看是否有開啟 nginx 使用的 port
    firewall-cmd --list-all --zone=public
    永久開放防火牆的 http 服務
    firewall-cmd --permanent --zone=public --add-service=http
    
    重新載入防火牆設定
    firewall-cmd --reload

    經過以上設定,應該就可以使用瀏覽器訪問 nginx 的預設頁面。
  4. 安裝 PHP-FPM
    使用 yum 安裝 php、php-fpm、php-mysql
    yum install php php-fpm php-mysql
    查看 php-fpm 服務目前的啟動設定
    systemctl list-unit-files | grep php-fpm
    改成開機自動啟動
    systemctl enable php-fpm
    立即啟動
    systemctl start php-fpm
    查看目前運作狀態
    systemctl status php-fpm

    其他個人常用 php extension (視需要安裝)
    yum install php-bcmath php-mbstring php-gd php-pecl-memcached php-pecl-redis
    systemctl restart php-fpm
  5. 修改 PHP-FPM 設定
    編輯 /etc/php-fpm.d/www.conf
    修改 group、user 設定
    user = nginx
    group = nginx
    
    //使用 unix socket 時設定
    listen.owner = nginx
    listen.group = nginx
    listen.mode = 0660

    這樣設定後,原本設定檔中的 session 資料夾路徑(/var/lib/php/session)擁有者可能不是剛設定的 nginx,可一併修改為其他新建的資料夾,例如:/home/php/session
    php_value[session.save_path] = /home/php/session
    並設定擁有者為nginx
    chown -R nginx.nginx /home/php/session/

    若想將 PHP-FPM listen 的方式,改成 unix socket
    listen = 127.0.0.1:9000
    改成
    listen = /var/run/php-fpm/php-fpm.sock

    然後重新啟動 php-fpm
    systemctl restart php-fpm

    註:不要改成 listen = /tmp/php-fcgi.sock (將 php-fcgi.sock 設定在 /tmp 底下), 因為系統產生 php-fcgi.sock 時,會放在 /tmp/systemd-private-*/tmp/php-fpm.sock 隨機私有目錄下, 除非把 /usr/lib/systemd/system/ 裡面的 PrivateTmp=true 設定改成 PrivateTmp=false, 但還是會產生其他問題,所以還是換個位置最方便

    相關資料:
    Centos 7 systemd temp files
    Why can't I see /tmp content with Php-FPM? 
  6. 在 nginx 設定使用 PHP-FPM
    編輯 /etc/nginx/conf.d/default.conf 檔案,但這邊要注意,設定檔中預設範例,PHP註解部分似乎有些錯誤,若只拿掉註解可能還是無法正常運作,我將重點部分改成如下
    server {
        listen 80;
        server_name www.example.com;
        
        location / {
            index index.php index.html index.htm;
            root  /home/web;
        }
        # 設定 PHP 檔案處理方式
        location ~ \.php$ {
            root  /home/web;
            try_files $uri =404;
            fastcgi_pass  unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }

    其他:系統原本預設的網頁目錄在 /usr/share/nginx/html,如果像我將網頁目錄 root 改到其他地方,例如 /home/web,加上系統的 SELinux 是開啟的的話,很可能因為 SELinux,而無法正常訪問。
    如果不關掉 SELinux,可以查看 /usr/share/nginx/html 目錄的 SELinux 存取設定
    ls -Zd /usr/share/nginx/html
    drwxr-xr-x. root root system_u:object_r:usr_t:s0       /usr/share/nginx/html
    
    然後將 /home/web 設成跟預設存取權限一樣
    chcon -R -u system_u -r object_r -t usr_t /home/web
    再重新啟動 nginx
    systemctl restart nginx
  7. 安裝 MariaDB
    CentOS7 裡面已經用 MariaDB 取代 MySQL,
    所以使用 yum install mariadb 或 yum install mysql,最後都是安裝 MariaDB
    yum install mariadb mariadb-server
    查看 MariaDB 服務目前的啟動設定
    systemctl list-unit-files | grep mariadb
    改成開機自動啟動
    systemctl enable mariadb
    立即啟動
    systemctl start mariadb


    若要其他電腦也可連線
    設定檔中不要設定 bind-address
    #bind-address = 127.0.0.1
    開啟防火牆設定
    firewall-cmd --permanent --zone=public --add-service=mysql
    firewall-cmd --reload
  8. 使用 mysql_secure_installation 進行安全的相關設定
    mysql_secure_installation 指令,會一步一步以問答方式進行 MySQL 的安全性設定(設定 root 密碼、移除 root 可以從其他電腦登入的設定、移除匿名帳號、移除 test 資料庫)。
    mysql_secure_installation
    因為是新安裝的,還沒有密碼,所以要 Enter current password for root 時留空白,直接按 enter
    設定過程如下
    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
    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
     ... 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
     - 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!
  9. 若要開放其他電腦可連上資料庫,可新增相關帳號。
    例如新增一個擁有root權限,同區網(192.168.0.*)的電腦可連上資料庫。
    CREATE USER 'root'@'192.168.0.%' IDENTIFIED BY '密碼';
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.0.%' WITH GRANT OPTION;
    GRANT PROXY ON ''@'' TO 'root'@'192.168.0.%' WITH GRANT OPTION;//若有要開放PROXY管理權限
    FLUSH PRIVILEGES;
    
    其他電腦不可連時,出現的錯誤訊息
    $ mysql -h 192.168.0.5 -u root -p
    Host '192.168.0.12' is not allowed to connect to this MariaDB server
    
    $ telnet 192.168.0.5 3306
    IHost '192.168.0.12' is not allowed to connect to this MariaDB serverConnection closed by foreign host.
    


其他:
  • 刪除所有 php-fpm 程序
    killall -KILL php-fpm
    PHP-FPM - Kill all linux processes that belong to php-fpm - one command line
  • PHP FPM設定參考
    [global]
    pid = /usr/local/php/var/run/php-fpm.pid
    error_log = /usr/local/php/var/log/php-fpm.log
    [www]
    listen = /var/run/php-fpm/php-fpm.sock
    user = www
    group = www
    pm = dynamic
    pm.max_children = 800
    pm.start_servers = 200
    pm.min_spare_servers = 100
    pm.max_spare_servers = 800
    pm.max_requests = 4000
    rlimit_files = 51200
    
    listen.backlog = 65536
    ;設 65536 的原因是-1 可能不是unlimited
    ;說明 http://php.net/manual/en/install.fpm.configuration.php#104172
    
    slowlog = /usr/local/php/var/log/slow.log
    request_slowlog_timeout = 10
  • nginx.conf 設定參考
    user  nginx;
    worker_processes  8;
    
    error_log  /var/log/nginx/error.log warn;
    pid        /var/run/nginx.pid;
    
    
    events {
        use epoll;
        worker_connections  65535;
    }
    worker_rlimit_nofile 65535;
    #若沒設定,可能出現錯誤:65535 worker_connections exceed open file resource limit: 1024
    
    
    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;
    
        sendfile        on;
        tcp_nopush     on;
    
        keepalive_timeout  65;
    
        server_names_hash_bucket_size 128;
        client_header_buffer_size 32k;
        large_client_header_buffers 4 32k;
        client_max_body_size 8m;
    
        server_tokens  off;
        client_body_buffer_size  512k;
    
    
        # fastcgi
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 64k;
        fastcgi_buffers 4 64k;
        fastcgi_busy_buffers_size 128k;
        fastcgi_temp_file_write_size 128k;
        fastcgi_intercept_errors on;
    
        #gzip (說明 http://nginx.org/en/docs/http/ngx_http_gzip_module.html)
        gzip  off;
        gzip_min_length  1k;#1k以上才壓縮
        gzip_buffers 32  4k;
          #http://stackoverflow.com/questions/4888067/how-to-get-linux-kernel-page-size-programatically
          #使用 getconf PAGESIZE 取得系統 one memory page size,
        gzip_http_version  1.0;
        gzip_comp_level  2;
        gzip_types  text/css text/xml application/javascript application/atom+xml application/rss+xml text/plain application/json;
          #查看 nginx 的 mime.types 檔案(/etc/nginx/mime.types),裡面有各種類型的定義
        gzip_vary  on;
    
        include /etc/nginx/conf.d/*.conf;
    }
    
    Nginx 設定檔參數值單位:http://nginx.org/en/docs/syntax.html
    大小:(bytes)、k(kilobytes)、m(megabytes)、g(gigabytes),大小寫不拘
    大小範例:1024、8k、1m、2g
    時間:ms(milliseconds)、s(seconds)、m(minutes)、h(hours)、d(days)、w(weeks)、M(months)、y(years)
    時間範例:500ms、30(若沒寫單位,預設為秒)、1h 20m(可多個單位合併寫)

    若出現出現錯誤:setrlimit(RLIMIT_NOFILE, 65535) failed (1: Operation not permitted)
    先查看目前系統的設定值
    ulimit -n
    若設定值太小,修改 /etc/security/limits.conf
    vi /etc/security/limits.conf
    加上或修改以下兩行設定
    * soft nofile 65535
    * hard nofile 65535


參考:
How To Install Linux, Nginx, MySQL, PHP (LEMP) stack On CentOS 7
How To Install Nginx With PHP And MySQL (LEMP Stack) On CentOS 7

沒有留言:

張貼留言