OB2D主機架設

1. 下載及安裝

關於OB2D

  1. 官網:https://b2d-linux.com/
  2. OB2D是以debian為基礎開發的Linux套件,OB2D很小很穩定!非常適合拿來架設伺服器,拿來當作虛擬機也很好用。
  3. 本文以2016、2017、2019 版本為主。
  4. 如果需要其他版本,可以到這裡找到所有的OB2D檔案下載:http://sourceforge.net/projects/ob2dlinux/files/?source=navbar

現有系統發行套件查詢

lsb_release -a

OB2D-XFCE-Server-2019-Maxima-v1.0.1(Debian 10 Buster

  1. https://sourceforge.net/projects/ob2dlinux/files/2019/OB2D/XFCE-SERVER/1.0.1/(PHP7.3)
  2. Debian 10 Buster 使用此版本:https://sourceforge.net/projects/ob2dlinux/files/2019/OB2D/XFCE-SERVER/1.0.1/OB2D-XFCE-Server-2019-Maxima-v1.0.1.amd64.iso/download

OB2D-XFCE-Server-2017-stretch-v1.4 Beta(Debian 9 Stretch)

  1. https://sourceforge.net/projects/ob2dlinux/files/2017/XFCE-SERVER/(PHP 7.0)
  2. Debian 9 Stretch 使用此版本:https://sourceforge.net/projects/ob2dlinux/files/2017/XFCE-SERVER/for-HyperV/OB2D-XFCE-Server-2017-stretch-v1.4beta.amd64.iso/download
  3. 如果喜歡文字界面的(不含桌面省資源),可用:https://sourceforge.net/projects/ob2dlinux/files/2017/MINI-SERVER/for-HyperV/

OB2D-XFCE-Server-2016-jessie-v1.4(Debian 8 Jessie)

  1. https://sourceforge.net/projects/ob2dlinux/files/2016/SERVER/(PHP 5.6)
  2. Debian 8 Jessie 使用此版本:https://sourceforge.net/projects/ob2dlinux/files/2016/XFCE-SERVER/OB2D-XFCE-Server-2016-jessie-v1.4.amd64.iso/download

安裝OB2D

  1. 由於沒有實際機器 可以安裝,所以,我們在自己的電腦(以下稱HOST機)用 VirtualBox  來建立虛擬機,並安裝OB2D。
  2. 安裝好  VirtualBox 後,「新增」一台虛擬電腦,均用預設值即可。
  3. 安裝部份,請直接參考原作者寫的:https://b2d-linux.com/?p=371
  4. 新增後,至「設定」找到「網路」改為「橋接介面卡」,以便使用現有網路環境。
  5. 若想了解這四種網路界面有什麼不一樣,請自行參考:
  6. 啟動電腦後,選擇下載的 iso 檔,以便掛載光碟(等同插入安裝光碟一樣)。
  7. 接著就按照提示進行安裝。
    1. IP 部份,輸入欲使用的固定IP,社大請輸入「192.168.0.xx」,南市教網請輸入「192.168.1.xx」,xx 範圍從40~70。
    2. gateway,輸入欲使用的gateway,社大請輸入「192.168.0.254」,南市教網請輸入「192.168.1.253」。
    3. DNS,輸入欲使用的DNS,社大請輸入「8.8.8.8」,南市教網請輸入「163.26.1.1」。
    4. 其他都使用預設值即可。
  8. 裝好之後,從HOST機輸入虛擬機IP,順利的話,應該就可以看到「 Apache2 Debian Default Page 」的畫面。
  9. 若UEFI 沒辨法安裝,請進入 BIOS 中,把 secure boot 關掉,就可以安裝了。

OB2D主機架設

2. 讓 ROOT 可以從 pietty 登入

pietty 是一套改良 putty 而來的,可以讓您從windows下登入Linux主機的一套遠端連線工具。

pietty 官網:http://ntu.csie.org/~piaip/pietty/

一般而言,操作 pietty 會比實際在主機中用專端機還來得方便一點...(因為可以很方便的複製貼上)

所以,在進行主機設定之前,先搞定讓 root 可以透過 peitty來登入網站的問題(預設只能用使用者登入)

  1. 先設定 root 密碼
    sudo passwd root
  2. 設好後,切換成 root
    su -
  3. 修改 ssh 設定(nano是編輯器,也可以用vi,但目前的vi很難用)
    nano /etc/ssh/sshd_config
  4. 修改其中的 PermitRootLogin 為
    PermitRootLogin yes
  5. 重新啟動 SSH
    service ssh restart
  6. 暫時先關閉防火牆:
    iptables -F
  7. 大功告成!您已經可以啟動 pietty,並連上主機後,直接以root身份登入了。

 

OB2D主機架設

3. 優化 vi

  1. 先到家目錄,並安裝 wget套件
    cd ~
    apt-get install wget 

     

  2. 下載優化檔
    wget https://campus-xoops.tn.edu.tw/uploads/vimrc.zip

     

  3. 解壓縮,完工!
    apt-get install unzip
    unzip vimrc.zip

     

VI簡易用法

按鍵 用途
a 編輯模式下新增、插入內容
esc鍵 切換指令模式或編輯模式
:wq! 指令模式下w 儲存,q 離開,! 強制模式
/ 指令模式下搜尋
n 指令模式下搜尋下一個

 

OB2D主機架設

4. 讓ll可以使用

  1. 編輯設定檔:
    vi ~/.bashrc 
  2. 把註解取消
    # You may uncomment the following lines if you want `ls' to be colorized:
     export LS_OPTIONS='--color=auto'
     eval "`dircolors`"
     alias ls='ls $LS_OPTIONS'
     alias ll='ls $LS_OPTIONS -l'
     alias l='ls $LS_OPTIONS -lA'
    #
    # Some more alias to avoid making mistakes:
    # alias rm='rm -i'
    # alias cp='cp -i'
    # alias mv='mv -i'
    
  3. 重新登出登入後就會生效。

OB2D主機架設

5. 修改防火牆

  1. 預設只有同網段才能登入,若想讓遠端其他網段或IP登入,就必須修改防火牆。
  2. 開啟rc.local
    vi /etc/rc.local
  3. 把 #LAN_IP_RANGE="192.168.1.0/24" 的註解符號 # 去掉,並設成你的網段。
  4. 把 #IPTABLES -A INPUT -p tcp -s $LAN_IP_RANGE --dport 22 -j ACCEPT 的註解符號 # 去掉
  5. 執行 sudo /etc/rc.local 以使設定生效
    sudo /etc/rc.local
  6. 完整範例:
    #!/bin/sh -e
    #
    ###-----------------------------------------------------###
    echo "Set path of iptables"
    echo
    
    IPTABLES="/sbin/iptables"
    
    ###-----------------------------------------------------###
    echo "Set external ......"
    echo
    
    #FW_IP=""
    #FW_IP_RANGE=""
    #FW_IFACE="eth0"
    
    ###-----------------------------------------------------###
    echo "Set internal ......"
    echo
    
    #LAN_IP="192.168.1.1"
    LAN_IP_RANGE="192.168.1.0/24"
    #LAN_BCAST_ADRESS="192.168.1.255"
    #LAN_IFACE="eth1"
    
    # loopback interface
    LO_IFACE="lo"
    LO_IP="127.0.0.1"
    
    ###-----------------------------------------------------###
    #echo "Enable ip_forward ......"
    #echo
    
    #echo "1" > /proc/sys/net/ipv4/ip_forward
    
    
    ###-----------------------------------------------------###
    echo "Flush fiter table ......"
    echo
    
    # Flush filter
    $IPTABLES -F
    $IPTABLES -X
    echo "Flush nat table ......"
    echo
    # Flush nat
    $IPTABLES -F -t nat
    $IPTABLES -t nat -X
    
    ###-----------------------------------------------------###
    $IPTABLES -P INPUT ACCEPT
    $IPTABLES -P OUTPUT ACCEPT
    $IPTABLES -P FORWARD ACCEPT
    
    ###-----------------------------------------------------###
    
    #$IPTABLES -t nat -A POSTROUTING -o $FW_IFACE -j SNAT --to-source $FW_IP
    
    ###-----------------------------------------------------###
    #$IPTABLES -t nat -A PREROUTING -p tcp -d $FW_IP --dport 8080  -j DNAT --to 192.168.1.3:80
    
    ###-----------------------------------------------------###
    
    #$IPTABLES -A FORWARD -o $FW_IFACE -p tcp -s 192.168.1.6 --dport 6677 -j ACCEPT
    #$IPTABLES -A FORWARD -o $FW_IFACE -p tcp --dport 6677 -j DROP
    
    ###-----------------------------------------------------###
    
    #$IPTABLES -A INPUT -i $FW_IFACE -p tcp -s 192.168.1.0/24 --dport 6677 -j ACCEPT
    #$IPTABLES -A INPUT -i $FW_IFACE -p tcp --dport 6677 -j DROP
    
    #iptables -A ratelimit -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
    #iptables -A ratelimit -p icmp --icmp-type echo-request  -m limit --limit 3/m --limit-burst 10 -j ACCEPT
    #iptables -A ratelimit -p icmp --icmp-type echo-request -j LOG --log-level "NOTICE" --log-prefix "[RATELIMIT$
    #iptables -A ratelimit -p icmp --icmp-type echo-request -j DROP
    
    
    #iptables -A INPUT -p icmp --icmp-type echo-request -j ratelimit
    
    
    #iptables -A INPUT -p tcp --dport 443 -j LOG --log-level "NOTICE" --log-prefix "[9999]"
    
    $IPTABLES -A INPUT -p tcp -s 127.0.0.1 --dport 21 -j ACCEPT
    $IPTABLES -A INPUT -p tcp --dport 21 -j DROP
    
    $IPTABLES -A INPUT -p tcp -s $LAN_IP_RANGE --dport 22 -j ACCEPT
    $IPTABLES -A INPUT -p tcp -s 120.115.3.33 --dport 22 -j ACCEPT
    $IPTABLES -A INPUT -p tcp -s 127.0.0.1 --dport 22 -j ACCEPT
    $IPTABLES -A INPUT -p tcp --dport 22 -j DROP
    
    $IPTABLES -A INPUT -p tcp -s 127.0.0.1 --dport 111 -j ACCEPT
    $IPTABLES -A INPUT -p tcp --dport 111 -j DROP
    
    /sbin/ip6tables -F
    /sbin/ip6tables -A INPUT -p tcp --dport 22 -j DROP
    
    exit 0
    

     

OB2D主機架設

6. 修改 source.list並進行套件更新

修改OB2D jessie 的sources.list:

vi /etc/apt/sources.list

在 vi 中用 dd 可以刪除整行(用 5dd 可以一次刪除五行)

如果是2019年版的(buster),請改成:

deb https://opensource.nchc.org.tw/debian/ buster main contrib non-free
deb-src https://opensource.nchc.org.tw/debian/ buster main contrib non-free
deb https://opensource.nchc.org.tw/debian/ buster-updates main
deb-src https://opensource.nchc.org.tw/debian/ buster-updates main
deb https://security.debian.org/debian-security buster/updates main contrib non-free
deb https://opensource.nchc.org.tw/debian buster-backports main

如果是2017年版的(stretch),請改成:

deb https://opensource.nchc.org.tw/debian/ stretch main contrib non-free
deb-src https://opensource.nchc.org.tw/debian/ stretch main contrib non-free
deb https://opensource.nchc.org.tw/debian/ stretch-updates main contrib non-free
deb-src https://opensource.nchc.org.tw/debian/ stretch-updates main contrib non-free
deb https://security.debian.org/ stretch/updates main
deb-src https://security.debian.org/ stretch/updates main

這是2016年版的(jessie )

deb https://opensource.nchc.org.tw/debian/ jessie main contrib non-free
deb-src https://opensource.nchc.org.tw/debian/ jessie main contrib non-free
deb https://opensource.nchc.org.tw/debian/ jessie-updates main contrib non-free
deb-src https://opensource.nchc.org.tw/debian/ jessie-updates main contrib non-free
deb https://security.debian.org/ jessie/updates main
deb-src https://security.debian.org/ jessie/updates main

如果是2013年版的(wheezy),請改成:

deb https://opensource.nchc.org.tw/debian/ wheezy main contrib non-free
deb https://opensource.nchc.org.tw/debian/ wheezy-updates main contrib non-free
deb https://security.debian.org/ wheezy/updates main contrib non-free

更新一下apt套件庫清單:

apt-get update 

萬一更新後,有出現 There is no public key available for the following key IDs: xxxxxxxxxxxx 的錯誤訊息

請執行以下動作解決之:

apt-get install debian-keyring debian-archive-keyring
apt-key update

如果出現被鎖住的狀況:

E: 無法將 /var/lib/apt/lists/lock 鎖定 - open (11: 資源暫時無法取得)
E: Unable to lock directory /var/lib/apt/lists/

則刪掉lock檔即可

rm /var/lib/apt/lists/lock

 

2019年後的(buster)安裝php7.3的curl、mail及mbstring函式庫

apt-get install php7.3-curl php7.3-mbstring php7.3-zip php7.3-soap php7.3-mail

2017年後的(stretch)安裝php7的curl及mbstring函式庫

apt-get install php7.0-curl php7.0-mbstring php7.0-zip php7.0-soap

2016年(含以前的)安裝php5的curl及intl函式庫(XOOPS會用到)

apt-get install php5-curl php5-intl php5-zip php5-soap

安裝rsync(方便日後備份)、htop(方便觀察主機狀況)、 fping(設定排程時可能會用到)、 sshfs及nfs(方便遠端掛載備份,無此需求可免裝)、zip(以壓縮)、unzip(以解壓縮)、NTP (校時工具)、安裝ca-certificates,避免wget無法下載https檔但,以及https網址時,Google快速登入會出現錯誤訊息(Google_IOException: HTTP Error: (0) error setting certificate verify locations: CAfile: /etc/ssl/certs/ca-certificates.crt CApath: /etc/ssl/certs)

apt-get install rsync htop fping sshfs nfs-common zip unzip ntp ntpdate ca-certificates

查詢核心

uname -a

升級核心(非必須)

apt-get install linux-image-4.11.8-ob2d linux-headers-4.11.8-ob2d linux-firmware-image-4.11.8-ob2d

日後要更新套件所有套件:

apt-get upgrade

 

OB2D主機架設

7. Apache的設定及優化

開啟Apache狀態功能

  1. 先啟用狀態模組(其他模組就順便啟用)
    a2enmod mod_status rewrite
  2. 修改設定檔
    vi /etc/apache2/mods-enabled/status.conf
  3. 加入可以觀看態結果的網域
    <Location /server-status>
            SetHandler server-status
            Require local
            Require ip 120.115.3.0/24
    </Location>
    
  4. 最後重新啟動Apache
    systemctl restart apache2
  5. 執行(每10秒自動更新)
    http://網址/server-status?refresh=10

放大限制(主機多的時候)

  1. 編輯設定檔
    vi /etc/apache2/envvars

    把其中limit的註解取消

    APACHE_ULIMIT_MAX_FILES='ulimit -n 65536'

    重啟網站

減少主機資訊外漏

  1. 網站資訊檢測:https://www.netcraft.com/
  2. 編輯 /etc/apache2/conf-enabled/security.conf
    vi /etc/apache2/conf-enabled/security.conf
  3. 找出底下兩個設定項目,並修改其值

    ServerTokens Prod
    ServerSignature Off
    
  4. 重啟網站

    service apache2 restart

Apache常用指令

  1. 計算 Apache2 總記憶體使用量
    ps aux | grep apache2 | awk '{ total += $6; } END { print total/1024"MB" }'
  2. 計算 Apache2 總 CPU 使用量
    ps aux | grep apache2 | awk '{ total += $3; } END { print total"%" }'
  3. 要查看當前正在運行的Apache進程數(processes),請使用此命令
    ps faux|grep apache2|wc -l
  4. 查看在所有進程下運行的Apache線程總數(threads), MaxRequestWorkers的設定值需大於此值
    ps -eLf|grep apache2|wc -l
  5. 查看在特定Apache進程(processes)下運行的線程數(threads)
    ps -eLf|grep $程序編號 |wc -l
  6. 查看當前的連接數狀況:
    netstat -nat|awk '{print awk $NF}'|sort|uniq -c|sort -n
  7. linux下獲取佔用CPU資源最多的10個進程,可以使用如下命令組合:
    ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head
  8. linux下獲取佔用內存資源最多的10個進程,可以使用如下命令組合:
    ps aux|head -1;ps aux|grep -v PID|sort -rn -k +4|head
  9. 列出系統上最耗費記憶體的程式:
    ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head
  10. 前 10 個最耗費記憶體的行程:
    top -b -o +%MEM | head -n 17
  11. 找出最耗費 CPU 資源的行程 :
    top -b -o +%CPU | head -n 17
  12. 查看和Apache相關的連線
    netstat -ae|grep www-data
  13. 可用以下指令查看目前連線數最高的IP
    netstat -nat|grep ":80"|awk '{print $5}' |awk -F: '{print $1}' | sort| uniq -c|sort -n

查看Apache2使用模式

  1. 先查看一下Apache 資訊
    apache2 -V
  2. 若出現類似以下訊息:

    [Mon Oct 16 22:34:47.936456 2017] [core:warn] [pid 9405] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
    apache2: Syntax error on line 80 of /etc/apache2/apache2.conf: DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot
  3. 則執行以下指令,重新匯入Apache環境變數:

    . /etc/apache2/envvars
  4. 接者再執行原本指令,應該就會看到正確信息,如:

    Server version: Apache/2.4.25 (Debian)
    Server built:   2017-09-19T18:58:57
    Server's Module Magic Number: 20120211:68
    Server loaded:  APR 1.5.2, APR-UTIL 1.5.4
    Compiled using: APR 1.5.2, APR-UTIL 1.5.4
    Architecture:   64-bit
    Server MPM:     prefork
      threaded:     no
        forked:     yes (variable process count)
    Server compiled with....
     -D APR_HAS_SENDFILE
     -D APR_HAS_MMAP
     -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
     -D APR_USE_SYSVSEM_SERIALIZE
     -D APR_USE_PTHREAD_SERIALIZE
     -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
     -D APR_HAS_OTHER_CHILD
     -D AP_HAVE_RELIABLE_PIPED_LOGS
     -D DYNAMIC_MODULE_LIMIT=256
     -D HTTPD_ROOT="/etc/apache2"
     -D SUEXEC_BIN="/usr/lib/apache2/suexec"
     -D DEFAULT_PIDLOG="/var/run/apache2.pid"
     -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
     -D DEFAULT_ERRORLOG="logs/error_log"
     -D AP_TYPES_CONFIG_FILE="mime.types"
     -D SERVER_CONFIG_FILE="apache2.conf"
    
  5. 從第7行可以得知,目前跑的是 prefork 模式。因此,開啟對應設定檔編輯之:

    vi /etc/apache2/mods-available/mpm_prefork.conf
  6. 完整說明請參考:http://www.cnblogs.com/kevingrace/p/6211887.html

OB2D主機架設

7-1 Prefork 模式

prefork模式是古老穩定的模式。Apache在啟動之初,就預先產生一些子進程,然後等待請求進來,以減少頻繁創建和銷毀進程的開銷。每個子進程只有一個線程,在一個時間點內,只能處理一個請求。

  1. 編輯mpm_prefork設定檔
    vi /etc/apache2/mods-available/mpm_prefork.conf
  2. 建議內容如下:
    <IfModule mpm_prefork_module>
            StartServers            5
            MinSpareServers         5
            MaxSpareServers         10
            ServerLimit             1000
            MaxRequestWorkers       750
            MaxConnectionsPerChild  3000
    </IfModule>
    • StartServers:一開始建立的子進程數#推薦設置:小=默認 中=20~50 大=50~100
    • MinSpareServers:最小數量的服務器進程,保存備用(達此數就不再主動建立新的進程,如果站點負載較大,可加大此值)推薦設置:與StartServers保持一致
    • MaxSpareServers:最大數量的服務器進程,保存備用(空閒進程數大於此值時,Apache會自動kill掉一些多餘進程。故不要設得過大,如果站點負載較大,可加大此值)#推薦設置:小=20 中=30~80 大=80~120
    • MaxRequestWorkers:最為重要的一個, Apache可以同時處理的請求數,是對Apache性能影響最大的參數。舊名MaxClients ,若連接數(ps -ef|grep apache2|wc -l)大於此值時,就會開始排隊#推薦設置:小=500 中=500~1500 大型=1500~3000( 如果最大請求進程數超過256需要在MaxRequestWorkers參數前添加參數ServerLimit並且定最大並發數,該參數最好與MaxRequestWorkers的值保持一致。
    • MaxConnectionsPerChild:設置的是每個子進程可處理的請求數(0意味著子進程永不銷毀,但不建議,舊名MaxRequestsPerChild )#推薦設置:小=10000 中或大=10000~500000
  3. 儲存後,重啟 Apache
    service apache2 restart
  4. 修改核心參數,解決WAIT_TIME過多問題:
    vi /etc/sysctl.conf
  5. 加入以下四行:
    net.ipv4.tcp_syncookies = 1
    net.ipv4.tcp_tw_recycle = 1
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_fin_timeout = 30

整理自https://www.jianshu.com/p/1e7273aa129f

OB2D主機架設

7-1-1 修改 php.ini

php.ini 的設定非常重要,尤其是時區與除錯的設定,沒設定好,日後問題多多。

2016年以前的版本請輸入:

vi /etc/php5/apache2/php.ini

2017年後的版本請輸入:

vi /etc/php/7.0/apache2/php.ini

請按著下表調整設定吧(底下行數每個版本都不同,這裡是以2017年1.1版為主):

設定項目 建議值 行數 相關說明
max_execution_time 150 368
每個程序最大允許執行時間(秒),0 表示沒有限制。這個參數有助於阻止劣質程序無休止的佔用伺服器資源。
檔案上傳時,若檔案很大,頻寬卻很小,那麼此值需調大一點,例如上傳 10M 檔案需要花2分鐘,那此值就不要小於 120。
max_input_time 120 378
每個程序解析輸入數據 (POST, GET, upload) 的最大允許時間(秒)。
-1 表示不限制。
max_input_vars 5000 385
表單可接收的變數數量,超過此數量,就可能無法完全接收表單內容。
部份系統有匯入功能,匯入後若有表單確定畫面,通常會有很多變數,因此,調大此值有助於匯入資料的完整性。
memory_limit 240M 389
一個程序所能夠申請到的記憶體空間 (可以使用 K 和 M 作為單位)。 這有助於防止劣質程序消耗完伺服器上的所有記憶體。如果要取消記憶體限制,則必須將其設為 -1 。
display_errors on 462
是否顯示錯誤訊息?建議開啟!!否則網站變成空白時將很難進行除錯。
post_max_size 220M 656
允許的 POST 數據最大字節長度。此設定也影響到檔案上傳。
如果 POST 數據超出限制,那麼 $_POST 和 $_FILES 將會為空。
要上傳大檔案,該值必須大於 upload_max_filesize 指令的值。
如果啟用了記憶體限制,那麼該值應當小於 memory_limit 指令的值。
upload_max_filesize 200M 809
允許上傳的檔案的最大尺寸。
max_file_uploads 300 812
最多只能傳幾個檔案?請視需求設定之。
date.timezone Asia/Taipei 924
主機預設時區,若主機在台灣,請務必設置為「Asia/Taipei」,否則系統抓到的可能會有誤差。

修改後記得重新啟動 apache

service apache2 restart

若想測試一下,可建立一個簡單的PHP檔來測試:

vi /var/www/html/info.php

內容為:

<?php
phpinfo();

存檔後,開啟瀏覽器,執行「http://網址/info.php」即可看到PHP的資訊頁面。

 

OB2D主機架設

7-2 Worker 模式

worker使用了多進程和多線程的混合模式。它也預先產生幾個子進程(數量比較少),然後每個子進程創建一些線程,同時包括一個監聽線程。每個請求過來,會被分配到1個線程來服務。

線程比起進程會更輕量,因為線程通常會共享父進程的內存空間,因此,內存的佔用會減少一些。在高並發的場景下,因為比起prefork有更多的可用線程,表現會更優秀一些。

  1. 更新套件庫
    apt-get update
  2. 升級套件
    apt-get upgrade
  3. 安裝php-fpm
    #for Debian 10 Buster
    apt-get install -y php7.3-fpm
    
    #for Debian 9 Stretch
    apt-get install -y php7.0-fpm 
    
    #for Debian 8 Jessie
    apt-get install -y php5.6-fpm 
  4. 關閉mpm_prefork 相關模組(php版本請自行調整)並開啟 mpm_worker 相關模組 並啟用 php-fpm 設定,最後重啟apache使之生效
    a2dismod php7.0 mpm_prefork
    a2enmod mpm_worker actions
    a2enconf php7.0-fpm
    systemctl restart apache2
  5. 設定 php.ini,可參考 https://campus-xoops.tn.edu.tw/modules/tad_book3/page.php?tbdsn=220
    #for Debian 10 Buster
    vi /etc/php/7.3/fpm/php.ini
    
    #for Debian 9 Stretch
    vi /etc/php/7.0/fpm/php.ini
    
    #for Debian 8 Jessie
    vi /etc/php/5.6/fpm/php.ini
  6. 重啟 php-fpm 後 php.ini 才會生效,先找出 php-fpm: master process 的程序編號
    ps aux|grep php-fpm
  7. 然後根據程序編號執行以下指令即可重啟 php-fpm
    kill -USR2 程序編號
  8. 編輯 mpm_worker 設定檔
    vi /etc/apache2/mods-available/mpm_worker.conf
  9. 建議內容如下:
    <IfModule mpm_worker_module>
        StartServers             3
        MinSpareThreads         75
        MaxSpareThreads        250
        ThreadsPerChild         25
        MaxRequestWorkers      400
        MaxConnectionsPerChild   0
    </IfModule>
    
    • StartServers:一開始建立的子進程數,每個子進程中包含固定的ThreadsPerChild線程數
    • MinSpareServers:最小數量的服務器進程,保存備用(最大預設值是75,達此數就不再主動建立新的進程,如果站點負載較大,可加大此值)
    • MaxSpareServers:最大數量的服務器進程,保存備用(最大預設值是250,空閒進程數大於此值時,Apache會自動kill掉一些多餘進程。故不要設得過大,如果站點負載較大,可加大此值)
    • ThreadsPerChild: 每個子進程的線程數(預設值是64, 如果負載較大,64也是不夠的。這時要顯式使用 ThreadLimit 指令,它的最大預設值是 20000)
    • MaxRequestWorkers: 如果現有子進程中的線程總數不能滿足負載,控制進程將派生新的子進程
    • MaxConnectionsPerChild:設置的是每個子進程可處理的請求數(0意味著子進程永不銷毀,但不建議,舊名MaxRequestsPerChild )
  10. Worker模式下所能同時處理的請求總數=子進程總數xThreadsPerChild ,請求總數應該 >= MaxRequestWorkers。
  11. 如果負載很大,現有的子進程數不能滿足時,控制進程會派生新的子進程。
  12. 默認最大的子進程總數是16,加大時 也需要顯式聲明ServerLimit(最大值是20000)
  13. 需要注意的是,如果顯式聲明了ServerLimit,那麼它乘以 ThreadsPerChild的值必須大於等於MaxRequestWorkers,而且MaxRequestWorkers必須是ThreadsPerChild的整數倍,否則 Apache將會自動調節到一個相應值。
  14. 最後重新啟動Apache
    systemctl restart apache2
  15. 修改 /uploads/.htaccess
    vi /var/www/html/uploads/.htaccess
  16. 刪掉 php_flag engine off,並在最後加入:
    <Files "*.php">
      SetHandler none
      SetHandler default-handler
      Options -ExecCGI
      RemoveHandler .php
    </Files>
  17. 日後若要改回mpm_prefork模式的話,則反過來做即可
    a2dismod mpm_worker actions
    a2enmod php7.0 mpm_prefork
    systemctl restart apache2
  18. 記得刪掉php-fpm程序
     ps aux|grep php-fpm|awk '{print $2}'|xargs kill -9


參考自:https://www.jianshu.com/p/1e7273aa129f

OB2D主機架設

7-3 Event 模式

這個是Apache中最新的模式,在現在版本裡的已經是穩定可用的模式。它和worker模式很像,最大的區別在於,它解決了keep-alive場景下,長期被佔用的線程的資源浪費問題(某些線程因為被keep-alive,空掛在哪裡等待,中間幾乎沒有請求過來,甚至等到超時)。

event MPM中,會有一個專門的線程來管理這些keep-alive類型的線程,當有真實請求過來的時候,將請求傳遞給服務線程,執行完畢後,又允許它釋放。這樣增強了高並發場景下的請求處理能力。

event MPM在遇到某些不兼容的模塊時,會失效,將會回退到worker模式,一個工作線程處理一個請求。官方自帶的模塊,全部是支持event MPM的。

注意一點,event MPM需要Linux系統(Linux 2.6+)對EPoll的支持,才能啟用。
  1. 更新套件庫
    apt-get update
  2. 升級套件
    apt-get upgrade
  3. 安裝php-fpm
    #for Debian 10 Buster
    apt-get install -y php7.3-fpm
    
    #for Debian 9 Stretch
    apt-get install -y php7.0-fpm 
    
    #for Debian 8 Jessie
    apt-get install -y php5.6-fpm 
  4. 關閉mpm_prefork 相關模組 (php版本請自行調整) 、開啟 mpm_event 相關模組並啟用 php-fpm 設定,最後重啟apache使之生效
    a2dismod php7.0 mpm_prefork
    a2enmod  mpm_event proxy_fcgi setenvif
    a2enconf php7.0-fpm
    systemctl restart apache2
  5. 設定 php.ini,可參考 https://campus-xoops.tn.edu.tw/modules/tad_book3/page.php?tbdsn=220
    #for Debian 10 Buster
    vi /etc/php/7.3/fpm/php.ini
    
    #for Debian 9 Stretch
    vi /etc/php/7.0/fpm/php.ini
    
    #for Debian 8 Jessie
    vi /etc/php/5.6/fpm/php.ini
  6. 修改後請重啟apache
    systemctl restart apache2
  7. 重啟 php-fpm 後 php.ini 才會生效,先找出 php-fpm: master process 的程序編號
    ps aux|grep php-fpm
  8. 然後根據程序編號執行以下指令即可重啟 php-fpm
    kill -USR2 程序編號
  9. 編輯 mpm_event 設定檔
    vi /etc/apache2/mods-available/mpm_event.conf
  10. 建議內容如下:
    <IfModule mpm_event_module>
        StartServers             3
        MinSpareThreads         75
        MaxSpareThreads        250
        ThreadsPerChild         25
        MaxRequestWorkers      400
        MaxConnectionsPerChild   0
    </IfModule>
    
    • StartServers:一開始建立的子進程數,每個子進程中包含固定的ThreadsPerChild線程數
    • MinSpareServers:最小數量的服務器進程,保存備用(最大預設值是75,達此數就不再主動建立新的進程,如果站點負載較大,可加大此值)
    • MaxSpareServers:最大數量的服務器進程,保存備用(最大預設值是250,空閒進程數大於此值時,Apache會自動kill掉一些多餘進程。故不要設得過大,如果站點負載較大,可加大此值)
    • ThreadsPerChild: 每個子進程的線程數(預設值是64, 如果負載較大,64也是不夠的。這時要顯式使用 ThreadLimit 指令,它的最大預設值是 20000)
    • MaxRequestWorkers: 如果現有子進程中的線程總數不能滿足負載,控制進程將派生新的子進程
    • MaxConnectionsPerChild:設置的是每個子進程可處理的請求數(0意味著子進程永不銷毀,但不建議,舊名MaxRequestsPerChild )
  11. Worker模式下所能同時處理的請求總數=子進程總數xThreadsPerChild ,請求總數應該 >= MaxRequestWorkers。
  12. 如果負載很大,現有的子進程數不能滿足時,控制進程會派生新的子進程。
  13. 默認最大的子進程總數是16,加大時 也需要顯式聲明ServerLimit(最大值是20000)
  14. 需要注意的是,如果顯式聲明了ServerLimit,那麼它乘以 ThreadsPerChild的值必須大於等於MaxRequestWorkers,而且MaxRequestWorkers必須是ThreadsPerChild的整數倍,否則 Apache將會自動調節到一個相應值。
  15. 修改 /uploads/.htaccess
    vi /var/www/html/uploads/.htaccess
  16. 最後重新啟動Apache
    systemctl restart apache2
  17. 刪掉 php_flag engine off,並在最後加入:
    <Files "*.php">
      SetHandler none
      SetHandler default-handler
      Options -ExecCGI
      RemoveHandler .php
    </Files>
  18. 日後若要改回mpm_prefork模式的話,則反過來做即可
    a2dismod mpm_event proxy_fcgi setenvif
    a2enmod php7.0 mpm_prefork
    systemctl restart apache2
  19. 記得刪掉php-fpm程序
     ps aux|grep php-fpm|awk '{print $2}'|xargs kill -9

OB2D主機架設

7-4 修改Apache 設定

一、讓主網站的 .htaccess 可用

編輯 apache 主設定檔

vi /etc/apache2/apache2.conf 

找到目錄設定,將設定修改成下方這樣:

<Directory /var/www/html>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

二、預設編碼改為UTF-8

將Apache預設編碼設為UTF-8,避免網頁錯誤訊息為亂碼

vi /etc/apache2/conf-available/charset.conf

拿掉#即可

AddDefaultCharset UTF-8

 

 

OB2D主機架設

7-5 啟動使用者家目錄及PHP功能

  1. 啟動使用者家目錄功能模組
    a2enmod userdir

     

  2. 設定使用者家目錄
    vi /etc/apache2/mods-enabled/userdir.conf

     

  3. 設定AllowOverride All(記得把 Options 後面的 Indexes 刪除)
    <IfModule mod_userdir.c>
            UserDir public_html
            UserDir disabled root
    
            <Directory /home/*/public_html>
                    AllowOverride All
                    Options MultiViews IncludesNoExec FollowSymLinks
                    Require method GET POST OPTIONS
            </Directory>
    </IfModule>
    

     

  4. 編輯使用者PHP設定檔:
    ##for Debian 10 Buster
    vi /etc/apache2/mods-available/php7.3.conf
    #for Debian 9 Stretch
    vi /etc/apache2/mods-available/php7.0.conf
    #for Debian 8 Jessie
    vi /etc/apache2/mods-available/php5.conf

     

  5. 啟用PHP(註解掉最下面5行)
    <FilesMatch ".+\.ph(ar|p|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>
    <FilesMatch ".+\.phps$">
        SetHandler application/x-httpd-php-source
        # Deny access to raw php sources by default
        # To re-enable it's recommended to enable access to the files
        # only in specific virtual host or directory
        Require all denied
    </FilesMatch>
    # Deny access to files without filename (e.g. '.php')
    <FilesMatch "^\.ph(ar|p|ps|tml)$">
        Require all denied
    </FilesMatch>
    
    # Running PHP scripts in user directories is disabled by default
    #
    # To re-enable PHP in user directories comment the following lines
    # (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
    # prevents .htaccess files from disabling it.
    #<IfModule mod_userdir.c>
    #    <Directory /home/*/public_html>
    #        php_admin_flag engine Off
    #    </Directory>
    ##</IfModule>
    

     

  6. 重啟apache完工!
    service apache2 restart

     

OB2D主機架設

7-6 啟用HTTP2

  1. 開啟 mod_http2 模組
    a2enmod http2
  2. 修改網站設定檔(若有其他走80port主機也請一併修改)
    vi /etc/apache2/sites-available/000-default.conf
  3. 加入以下設定
    <VirtualHost *:80>
            Protocols h2c http/1.1
            ServerAdmin webmaster@localhost
            DocumentRoot /var/www/html
    
    
  4. 修改SSL網站設定檔(若有其他走443port主機也請一併修改)
    vi /etc/apache2/sites-available/default-ssl.conf
  5. 加入以下設定
    <IfModule mod_ssl.c>
            <VirtualHost _default_:443>
                    Protocols h2 http/1.1
                    ServerAdmin webmaster@localhost
    
                    DocumentRoot /var/www/html
    
  6. 重啟Apache
    service apache2 restart
  7. 測試網站是否成功支援 http/2
    https://tools.keycdn.com/http2-test

OB2D主機架設

7-7 加入SSL

已不建議使用以下的服務來建置SSL,強烈建議改用 https://certbot.eff.org/

  1. 先到 https://www.sslforfree.com/ 輸入網址
  2. 按下中間的「Manual Verification」也就是手動上傳驗證
  3. 按一下「Manually Verify Domain」
  4. 點擊「Download File #1」下載一個檔名看起來像亂碼的檔案
  5. 接著到您自己的主機網頁目錄下,建立 .well/ acme-challenge 資料夾,並將該檔案上傳到該資料夾底下
  6. 點一下網頁上的驗證連結
  7. 若畫面上有出現一串字碼,那就表示OK(放對位置)。
  8. 按一下「Download SSL Certificate」按鈕,以產生或下載憑證。
  9. 下載憑證:
  10. 下載後,解壓縮,會得到三個檔,上傳至任一位置,如:/etc/ssl
  11. 先安裝OpenSSL,並啟動 Apache2 的 SSL 模組
    apt-get install openssl
    a2enmod ssl
  12. 編輯 default-ssl 設定檔案
    vi /etc/apache2/sites-available/default-ssl.conf
  13. 分別設定底下這三個參數:
  14. 儲存後, 加入Aapche2的SSL網站設定檔, 並重新啟動 Apache2
    cd /etc/apache2/sites-enabled
    ln -s ../sites-available/default-ssl.conf
    service apache2 restart
  15. 接著,就可以用 https://網址 來瀏覽您的網站。

OB2D主機架設

7-8 跨域或設定可被崁入網站

現在大多預設網站無法被別人用框架崁入,但若是有特殊情形,例如網站上有架設公佈欄,需要讓別的網站崁入,那遍需要做此設定。

  1. 直接使用 .htaccess(放網頁目錄下) 允許部份網站崁入,例如:

    Header set X-Frame-Options http://odata.tn.edu.tw

     

  2. 若允許多個網站崁入,一樣用.htaccess
    Header always unset X-Frame-Options

     

OB2D主機架設

7-9 修改phpmyadmin 連線範圍

phpmyadmin 是用來管理資料庫的工具,預設只能在同網段中連線,若希望遠端也可以連線,必須改一下設定檔:

vi /etc/apache2/conf.d/ra-phpmyadmin

例如:

allow from 127.0.0.1 120.115.3.0/24 106.104.14.111

120.115.3.0/24 是中心網段

106.104.14.111 是我家IP

請視需求自己修改

修改後記得重新啟動 apache

service apache2 restart

啟動後執行phpMyAdmin

http://網址/phpmyadmin

若出現 Not Fund 請重新執行設定檔

dpkg-reconfigure phpmyadmin

若一直沒辦法,請先移除 phpmyadmin

apt-get remove --purge phpmyadmin

再重裝

apt-get install phpmyadmin

重裝的一個畫面請選「否」,後面步驟的「apache」記得空白標記星號。下一步即完成。

OB2D主機架設

8. 安裝Nginx(非必須)

  1. 安裝
    apt install nginx

     

  2. 觀看狀態
    systemctl status nginx

     

  3. 若有 nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument 的錯誤
    mkdir /etc/systemd/system/nginx.service.d
    printf "[Service]\nExecStartPost=/bin/sleep 0.1\n" > /etc/systemd/system/nginx.service.d/override.conf
    systemctl daemon-reload
    systemctl restart nginx 

     

  4. 手動啟動
    systemctl start nginx

     

  5. 自動啟動
    systemctl enable nginx

     

  6. 查看版本
    nginx -v

     

  7. 檢查設定是否正確
    nginx -t

     

  8. 在網頁目錄建立預設網頁:
    vi /var/www/html/index.html

     

  9. index.html的內容為
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        網頁已開通!
    </body>
    </html>

     

  10. 可開啟瀏覽器,輸入IP,試試是否OK。
    http://網址或IP/

     

OB2D主機架設

8-1 安裝PHP-FPM

  1. 讓Nginx可以支援PHP,先安裝PHP套件
    apt -y install php php-fpm php-common php-pear php-mbstring

     

  2. 查看PHP版本
    php --version

     

  3. 手動啟用PHP-FPM
    systemctl start php7.3-fpm

     

  4. 開機自動啟用PHP-FPM
    systemctl enable php7.3-fpm

     

  5. 檢查PHP-FPM運行狀態
    systemctl status php7.3-fpm

     

  6. 編輯設定檔
    vi /etc/nginx/sites-available/default

     

  7. 在server{}中加入
      location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
      }
    

     

  8. 重啟PHP-FPM及nginx
    systemctl restart php7.3-fpm nginx 

     

  9. 建立測試檔案
    vi /var/www/html/index.php

     

  10. 內容為
    <?php
    phpinfo();

     

  11. 開啟瀏覽器試試吧!
    http://網址或IP/index.php

     

OB2D主機架設

8-2 啟用使用者目錄

  1. 編輯設定檔
    vi /etc/nginx/sites-available/default 

     

  2. server{}中加入:
      location ~ ^/~(.+?)(/.*)?$ {
        alias /home/$1/public_html$2;
        index  index.html index.htm index.php;
        autoindex on;
      }

     

  3. 至此,已經支援使用者家目錄網頁。可建立新使用者並測試之。
    adduser somebody

     

  4. 建立使用者網頁目錄
    mkdir /home/somebody/public_html

     

  5. 建立網頁檔:
    vi /home/somebody/public_html/index.html

     

  6. 其內容為:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        網頁已開通!
    </body>
    </html>

     

  7. 接著讓使用者加目錄網頁也可以支援PHP,編輯設定檔
    vi /etc/nginx/sites-available/default 

     

  8. server{}中的location ~ ^/~(.+?)(/.*)?$ {上方加入:
      location ~* ^/~(.+?)(/.*\.php)$ {
        alias /home/$1/public_html$2;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
      }
    
      location ~ ^/~(.+?)(/.*)?$ {
        alias /home/$1/public_html$2;
        index  index.html index.htm index.php;
        autoindex on;
      }

     

  9. 重啟伺服器即可
    systemctl restart nginx 

     

OB2D主機架設

8-3 安裝 MariaDB

  1. 安裝
    apt install mariadb-server mariadb-client

     

  2. 狀態
    systemctl status mariadb

     

  3. 手動啟動
    systemctl start mariadb

     

  4. 開機自動啟動
    systemctl enable mariadb

     

  5. 設定密碼及安全設定
    mysql_secure_installation

     

  6. 查看版本
    mariadb --version

     

  7. 安裝 php-mysql
    apt install php7.3-mysql

     

OB2D主機架設

8-4 網站伺服器效能優化

  1. 可先參考以下文件:
    1. https://gist.github.com/holmberd/44fa5c2555139a1a46e01434d3aaa512
    2. https://blog.gtwang.org/linux/nginx-php-fpm-configuration-optimization/
    3. https://www.kancloud.cn/digest/php-src/136260
  2. 找出目前可用記憶體:
    free -h
    root@ic:/etc/php/7.3/fpm/pool.d# free -h
                  total        used        free      shared  buff/cache   available
    Mem:          7.8Gi       988Mi       514Mi        39Mi       6.3Gi       6.7Gi
    Swap:         2.0Gi        30Mi       2.0Gi

    先計算每個php行程需要的記憶體,例如:38M
    ps --no-headers -o "rss,cmd" -C php-fpm7.3 | awk '{ sum+=$1 } END { printf ("%d%s\n", sum/NR/1024,"M") }'

    計算max_children數

    (6.7*1024)/38=180

     

  3. 編輯php的設定檔
    vi /etc/php/7.3/fpm/pool.d/www.conf

    修改以下幾個設定項目:

    pm.max_children = 180
    pm.start_servers = 20
    pm.min_spare_servers = 5
    pm.max_spare_servers = 35
    pm.max_request = 10000

     

  4. 最後重啟PHP
    systemctl restart php7.3-fpm

     

OB2D主機架設

9. 修改mysql密碼

直接用指令修改(適用各種版本):推薦使用

sudo mysql -u root mysql
use mysql;
UPDATE mysql.user SET Password=PASSWORD('新密碼') WHERE User='root';
UPDATE user set plugin='' where User='root';
FLUSH PRIVILEGES;

若要試試有無成功,只要輸入以下指令,輸入密碼登入試試即可:

mysql -u root -p

以下方法在2017年版(v1.2版以前)可能會無作用...

有圖形界面的

  1. 執行 ob2d-init (不要用 root 權限!用你安裝 OB2D 時建立的管理者帳號,在提示字元下 (:~$ ) 直接執行 ob2d-init)
    ob2d-init
    

文字界面的

  1. 安裝 ob2d-init-txt 套件
    apt-get install ob2d-init-txt
    
  2. 以 以管理員身份(不是root喔,是安裝OB2D時設定的那個管理員帳號)執行 ob2d-init-txt (不必用 sudo 執行)

    ob2d-init-txt
    
  3. 安裝後進入mysql操作界面
    mysql -u root -p mysql
  4. 然後執行以下指令:

    update user set plugin='' where User='root';
    flush privileges;
    \q

     

 

 

OB2D主機架設

9-1 優化MySQL

新方式

  1. 連至 https://tools.percona.com/wizard 並按照順序填寫






  2. 先備份原來的設定檔
    cd /etc/mysql/mariadb.conf.d/
    cp 50-server.cnf 50-server.cnf.bak

     

  3. 得到最後結果後,將之複製到底下設定檔
    vi /etc/mysql/mariadb.conf.d/50-server.cnf

     

  4. 修改其中的幾個設定儲存後重啟mysql(請自行根據主機狀況來調整):
    socket                         = /var/run/mysqld/mysqld.sock
    pid-file                       = /var/run/mysqld/mysqld.pid
    

    註解掉log-bin(否則會有大量log產生拖慢效能)

    # BINARY LOGGING #
    #log-bin                        = /var/lib/mysql/mysql-bin
    #expire-logs-days               = 14
    #sync-binlog                    = 1
    

    註解掉slow-query-log (否則可能會有超巨型log產生)

    # LOGGING #
    log-error                      = /var/lib/mysql/mysql-error.log
    log-queries-not-using-indexes  = 1
    #slow-query-log                 = 0
    #slow-query-log-file            = /var/lib/mysql/mysql-slow.log
    

     

手動方式:(不太建議)

  1. 下載檢測程式,並賦予執行權限
    cd ~
    wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/mysqltuner.pl
    chmod +x mysqltuner.pl
  2. 執行之:

    perl mysqltuner.pl --user root --pass '密碼'
  3. 建議:

    Variables to adjust:
        query_cache_size (=0)
        query_cache_type (=0)
        performance_schema = ON enable PFS
        innodb_log_file_size should be (=16M) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
        innodb_buffer_pool_instances (=1)
    

     

  4. 開啟設定檔,針對紅色[!!] 的結果來做改善與調教:

    vi /etc/mysql/mariadb.conf.d/50-server.cnf
  5. 修改設定如:

    skip-name-resolve=1
    
    max_connections         = 300
    
    query_cache_limit       = 1M
    query_cache_size        = 0
    query_cache_type        = 0
    performance_schema      = ON
    
  6. 重啟資料庫服務即可。

  7. 查詢資料庫最大佔用記憶體語法:

    SELECT ( @@key_buffer_size
    + @@query_cache_size
    + @@innodb_buffer_pool_size
    + @@innodb_additional_mem_pool_size
    + @@innodb_log_buffer_size
    + @@max_connections * ( @@read_buffer_size
    + @@read_rnd_buffer_size
    + @@sort_buffer_size
    + @@join_buffer_size
    + @@binlog_cache_size
    + @@thread_stack
    + @@tmp_table_size )
    ) / (1024 * 1024 * 1024) AS MAX_MEMORY_GB;

     

OB2D主機架設

9-2 讓資料庫可以讓別的主機連線

  1. 若想讓主機的資料庫也開放給其他機器連線
  2. 先在防火牆加入設定
    vi /etc/rc.local
  3. 加入3306 port 的設定,例如:

    $IPTABLES -A INPUT -p tcp -s 120.115.2.0/24 --dport 3306 -j ACCEPT
    $IPTABLES -A INPUT -p tcp -s 120.115.3.0/24 --dport 3306 -j ACCEPT
    $IPTABLES -A INPUT -p tcp -s 127.0.0.1 --dport 3306 -j ACCEPT
    $IPTABLES -A INPUT -p tcp --dport 3306 -j DROP
  4. 重新套用防火牆
    /etc/rc.local
  5. 解除資料庫IP綁訂
    vi /etc/mysql/mariadb.conf.d/50-server.cnf
  6. 將裡面的bind-address標記起來

    #bind-address           = 127.0.0.1
    
  7. 重啟資料庫即可

    service mysql restart
  8. 接著就是在資料庫開權限即可。

OB2D主機架設

10. 修改網卡及ip等資訊

如果主機要換IP,或者這是做好的虛擬機檔案,想要複製在開另一臺機器,那必然會遇到改IP的需求。

先找出有啟動的網卡,如 eth0

ifconfig -a

修改網卡及ip等資訊

vi /etc/network/interfaces

底下的IP、閘道器、DNS...等請自行視情況修改

auto lo eth0
iface lo inet loopback

# The primary network interface
allow-hotplug eth0
iface eth0 inet static
        address 120.115.2.90
        netmask 255.255.255.0
        network 120.115.2.0
        broadcast 120.115.2.255
        gateway 120.115.2.253
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 163.26.1.1
        dns-search tn.edu.tw
iface eth0 inet6 static
        address 2001:288:7201:2::90
        netmask 64
        gateway 2001:288:7201:2::fffe

更簡易的寫法:

auto lo eth0
iface lo inet loopback

# The primary network interface
allow-hotplug eth0
iface eth0 inet static
        address 120.115.2.90/24
        gateway 120.115.2.253
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 163.26.1.1
        dns-search tn.edu.tw
iface eth0 inet6 static
        address 2001:288:7201:2::90
        netmask 64
        gateway 2001:288:7201:2::fffe

修改 /etc/hosts(一樣請自行修改IP及網址)

vi /etc/hosts
127.0.0.1       localhost
120.115.2.90    campus-xoops.tn.edu.tw  

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

修改hostname

vi /etc/hostname

將內容改為主機名稱,如:campus-xoops,接著在手動改一下(立即呈現)

hostname  campus-xoops

查詢主機版本以及hostname

uname -a

修改DNS設定

vi /etc/resolv.conf
search campus-xoops.tn.edu.tw
nameserver 163.26.1.1

重啟網路

service networking restart

這樣IP就改好了!

OB2D主機架設

11. 設定IPv6

  1. 各校的 ipv6 網址:http://web.tn.edu.tw/forum/?p=641
  2. 關於IPv6的觀念:http://www.techbang.com/posts/10966-ipv6-ready-growth-of-128bits-die-company-mis-computer-king-97-special-report-5
  3. 編輯網路設定
    vi /etc/network/interfaces
  4. 加入IPV6設定(記得改IP)
    iface eth0 inet6 static
            address 2001:288:7201:2::99
            netmask 64
            gateway 2001:288:7201:2::fffe
  5. 中心範例:中心電腦教室IPv6網段為 2001:288:7201:12::桌號
    iface enp0s3 inet6 static
            address 2001:288:7201:12::D05
            netmask 64
            gateway 2001:288:7201:12::fffe
    
  6. 重啟網路
    systemctl restart network
  7. 開瀏覽器測試
    http://[2001:288:7201:2::99]
    或
    http://[2001:288:7201:12::d05]

     

OB2D主機架設

12. 關閉 mail relay

直接執行

dpkg-reconfigure postfix

其中第一個畫面(還是第二個?)選項選擇「Local only」即可

後面的就視需求設定,或直接用預設值即可。

 

OB2D主機架設

13. 自動時間校正

  1. 使用 APT 安裝 NTP 套件:
    apt-get install ntp ntpdate

     

  2. 執行下列指令即讓系統時間與 time.stdtime.gov.tw 的時間同步,並 修改BIOS時間 :
    ntpdate -s time.stdtime.gov.tw
    hwclock --systohc
  3. 加入自動排程
    crontab -e
    

     

  4. 每天5:10自動校時
    10 5 * * * root /usr/sbin/ntpdate -s time.stdtime.gov.tw

    */30 * * * * (/usr/sbin/ntpdate -s time.stdtime.gov.tw;/sbin/hwclock -w) > /dev/null 2>&1

     

OB2D主機架設

14. 加入monit監控

  1. 安裝
    apt-get install monit -y
  2. 啟動服務

    systemctl start monit
    systemctl enable monit
  3. 可以利用與下指令觀察執行狀態

    systemctl status monit

主要設定

  1. 編輯設定檔

    vi /etc/monit/monitrc
  2. 設定網監看服務(2812 port 可不改,或自行修改,因為中心只開放3389,所以,才修改之),另外,偵測系統swap若超過75%就重啟apache

    set mailserver mail.tn.edu.tw,               # 設定郵寄伺服器
                     localhost                   # fallback relay
    
    set mail-format {
      from:    Monit <monit@$HOST>
      subject: 通知 $HOST --  $EVENT $SERVICE
      message: 
      $EVENT => $SERVICE
      日期: $DATE
      動作: $ACTION
      主機: $HOST
      說明: $DESCRIPTION
      http://網址:port
    }
    
    set alert tad@tn.edu.tw                       # 接收所有 alerts 訊息的信箱
    
    set httpd port 3389 and
        use address 0.0.0.0      # 我要讓他可以對外連線
        allow 0.0.0.0/0.0.0.0   # 開放所有IP都可以連得到
        allow 帳號:密碼      # require user 'admin' with password 'monit'
    
    check system $HOST
    if loadavg (1min) > 4 then alert
    if loadavg (5min) > 2 then alert
    if cpu usage > 95% for 10 cycles then alert
    if memory usage > 75% then alert
    if swap usage > 25% then alert
    if swap usage > 75% for 5 cycles then exec "/usr/sbin/apachectl restart"
    
  3. 修改後,重啟服務

    systemctl restart monit
  4. 看看是否有在監聽

    netstat -ant | grep :3389
  5. 此時可自行輸入「http://網址:3389」看看是否能登入觀看。亦可下指令在終端機中觀看狀態:

    monit status
  6. 加入Apache、MySQL、Rsyslog監控

    ln -s /etc/monit/conf-available/apache2 /etc/monit/conf-enabled/
    ln -s /etc/monit/conf-available/mysql /etc/monit/conf-enabled/
    ln -s /etc/monit/conf-available/rsyslog /etc/monit/conf-enabled/
  7. 2017年以前的版本為
    ln -s /etc/monit/monitrc.d/apache2 /etc/monit/conf.d/
    ln -s /etc/monit/monitrc.d/mysql /etc/monit/conf.d/
    ln -s /etc/monit/monitrc.d/rsyslog /etc/monit/conf.d/
  8. 記得重啟,使之生效

    systemctl restart monit

讓記憶體不足時,Apache2自動啟動

  1. 修改給Apache用的設定檔
    vi /etc/monit/conf-available/apache2
  2. 加入一行到原有 if 的前面:

    if memory usage > 80% for 5 cycles then restart
  3. 記得重啟,使之生效

    systemctl restart monit

讓MySQL可以連接得上

  1. 修改給MySQL用的設定檔
    vi /etc/monit/conf-available/mysql
  2. 將第6行註解掉:

    #if failed host localhost port 3306 protocol mysql with timeout 15 seconds for 3 times within 4 cycles then restart
  3. 記得重啟,使之生效

    systemctl restart monit

OB2D主機架設

15. 預設使用者目錄內容

  1. 進入 /etc/skel/ 編輯其內容即可
    cd /etc/skel/
    mkdir public_html
    
  2. 下載 https://campus-xoops.tn.edu.tw/modules/tad_uploader/index.php?op=dlfile&cfsn=112&cat_sn=11

  3. 解壓上傳至/etc/skel/public_html即可。

建立使用者

  1. 利用下列指令建立使用者:
    adduser 使用者名稱
  2. 接著,在瀏覽器輸入「http://網址/~使用者名稱」即可看到使用者的網頁

OB2D主機架設

16. 大量建立帳號

  1. http://myip.tw/itsmw/index.php?title=YHTools
  2. 下載:
    wget http://myip.tw/download/yhtools.tar.gz
    
  3. 解壓:
    tar xzvf yhtools.tar.gz
    
  4. maccount.sh 是以 BASH 寫成的大量建帳號工具,支援 samba 同步及 MySQL 同名資料庫建立。請切換至 yhtools/maccount 底下:
    cd  yhtools/maccount
    
  5. 編輯帳號密碼表「passwd.txt」:
    vi passwd.txt
    
  6. 大量新增帳號:
    ./maccount.sh add passwd.txt
    
  7. 大量新增資料庫帳號:
    ./maccount.sh mysql passwd.txt

OB2D主機架設

17. 修正 /etc/rc.local 無效問題

  1. 這是因為 Debian9、10之後,就不再支援 /etc/rc.local 的關係,故可以將之做為 service來啟用即可
  2. 建立 service
    cat <<EOF >> /etc/systemd/system/rc-local.service
    [Unit]
    Description=/etc/rc.local
    ConditionPathExists=/etc/rc.local
    
    [Service]
    Type=forking
    ExecStart=/etc/rc.local start
    TimeoutSec=0
    StandardOutput=tty
    RemainAfterExit=yes
    SysVStartPriority=99
    
    [Install]
    WantedBy=multi-user.target
    EOF

     

  3. 自行建立好需要的/etc/rc.local內容,然後賦予執行權限
    chmod +x /etc/rc.local

     

  4. 開啟自動啟用該 service
    systemctl enable rc-local

     

  5. 手動啟用方式:
    systemctl start rc-local

     

  6. 查看狀態
    systemctl status rc-local

     

OB2D主機架設

18. 異地備份

  1. 先準備好一台異地的主機,拿來放備份檔用,以下簡稱「備份主機」
  2. 本文的備份主機以IAAS(即台南試飛番雲的VM服務)為例,環境為ubuntu。

一、下載備份程式

  1. ensshRsync.sh 程式由卓國興老師開發
    cd ~
    wget https://campus-xoops.tn.edu.tw/uploads/ensshRsync.zip
    unzip ensshRsync.zip
    chmod +x ensshRsync.sh
    
  2. 編輯 ensshRsync.sh 內容
    #本地端要備份的目錄
    backuplist="/var/www /var/lib/mysql"
    
    #遠端備份主機的IP OR DomainName
    remote="120.115.1.1"
    
    #頻寬設定
    limit=5000
    
    #recycle保留的設定
    recyclekeep=7
    
    #備份的主機使用者名稱
    remoteUser="root"
    # remoteUser="使用者帳號"
    
    #備份的主機使用者家目錄
    remoteHome="/root"
    #remoteHome="/home/${remoteUser}"
    
    #備份的目錄名稱
    remoteDIR="${remoteHome}/backup"
    1. backuplist:要備份的目錄路徑,多個請用空白隔開

    2. remote:備份主機的IP

    3. limit:5000就是5M,若不想限制頻寬,將之註解掉即可。

    4. recyclekeep:備份份數,若一天備份一次,設成7就是可還原至7天前資料之意。

    5. remoteDIR:備份主機放備份資料的資料夾(該資料夾會自動建立無須手動建立)

    6. remoteUser:登入遠端主機的ssh帳號

    7. remoteHome:遠端主機的ssh帳號的加目錄,如果身份不是root,請改用#remoteHome="/home/${remoteUser}"

二、執行備份

  1. 執行之
    ./ensshRsync.sh
  2. 前三個問題都直接按Enter略過
    Enter file in which to save the key (/root/.ssh/id_rsa):
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    
  3. 直到出現以下問句,輸入 yes 繼續

    Are you sure you want to continue connecting (yes/no)
  4. 接著會要求輸入備份主機的ssh密碼,請輸入之即可(有可能需要輸入數次)。

三、加入排程

  1. 記得加入排程
     crontab -e
  2. 每天三點自動備份(時間可以自己修改)

    0  3 * * * /root/ensshRsync.sh
    

四、還原

  1. 若欲還原資料,直接在主機的 /root 下,執行 getMyBackup.sh 即可,例如:
    ./getMyBackup.sh
  2. 注意,一執行就會開始自動把備份資料全部抓回原主機(會另外放在backup資料夾下,不會直接覆蓋原檔案),所以,沒事別亂執行。

五、建立ISSA虛擬機

  1. 登入 https://cloud.dcs.tn.edu.tw,點選「虛擬機器」→「建立虛擬機器」
  2. 使用「快速建立」,選好範本,設定root密碼即可。
  3. 生成後,點選名稱
  4. 查到IP即可。

OB2D主機架設

19. 安裝docker

以下內容參考自:

  1. 先修改sources.list
    vi /etc/apt/sources.list
  2. 加上docker的套件來源
    deb https://apt.dockerproject.org/repo debian-jessie main #2016 年的 jessie 請加這行
    deb https://apt.dockerproject.org/repo debian-stretch main #2017 年後的 stretch 請加這行
  3. 執行套件更新,然後安裝必要套件
    apt-get update
    apt-get install apt-transport-https ca-certificates dirmngr
  4. 新增堧體來源的gpg金鑰
    apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
  5. 開始安裝docker
    apt-get install docker-engine
  6. 啟動docker
    systemctl start docker
  7. 設定開機自動啟動
    systemctl enable docker
  8. 查看 docker 狀態
    systemctl status docker
  9. 進行測試
    docker run hello-world
  10. 或者下述一行搞定:(取自:Example: Install Docker on Ubuntu Linux - Docker)
    curl -fsSL https://get.docker.com/ | sh

Docker engine 移除

  1. 移除相關套件
    apt-get purge docker-engine
    apt-get autoremove --purge docker-engine
  2. 移除docker images
    rm -rf /var/lib/docker

OB2D主機架設

20. 安裝Jitsi meet

  1. 先設好DNS,底下以 meet.lces.tn.edu.tw 網域為例,伺服器用 nginx,先安裝好 cert-bot,以便安裝憑證。
  2. 安裝必要套件
    apt install gnupg

     

  3. 安裝 Jitsi repository key
    wget -qO - https://download.jitsi.org/jitsi-key.gpg.key | sudo apt-key add -

     

  4. 添加套件來源
    sh -c "echo 'deb https://download.jitsi.org stable/' > /etc/apt/sources.list.d/jitsi-stable.list"

     

  5. 更新套件庫
    apt-get -y update

     

  6. 安裝 Jitsi Meet
    apt-get -y install jitsi-meet

     

  7. 安裝憑證
    /usr/share/jitsi-meet/scripts/install-letsencrypt-cert.sh

    若裝不起來請用

    cert-bot --nginx

     

  8. 修改設定檔
    vi /etc/nginx/sites-available/default
    server_names_hash_bucket_size 64;
    
    server {
        listen 80;
        listen [::]:80;
        server_name meet.lces.tn.edu.tw;
    
        location ^~ /.well-known/acme-challenge/ {
           default_type "text/plain";
           root         /usr/share/jitsi-meet;
        }
        location = /.well-known/acme-challenge/ {
           return 404;
        }
        location / {
           return 301 https://$host$request_uri;
        }
    }
    server {
        listen 443 ssl;
        listen [::]:443 ssl;
        server_name meet.lces.tn.edu.tw;
    
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA256:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EDH+aRSA+AESGCM:EDH+aRSA+SHA256:EDH+aRSA:EECDH:!aNULL:!eNULL:!MEDIUM:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SEED";
        
        add_header Strict-Transport-Security "max-age=31536000";
    
        ssl_certificate /etc/letsencrypt/live/meet.lces.tn.edu.tw/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/meet.lces.tn.edu.tw/privkey.pem; # managed by Certbot
    
        root /usr/share/jitsi-meet;
    
        # ssi on with javascript for multidomain variables in config.js
        ssi on;
        ssi_types application/x-javascript application/javascript;
    
        index index.html index.htm;
        error_page 404 /static/404.html;
    
        gzip on;
        gzip_types text/plain text/css application/javascript application/json;
        gzip_vary on;
    
        location = /config.js {
            alias /etc/jitsi/meet/meet.lces.tn.edu.tw-config.js;
        }
    
        location = /external_api.js {
            alias /usr/share/jitsi-meet/libs/external_api.min.js;
        }
    
        #ensure all static content can always be found first
        location ~ ^/(libs|css|static|images|fonts|lang|sounds|connection_optimization|.well-known)/(.*)$
        {
            add_header 'Access-Control-Allow-Origin' '*';
            alias /usr/share/jitsi-meet/$1/$2;
        }
    
        # BOSH
        location = /http-bind {
            proxy_pass      http://localhost:5280/http-bind;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $http_host;
        }
    
        # xmpp websockets
        location = /xmpp-websocket {
            proxy_pass http://127.0.0.1:5280/xmpp-websocket?prefix=$prefix&$args;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $http_host;
            tcp_nodelay on;
        }
    
        location ~ ^/([^/?&:'"]+)$ {
            try_files $uri @root_path;
        }
    
        location @root_path {
            rewrite ^/(.*)$ / break;
        }
    
        location ~ ^/([^/?&:'"]+)/config.js$
        {
           set $subdomain "$1.";
           set $subdir "$1/";
    
           alias /etc/jitsi/meet/meet.lces.tn.edu.tw-config.js;
        }
    
        #Anything that didn't match above, and isn't a real file, assume it's a room name and redirect to /
        location ~ ^/([^/?&:'"]+)/(.*)$ {
            set $subdomain "$1.";
            set $subdir "$1/";
            rewrite ^/([^/?&:'"]+)/(.*)$ /$2;
        }
    
        # BOSH for subdomains
        location ~ ^/([^/?&:'"]+)/http-bind {
            set $subdomain "$1.";
            set $subdir "$1/";
            set $prefix "$1";
    
            rewrite ^/(.*)$ /http-bind;
        }
    
        # websockets for subdomains
        location ~ ^/([^/?&:'"]+)/xmpp-websocket {
            set $subdomain "$1.";
            set $subdir "$1/";
            set $prefix "$1";
    
            rewrite ^/(.*)$ /xmpp-websocket;
        }
    }
    

     

  9. 重啟伺服器
    systemctl restart nginx

     

  10. 大功告成~

OB2D主機架設

22. 漂亮終端機

  1. 執行以下指令即可:
    apt-get install python-pip
    apt-get install git
    pip install git+git://github.com/Lokaltog/powerline
    wget https://github.com/powerline/powerline/raw/develop/font/PowerlineSymbols.otf
    mv PowerlineSymbols.otf /usr/share/fonts/
    wget https://github.com/powerline/powerline/raw/develop/font/10-powerline-symbols.conf
    mv 10-powerline-symbols.conf /etc/fonts/conf.d/
    apt-get install fontconfig 
    fc-cache -vf /usr/share/fonts/
    vi ~/.bashrc
  2. 在檔案裡面加入:

    export TERM="screen-256color"
  3. 找出powerline-status的位置

    pip show powerline-status
  4. 結果如:
    Name: powerline-status
    Version: 2.5.2.dev9999-git.5fa504118ee470e9cc9c8665515b77900ce5821e
    Location: /usr/local/lib/python2.7/dist-packages
    Requires:
    
  5. 將之再加到 ~/.bashrc

    vi ~/.bashrc
  6. 貼上,看起來會像這樣:

    powerline-daemon -q
    POWERLINE_BASH_CONTINUATION=1
    POWERLINE_BASH_SELECT=1
    . /usr/local/lib/python2.7/dist-packages/powerline/bindings/bash/powerline.sh
    
  7. 登出在登入即可看到效果。

  8. 在vim中套用之:

    vi ~/.vimrc
  9. 加入以下語法:

    set  rtp+=/usr/local/lib/python2.7/dist-packages/powerline/bindings/vim/
    set laststatus=2
    set t_Co=256
  10. 安裝

    apt-get install vim-nox
  11. 完整說明:http://www.tecmint.com/powerline-adds-powerful-statuslines-and-prompts-to-vim-and-bash/

OB2D主機架設

23. 常用指令

查看目前的所有服務

netstat -pnltu