# 用 Raspberry Pi 打造 Astro 部落格 + 自動部署到 Cloudflare

Table of Contents

🧰 前置準備

以下是你需要的開發環境與工具:

  • 一台 Raspberry Pi(建議 Raspberry Pi 4 或 400)
  • Raspberry Pi OS + Node.js ≥ 18.20.8
  • npm, git, podman 安裝完成
  • GitHub 帳號(可免費申請)
  • Cloudflare 帳號(啟用 Workers 與 GitHub 整合)

🚀 步驟 1:建立 Astro 專案

打開你的 Raspberry Pi 終端機,輸入以下指令建立 Astro 專案:

Terminal window
npm create astro@latest myastro
cd myastro
npm install

使用預設的 blog 模板即可。若你選擇其他模板也沒問題,流程一致。


✍️ 步驟 2:新增一篇文章

Astro 使用 Markdown (.md) 撰寫文章,文章放在 src/content/blog/ 目錄中。

建立資料夾與檔案:

Terminal window
mkdir -p src/content/blog
nano src/content/blog/hello-from-pi.md

填入以下內容:

---
title: "Hello from Raspberry Pi!"
pubDate: 2025-08-02
description: "這是我用樹莓派寫的第一篇 Astro 部落格文章"
author: "musky"
---
這篇文章是用我的 Raspberry Pi 開發的 Astro 網站內容。

儲存後離開 nano:按 Ctrl + XYEnter


🛠️ 步驟 3:建置 Astro 專案

確保 Node.js 版本符合 Astro 要求(至少 18.20.8)後執行:

Terminal window
npm run build

成功時會出現 /dist 資料夾,內含靜態網站檔案。


🐳 步驟 4:使用 Podman 建立 Docker Image(可選)

若你想將網站包進一個 Image,使用 Dockerfile 如下:

# Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

建置與執行:

Terminal window
podman build -t astro-nginx .
podman run -d -p 8080:80 localhost/astro-nginx

如需掛載網站內容目錄(使用 -v):

Terminal window
podman run -d -p 8080:80 -v /home/musky/myastro/dist:/usr/share/nginx/html:ro localhost/astro-nginx

☁️ 步驟 5:連接 GitHub 並部署到 Cloudflare Workers

  1. 將 Astro 專案推送到 GitHub:
Terminal window
git init
git remote add origin https://github.com/<你的帳號>/<repo名稱>.git
git add .
git commit -m "initial commit"
git push -u origin main
  1. Cloudflare Dashboard
  • 開啟 Workers → 建立新專案
  • 選擇「從 GitHub 導入」
  • 選擇你的 Astro 專案
  • 架設部署後會自動偵測到 Astro 並自動部署

Cloudflare 會自動執行 npm installnpm run build → 發布至 Workers。


🤖 加分功能:建立快速新增文章腳本

建立一個 Bash 腳本快速新增部落格文章:

Terminal window
nano add-post.sh

內容如下:

#!/bin/bash
echo "輸入文章檔名(英文小寫):"
read slug
FILENAME="src/content/blog/$slug.md"
DATE=$(date +%Y-%m-%d)
cat > $FILENAME <<EOF
---
title: "$slug"
pubDate: $DATE
description: "自動產生的 Astro 文章"
author: "musky"
---
這是我用腳本新增的文章!
EOF
git add $FILENAME
git commit -m "新增文章:$slug"
git push origin main

啟用腳本權限:

Terminal window
chmod +x add-post.sh

使用方式:

Terminal window
./add-post.sh

總結

恭喜你完成了:

  • 在 Raspberry Pi 上建立 Astro 專案
  • 撰寫與管理 Markdown 文章
  • 使用 Podman 建立容器
  • 透過 GitHub 自動部署到 Cloudflare Workers
  • 撰寫自動新增文章與部署腳本

🧩 延伸學習建議

  • astro add tailwind:加入 Tailwind CSS 美化網站
  • astro add image:加入圖片壓縮功能
  • 整合 Cloudflare Analytics、留言系統
  • 自訂網域、設定 HTTPS 憑證

📮 有任何問題歡迎留言或開 issue 交流!

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments