在RaspberryPi上建置便宜高效的個人Blog Server

(Ghost + varnish + nginx) x RaspberryPi3 = 超低成本自製節能Blog網頁伺服器!
作為本Blog第一篇文,筆記順便兼測試,就來寫寫這Blog是怎麼建起來的吧,Debian譜系的OS應該皆可直接用。
想快速自架一個hackable的高自由度Blog,使用網路上的代管服務雖然算不上貴但通常每個月也要幾百塊,對窮學生的荷包來說還是很傷,用PC或筆電又太耗電,身為一個沒什麼錢的學生,這時RaspberryPi3就是一個好選擇,體積小耗電少,一塊不到NT$1500就可以放到爽,單看帳面規格也不輸AWS只能用一年的免費實體方案(先不論你家頻寬跟Amazon差多少=0=,適合小流量的個體戶),再寫個腳本搭配 git server 做備份也不怕 Pi 掛掉。
第一步,裝好你的CMS
本文採用的CMS是Ghost,根據網上資料[1]以及我個人實測,以Node.js開發的Ghost在RPi上反應速度確實比以PHP開發、功能強大的Wordpress來的快,看好未來社群的成長、加上本人現正迷Node.js :P 所以採用了Ghost。 首先,必須在RPi上先裝好Node.js(任一個的LTS版都可),接著下載最新版的Ghost解壓縮到你喜歡的地方。
切換到剛解壓的Ghost目錄下,輸入以下指令安裝Ghost
$ npm install --production
在Ghost根目錄下的config.js
內找到如下內容,網址改成你自己的
production: {
url: 'http://my-ghost-blog.com',
讓你的Ghost一開機就自動持續執行
安裝forever,可以讓Node.js的程式就算因不明原因crash掉後也能自動重啟
$ npm install forever -g
在/etc/init.d/
目錄下建立ghost.sh
,輸入以下內容
#!/bin/sh
sudo NODE_ENV=production forever start /{你Ghost的path}/ghost/index.js
讓RPi開機便啟動forever跑Ghost
$ sudo chmod +x /etc/init.d/ghost.sh
$ sudo update-rc.d ghost.sh defaults
重開機後,看看Ghost有沒有正常運作
$ sudo forever list
加速你的RaspberryPi Server
現在來裝Varnish Cache,裝上後以我的RPi網頁反應速度少說快三倍還能減少SD Card或硬碟(看你放哪)的讀取次數,詳細運作原理可看官方文檔。
安裝Varnish Cache
$ sudo apt-get update
$ sudo apt-get install varnish
編輯/etc/varnish/default.vcl
的Varnish configuration,將下述要快取ip和port改成你Ghost的
backend default {
.host = "127.0.0.1";
.port = "8080";
}
- For example:
backend default {
.host = "192.168.0.180";
.port = "2368";
}
接者修改/etc/default/varnish
,varnish用來listening for request的port
DAEMON_OPTS="-a :6081 \
- 一般是改成http的port 80
DAEMON_OPTS="-a :80 \
快完成了,再設定多久鼓勵快取程式自動快取一次,修改Ghost底下的/core/server/middleware/cache-control.js
,會看到
// ### CacheControl Middleware
// provide sensible cache control headers
cacheControl: function (options) {
/*jslint unparam:true*/
var profiles = {
'public': 'public, max-age=XXX',
修改max-age=
後面的值,單位是秒,以下是一些常用的值用做參考
60
(1 minute)3600
(1 hour)86400
(1 day)604800
(1 week)2419200
(28 days)
用sudo service varnish restart
重啟varnish後,到 http://www.isvarnishworking.com/ 來看看你的Turbo booster有沒有開起來吧!
用nginx增加SSL support(自簽:P 非必要)
安裝nginx
$ sudo apt-get install nginx
建一個用來放SSL Key的資料夾,然後產生Key,Common Name欄位記得打你的Domain name
$ sudo mkdir /etc/nginx/ssl
$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
接者修改/etc/nginx/sites-enabled/default
用以下內容覆蓋裡面原本的內容,把server_name
後面的網址改成你的
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
location / {
proxy_pass http://127.0.0.1:80;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Port 443;
proxy_set_header Host $host;
}
}
重啟nginx
$ sudo service nginx start
你可以用 https:// 存取你的網頁了!
註: 因為你這SSL certificate是自己簽的,存取時Broswer可能會警告你XD
Reference: