CDK 常用指令
# 初始化新專案
cdk init app --language typescript

# 部署所有 Stack
cdk deploy --all

# 查看差異
cdk diff

# 銷毀資源
cdk destroy
CDK 最佳實踐
  1. 使用 Environment 變數
const env = {
  account: process.env.CDK_DEFAULT_ACCOUNT,
  region: process.env.CDK_DEFAULT_REGION,
};
  1. 標籤管理
Tags.of(this).add('Project', 'MyProject');
Tags.of(this).add('Environment', 'Production');
AWS CLI 安裝與設定

安裝 AWS CLI:

# macOS (使用 Homebrew)
brew install awscli

# Ubuntu/Debian
sudo apt update
sudo apt install awscli

# 使用 pip 安裝
pip install awscli

# 安裝 AWS CLI v2 (推薦)
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

# 驗證安裝
aws --version

設定 AWS CLI:

# 基本設定
aws configure
# 會提示輸入:
# AWS Access Key ID
# AWS Secret Access Key  
# Default region name (例如: us-east-1)
# Default output format (json/text/table)

# 設定特定 profile
aws configure --profile myprofile

# 查看設定
aws configure list
aws configure list --profile myprofile

# 設定單一參數
aws configure set region ap-northeast-1
aws configure set output json --profile myprofile

環境變數設定:

# 設定環境變數
export AWS_ACCESS_KEY_ID=your_access_key
export AWS_SECRET_ACCESS_KEY=your_secret_key
export AWS_DEFAULT_REGION=us-east-1
export AWS_PROFILE=myprofile

# 查看當前設定
aws sts get-caller-identity
S3 基本操作

Bucket 管理:

# 列出所有 buckets
aws s3 ls

# 建立 bucket
aws s3 mb s3://my-bucket-name
aws s3 mb s3://my-bucket-name --region ap-northeast-1

# 刪除空的 bucket
aws s3 rb s3://my-bucket-name

# 刪除 bucket 及所有內容
aws s3 rb s3://my-bucket-name --force

# 查看 bucket 內容
aws s3 ls s3://my-bucket-name
aws s3 ls s3://my-bucket-name/folder/ --recursive

檔案上傳與下載:

# 上傳單一檔案
aws s3 cp file.txt s3://my-bucket-name/
aws s3 cp file.txt s3://my-bucket-name/folder/

# 下載單一檔案
aws s3 cp s3://my-bucket-name/file.txt ./
aws s3 cp s3://my-bucket-name/folder/file.txt ./downloads/

# 上傳整個目錄
aws s3 cp ./local-folder s3://my-bucket-name/remote-folder --recursive

# 下載整個目錄
aws s3 cp s3://my-bucket-name/remote-folder ./local-folder --recursive

# 同步目錄 (只上傳變更的檔案)
aws s3 sync ./local-folder s3://my-bucket-name/remote-folder
aws s3 sync s3://my-bucket-name/remote-folder ./local-folder

# 移動檔案
aws s3 mv file.txt s3://my-bucket-name/
aws s3 mv s3://my-bucket-name/old-file.txt s3://my-bucket-name/new-file.txt
S3 進階操作

檔案管理:

# 刪除檔案
aws s3 rm s3://my-bucket-name/file.txt

# 刪除目錄及所有內容
aws s3 rm s3://my-bucket-name/folder --recursive

# 設定檔案權限 (ACL)
aws s3 cp file.txt s3://my-bucket-name/ --acl public-read
aws s3 cp file.txt s3://my-bucket-name/ --acl private

# 設定 Content-Type
aws s3 cp index.html s3://my-bucket-name/ --content-type "text/html"

# 設定快取控制
aws s3 cp image.jpg s3://my-bucket-name/ --cache-control "max-age=3600"

# 設定 metadata
aws s3 cp file.txt s3://my-bucket-name/ --metadata "key1=value1,key2=value2"

過濾與排除:

# 只同步特定檔案類型
aws s3 sync ./folder s3://my-bucket-name/ --include "*.jpg"

# 排除特定檔案
aws s3 sync ./folder s3://my-bucket-name/ --exclude "*.tmp"

# 複合條件
aws s3 sync ./folder s3://my-bucket-name/ --exclude "*" --include "*.jpg" --include "*.png"

# 刪除本地不存在的檔案
aws s3 sync ./folder s3://my-bucket-name/ --delete

檔案資訊查詢:

# 查看檔案詳細資訊
aws s3api head-object --bucket my-bucket-name --key file.txt

# 查看檔案大小和數量
aws s3 ls s3://my-bucket-name --recursive --human-readable --summarize

# 查看特定前綴的檔案
aws s3 ls s3://my-bucket-name/logs/ --recursive
S3 靜態網站託管
# 啟用靜態網站託管
aws s3 website s3://my-bucket-name --index-document index.html --error-document error.html

# 上傳網站檔案並設定公開讀取
aws s3 sync ./website s3://my-bucket-name --acl public-read

# 設定 bucket policy (允許公開讀取)
cat > bucket-policy.json << EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-bucket-name/*"
        }
    ]
}
EOF

aws s3api put-bucket-policy --bucket my-bucket-name --policy file://bucket-policy.json

# 查看網站設定
aws s3api get-bucket-website --bucket my-bucket-name

# 停用網站託管
aws s3api delete-bucket-website --bucket my-bucket-name
S3 生命週期管理
# 建立生命週期規則
cat > lifecycle.json << EOF
{
    "Rules": [
        {
            "ID": "DeleteOldFiles",
            "Status": "Enabled",
            "Filter": {
                "Prefix": "logs/"
            },
            "Expiration": {
                "Days": 30
            }
        },
        {
            "ID": "TransitionToIA",
            "Status": "Enabled",
            "Transitions": [
                {
                    "Days": 30,
                    "StorageClass": "STANDARD_IA"
                },
                {
                    "Days": 90,
                    "StorageClass": "GLACIER"
                }
            ]
        }
    ]
}
EOF

# 套用生命週期規則
aws s3api put-bucket-lifecycle-configuration --bucket my-bucket-name --lifecycle-configuration file://lifecycle.json

# 查看生命週期規則
aws s3api get-bucket-lifecycle-configuration --bucket my-bucket-name

# 刪除生命週期規則
aws s3api delete-bucket-lifecycle --bucket my-bucket-name
S3 版本控制
# 啟用版本控制
aws s3api put-bucket-versioning --bucket my-bucket-name --versioning-configuration Status=Enabled

# 查看版本控制狀態
aws s3api get-bucket-versioning --bucket my-bucket-name

# 列出檔案的所有版本
aws s3api list-object-versions --bucket my-bucket-name --prefix file.txt

# 下載特定版本的檔案
aws s3api get-object --bucket my-bucket-name --key file.txt --version-id VERSION_ID output.txt

# 刪除特定版本
aws s3api delete-object --bucket my-bucket-name --key file.txt --version-id VERSION_ID

# 暫停版本控制
aws s3api put-bucket-versioning --bucket my-bucket-name --versioning-configuration Status=Suspended
S3 跨區域複製
# 建立複製規則
cat > replication.json << EOF
{
    "Role": "arn:aws:iam::ACCOUNT_ID:role/replication-role",
    "Rules": [
        {
            "ID": "ReplicateToBackup",
            "Status": "Enabled",
            "Filter": {
                "Prefix": "important/"
            },
            "Destination": {
                "Bucket": "arn:aws:s3:::backup-bucket-name",
                "StorageClass": "STANDARD_IA"
            }
        }
    ]
}
EOF

# 套用複製規則
aws s3api put-bucket-replication --bucket my-bucket-name --replication-configuration file://replication.json

# 查看複製規則
aws s3api get-bucket-replication --bucket my-bucket-name

# 刪除複製規則
aws s3api delete-bucket-replication --bucket my-bucket-name
常用 S3 技巧
# 產生預簽名 URL (臨時存取連結)
aws s3 presign s3://my-bucket-name/file.txt --expires-in 3600

# 計算檔案 MD5 雜湊值
aws s3api head-object --bucket my-bucket-name --key file.txt --query 'ETag' --output text

# 批次操作 (使用 xargs)
aws s3 ls s3://my-bucket-name --recursive | grep ".log" | awk '{print $4}' | xargs -I {} aws s3 rm s3://my-bucket-name/{}

# 監控傳輸進度
aws s3 cp large-file.zip s3://my-bucket-name/ --cli-read-timeout 0 --cli-write-timeout 0

# 設定多部分上傳閾值
aws configure set default.s3.multipart_threshold 64MB
aws configure set default.s3.max_concurrent_requests 10

# 使用不同的 storage class
aws s3 cp file.txt s3://my-bucket-name/ --storage-class STANDARD_IA
aws s3 cp file.txt s3://my-bucket-name/ --storage-class GLACIER

# 加密上傳
aws s3 cp file.txt s3://my-bucket-name/ --sse AES256
aws s3 cp file.txt s3://my-bucket-name/ --sse aws:kms --sse-kms-key-id alias/my-key
Launchpad 管理
# 重置 Launchpad 排列
defaults write com.apple.dock ResetLaunchPad -bool true
killall Dock

# 設定 Launchpad 每頁顯示的 app 數量
# 設定每行顯示數量 (預設 7)
defaults write com.apple.dock springboard-columns -int 8
# 設定每列顯示數量 (預設 5)  
defaults write com.apple.dock springboard-rows -int 6
killall Dock

# 恢復預設設定
defaults delete com.apple.dock springboard-columns
defaults delete com.apple.dock springboard-rows
killall Dock
Dock 設定
# 隱藏/顯示 Dock
defaults write com.apple.dock autohide -bool true
defaults write com.apple.dock autohide -bool false
killall Dock

# 設定 Dock 大小
defaults write com.apple.dock tilesize -int 50
killall Dock

# 設定 Dock 位置 (left, bottom, right)
defaults write com.apple.dock orientation -string "left"
killall Dock

# 移除 Dock 中所有 app (只保留 Finder 和垃圾桶)
defaults write com.apple.dock persistent-apps -array
killall Dock

# 顯示隱藏的 app 圖示 (半透明效果)
defaults write com.apple.dock showhidden -bool true
killall Dock

# 加快 Dock 動畫速度
defaults write com.apple.dock autohide-time-modifier -float 0.5
killall Dock
Finder 設定
# 顯示隱藏檔案
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder

# 隱藏隱藏檔案
defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder

# 顯示副檔名
defaults write NSGlobalDomain AppleShowAllExtensions -bool true
killall Finder

# 顯示路徑列
defaults write com.apple.finder ShowPathbar -bool true

# 顯示狀態列
defaults write com.apple.finder ShowStatusBar -bool true

# 設定預設檢視方式 (icnv=圖示, Nlsv=列表, clmv=欄位, Flwv=Cover Flow)
defaults write com.apple.finder FXPreferredViewStyle -string "Nlsv"

# 設定新 Finder 視窗開啟位置為家目錄
defaults write com.apple.finder NewWindowTarget -string "PfHm"

# 停用清空垃圾桶警告
defaults write com.apple.finder WarnOnEmptyTrash -bool false
截圖設定
# 更改截圖儲存位置
defaults write com.apple.screencapture location ~/Desktop/Screenshots
killall SystemUIServer

# 更改截圖檔案格式 (png, jpg, gif, pdf, tiff)
defaults write com.apple.screencapture type -string "jpg"

# 移除截圖檔名中的陰影
defaults write com.apple.screencapture disable-shadow -bool true

# 截圖不顯示浮動縮圖
defaults write com.apple.screencapture show-thumbnail -bool false

# 截圖快捷鍵
# Cmd+Shift+3: 全螢幕截圖
# Cmd+Shift+4: 選取區域截圖  
# Cmd+Shift+4+Space: 視窗截圖
# Cmd+Shift+5: 截圖工具列
系統資訊查詢
# 查看 macOS 版本
sw_vers
sw_vers -productVersion

# 查看系統資訊
system_profiler SPSoftwareDataType
system_profiler SPHardwareDataType

# 查看 CPU 資訊
sysctl -n machdep.cpu.brand_string
sysctl -n hw.ncpu  # CPU 核心數

# 查看記憶體資訊
sysctl -n hw.memsize  # 總記憶體 (bytes)
vm_stat  # 記憶體使用統計

# 查看磁碟使用情況
df -h
diskutil list

# 查看網路介面
ifconfig
networksetup -listallhardwareports

# 查看已安裝的應用程式
ls /Applications
system_profiler SPApplicationsDataType
網路設定
# 查看網路設定
networksetup -listallhardwareports
networksetup -getinfo "Wi-Fi"

# 設定 DNS
sudo networksetup -setdnsservers "Wi-Fi" 8.8.8.8 1.1.1.1
sudo networksetup -setdnsservers "Wi-Fi" Empty  # 清除 DNS

# 重新整理 DNS 快取
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

# 查看 Wi-Fi 密碼 (需要管理員密碼)
security find-generic-password -wa "WiFi名稱"

# 掃描 Wi-Fi 網路
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s

# 連接 Wi-Fi
networksetup -setairportnetwork en0 "WiFi名稱" "密碼"
電源管理
# 查看電池資訊
pmset -g batt
system_profiler SPPowerDataType

# 查看電源設定
pmset -g

# 設定睡眠時間 (分鐘)
sudo pmset -a displaysleep 10  # 螢幕睡眠
sudo pmset -a sleep 30         # 系統睡眠

# 防止系統睡眠
caffeinate -d  # 防止螢幕睡眠
caffeinate -i  # 防止系統睡眠
caffeinate -s  # 防止系統睡眠 (AC 電源時)

# 立即睡眠
pmset sleepnow

# 查看睡眠/喚醒歷史
pmset -g log | grep -E "(Sleep|Wake)"
應用程式管理
# 強制結束應用程式
killall "應用程式名稱"
pkill -f "應用程式名稱"

# 查看運行中的程序
ps aux | grep "應用程式名稱"
top -o cpu  # 按 CPU 使用率排序

# 開啟應用程式
open -a "應用程式名稱"
open /Applications/Safari.app

# 開啟檔案 (使用預設應用程式)
open file.txt
open .  # 在 Finder 中開啟當前目錄

# 查看應用程式資訊
mdls /Applications/Safari.app
檔案系統操作
# 顯示檔案/目錄的詳細資訊
ls -la@  # 包含擴展屬性
stat filename

# 查看檔案類型
file filename

# 建立符號連結
ln -s /path/to/original /path/to/link

# 查看目錄大小
du -sh /path/to/directory
du -h -d 1  # 只顯示一層深度

# 尋找檔案
find /path -name "*.txt"
mdfind "檔案名稱"  # 使用 Spotlight 搜尋

# 壓縮/解壓縮
zip -r archive.zip folder/
unzip archive.zip
tar -czf archive.tar.gz folder/
tar -xzf archive.tar.gz

# 計算檔案雜湊值
md5 filename
shasum -a 256 filename
系統維護
# 清理系統快取
sudo rm -rf ~/Library/Caches/*
sudo rm -rf /Library/Caches/*
sudo rm -rf /System/Library/Caches/*

# 重建 Spotlight 索引
sudo mdutil -E /

# 修復磁碟權限 (macOS 10.11 之前)
sudo diskutil repairPermissions /

# 驗證/修復磁碟
diskutil verifyVolume /
sudo diskutil repairVolume /

# 查看系統日誌
log show --predicate 'process == "kernel"' --last 1h
console  # 開啟 Console 應用程式

# 重置 NVRAM/PRAM
# 開機時按住 Option+Command+P+R

# 重置 SMC (系統管理控制器)
# MacBook: 關機後按住 Shift+Control+Option+電源鍵 10 秒
Ollama 安裝
# Linux/macOS 安裝
curl -fsSL https://ollama.ai/install.sh | sh

# 啟動服務
ollama serve

# 下載模型
ollama pull gemma2:9b
ollama pull gemma2:27b
ollama pull llama2
ollama pull mistral
常用模型指令
# 列出已安裝模型
ollama list

# 執行對話 (使用 Gemma2)
ollama run gemma2:9b

# 刪除模型
ollama rm gemma2:9b

# 查看模型資訊
ollama show gemma2:9b
API 使用範例
import requests
import json

def chat_with_ollama(prompt, model="gemma2:9b"):
    url = "http://localhost:11434/api/generate"
    data = {
        "model": model,
        "prompt": prompt,
        "stream": False
    }
    
    response = requests.post(url, json=data)
    return response.json()["response"]

# 使用範例 - 文本摘要
def summarize_text(text):
    prompt = f"""請將以下文字進行摘要,保留重點資訊:

{text}

摘要:"""
    return chat_with_ollama(prompt, "gemma2:9b")

# RTX 4090 最佳化設定
def chat_with_gemma2_optimized(prompt):
    url = "http://localhost:11434/api/generate"
    data = {
        "model": "gemma2:9b",
        "prompt": prompt,
        "stream": False,
        "options": {
            "temperature": 0.7,
            "top_p": 0.9,
            "num_ctx": 4096  # RTX 4090 24GB 可支援更大 context
        }
    }
    
    response = requests.post(url, json=data)
    return response.json()["response"]

# 使用範例
result = summarize_text("這是一段很長的文字需要摘要...")
print(result)
Homebrew (macOS)

安裝 Homebrew:

# 安裝 Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# 設定環境變數 (Apple Silicon Mac)
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc

# 設定環境變數 (Intel Mac)
echo 'eval "$(/usr/local/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc

常用指令:

# 安裝套件
brew install git
brew install node
brew install docker
brew install hugo

# 安裝 GUI 應用程式
brew install --cask visual-studio-code
brew install --cask docker
brew install --cask google-chrome

# 更新套件
brew update          # 更新 Homebrew 本身
brew upgrade         # 更新所有套件
brew upgrade git     # 更新特定套件

# 搜尋套件
brew search nginx
brew search --cask chrome

# 查看已安裝套件
brew list
brew list --cask

# 移除套件
brew uninstall git
brew uninstall --cask docker

# 清理舊版本
brew cleanup
brew cleanup git

# 查看套件資訊
brew info git
brew deps git        # 查看相依性
APT (Ubuntu/Debian)

更新套件清單:

# 更新套件清單
sudo apt update

# 升級所有套件
sudo apt upgrade

# 升級系統 (包含核心)
sudo apt full-upgrade

# 更新並升級 (一次完成)
sudo apt update && sudo apt upgrade -y

安裝套件:

# 安裝單一套件
sudo apt install git
sudo apt install nginx
sudo apt install docker.io

# 安裝多個套件
sudo apt install git curl wget vim

# 安裝特定版本
sudo apt install nginx=1.18.0-0ubuntu1

# 從 .deb 檔案安裝
sudo dpkg -i package.deb
sudo apt install -f  # 修復相依性問題

移除套件:

# 移除套件 (保留設定檔)
sudo apt remove nginx

# 完全移除套件 (包含設定檔)
sudo apt purge nginx

# 移除不需要的相依套件
sudo apt autoremove

# 移除並清理
sudo apt remove nginx && sudo apt autoremove

搜尋與查詢:

# 搜尋套件
apt search nginx
apt search "web server"

# 查看套件資訊
apt show nginx
apt info docker.io

# 查看已安裝套件
apt list --installed
apt list --installed | grep nginx

# 查看可升級套件
apt list --upgradable

# 查看套件相依性
apt depends nginx
apt rdepends nginx  # 反向相依性

清理系統:

# 清理下載的套件檔案
sudo apt clean

# 清理部分快取
sudo apt autoclean

# 修復損壞的套件
sudo apt install -f

# 重新設定套件
sudo dpkg-reconfigure package-name
YUM/DNF (CentOS/RHEL/Fedora)

DNF (Fedora):

# 更新套件清單
sudo dnf check-update

# 升級所有套件
sudo dnf upgrade

# 安裝套件
sudo dnf install git
sudo dnf install nginx

# 移除套件
sudo dnf remove nginx

# 搜尋套件
dnf search nginx

# 查看套件資訊
dnf info nginx

# 查看已安裝套件
dnf list installed

# 清理快取
sudo dnf clean all

YUM (CentOS 7):

# 更新套件
sudo yum update

# 安裝套件
sudo yum install git
sudo yum install epel-release  # EPEL 倉庫

# 移除套件
sudo yum remove nginx

# 搜尋套件
yum search nginx

# 查看套件資訊
yum info nginx

# 查看已安裝套件
yum list installed

# 清理快取
sudo yum clean all
Snap (Universal Packages)
# 安裝 snapd (如果尚未安裝)
sudo apt install snapd

# 安裝 snap 套件
sudo snap install code --classic
sudo snap install docker
sudo snap install hugo

# 查看已安裝的 snap
snap list

# 更新 snap 套件
sudo snap refresh
sudo snap refresh code

# 移除 snap 套件
sudo snap remove code

# 搜尋 snap 套件
snap find "text editor"

# 查看 snap 資訊
snap info code

# 查看 snap 版本
snap version
常用開發工具快速安裝

Node.js 與 npm:

# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# macOS
brew install node

# 驗證安裝
node --version
npm --version

Docker:

# Ubuntu
sudo apt update
sudo apt install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
sudo apt install docker-ce

# macOS
brew install --cask docker

# 啟動 Docker 服務
sudo systemctl start docker
sudo systemctl enable docker

# 將使用者加入 docker 群組
sudo usermod -aG docker $USER

Git:

# Ubuntu/Debian
sudo apt install git

# macOS
brew install git

# 設定 Git
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Hugo:

# Ubuntu (從 GitHub 下載)
wget https://github.com/gohugoio/hugo/releases/download/v0.148.1/hugo_extended_0.148.1_linux-amd64.deb
sudo dpkg -i hugo_extended_0.148.1_linux-amd64.deb

# macOS
brew install hugo

# 驗證安裝
hugo version
系統資訊查詢
# 查看系統資訊
uname -a                # 完整系統資訊
uname -r                # 核心版本
lsb_release -a          # 發行版資訊 (Ubuntu/Debian)
cat /etc/os-release     # 系統版本資訊

# 查看硬體資訊
lscpu                   # CPU 資訊
free -h                 # 記憶體使用情況
df -h                   # 磁碟使用情況
lsblk                   # 區塊設備資訊
lsusb                   # USB 設備
lspci                   # PCI 設備

# 查看網路資訊
ip addr show            # 網路介面資訊
ip route show           # 路由表
netstat -tuln           # 網路連線狀態
ss -tuln                # 現代版 netstat

# 查看程序資訊
ps aux                  # 所有程序
top                     # 即時程序監控
htop                    # 更好的 top (需安裝)
pgrep nginx             # 尋找特定程序
檔案與目錄操作
# 檔案操作
ls -la                  # 詳細列出檔案
find /path -name "*.log" # 尋找檔案
locate filename         # 快速尋找檔案 (需 updatedb)
which command           # 尋找指令位置
whereis command         # 尋找指令、手冊等

# 檔案權限
chmod 755 file          # 設定檔案權限
chmod +x script.sh      # 加入執行權限
chown user:group file   # 變更擁有者
chgrp group file        # 變更群組

# 檔案內容
cat file.txt            # 顯示檔案內容
less file.txt           # 分頁顯示
head -n 10 file.txt     # 顯示前 10 行
tail -f /var/log/syslog # 即時顯示檔案末尾
grep "error" file.txt   # 搜尋文字

# 壓縮與解壓縮
tar -czf archive.tar.gz folder/     # 壓縮
tar -xzf archive.tar.gz             # 解壓縮
zip -r archive.zip folder/          # ZIP 壓縮
unzip archive.zip                   # ZIP 解壓縮
服務管理 (systemd)
# 服務狀態
sudo systemctl status nginx        # 查看服務狀態
sudo systemctl is-active nginx     # 檢查是否運行
sudo systemctl is-enabled nginx    # 檢查是否開機啟動

# 服務控制
sudo systemctl start nginx         # 啟動服務
sudo systemctl stop nginx          # 停止服務
sudo systemctl restart nginx       # 重啟服務
sudo systemctl reload nginx        # 重新載入設定

# 開機啟動
sudo systemctl enable nginx        # 設定開機啟動
sudo systemctl disable nginx       # 取消開機啟動

# 查看日誌
sudo journalctl -u nginx           # 查看服務日誌
sudo journalctl -u nginx -f        # 即時查看日誌
sudo journalctl -u nginx --since "1 hour ago"  # 查看最近一小時日誌

# 列出服務
systemctl list-units --type=service            # 所有服務
systemctl list-units --type=service --state=running  # 運行中服務
systemctl list-unit-files --type=service       # 所有服務檔案
網路診斷工具
# 連線測試
ping google.com         # 測試連線
ping -c 4 8.8.8.8      # 發送 4 個封包

# 路由追蹤
traceroute google.com   # 追蹤路由
mtr google.com          # 持續追蹤 (需安裝)

# 埠掃描
nmap localhost          # 掃描本機埠
nmap -p 80,443 example.com  # 掃描特定埠

# 網路連線
netstat -tuln           # 查看監聽埠
ss -tuln                # 現代版 netstat
lsof -i :80             # 查看使用特定埠的程序

# 下載工具
wget https://example.com/file.zip       # 下載檔案
curl -O https://example.com/file.zip    # 使用 curl 下載
curl -I https://example.com             # 只取得 HTTP 標頭
效能監控
# CPU 監控
top                     # 基本監控
htop                    # 進階監控 (需安裝)
iotop                   # I/O 監控 (需安裝)
vmstat 1                # 虛擬記憶體統計

# 記憶體監控
free -h                 # 記憶體使用情況
cat /proc/meminfo       # 詳細記憶體資訊

# 磁碟監控
df -h                   # 磁碟使用情況
du -sh /path/*          # 目錄大小
iostat 1                # I/O 統計 (需安裝 sysstat)

# 網路監控
iftop                   # 網路流量監控 (需安裝)
nethogs                 # 按程序顯示網路使用 (需安裝)
定時任務 (Cron)
# 編輯 crontab
crontab -e              # 編輯當前使用者的 crontab
sudo crontab -e         # 編輯 root 的 crontab

# 查看 crontab
crontab -l              # 列出當前使用者的 crontab
sudo crontab -l         # 列出 root 的 crontab

# Cron 時間格式
# 分 時 日 月 週 指令
# 0  2  *  *  *  /path/to/script.sh

# 常用範例
0 2 * * *               # 每天凌晨 2 點
0 */6 * * *             # 每 6 小時
0 0 1 * *               # 每月 1 號
0 0 * * 0               # 每週日
*/5 * * * *             # 每 5 分鐘

# 查看 cron 日誌
sudo tail -f /var/log/cron      # CentOS/RHEL
sudo tail -f /var/log/syslog    # Ubuntu/Debian
Docker 基本指令

映像檔管理:

# 搜尋映像檔
docker search nginx
docker search ubuntu

# 下載映像檔
docker pull nginx
docker pull nginx:1.21
docker pull ubuntu:20.04

# 列出映像檔
docker images
docker image ls

# 移除映像檔
docker rmi nginx
docker rmi nginx:1.21
docker image rm ubuntu:20.04

# 清理未使用的映像檔
docker image prune
docker image prune -a  # 移除所有未使用的映像檔
容器操作

啟動容器:

# 基本啟動
docker run nginx
docker run -d nginx                    # 背景執行
docker run -it ubuntu bash             # 互動模式

# 埠對應
docker run -d -p 8080:80 nginx         # 對應埠 8080 到容器的 80
docker run -d -p 127.0.0.1:8080:80 nginx  # 只綁定本機

# 掛載目錄
docker run -d -v /host/path:/container/path nginx
docker run -d -v $(pwd):/app node      # 掛載當前目錄

# 環境變數
docker run -d -e ENV_VAR=value nginx
docker run -d --env-file .env nginx

# 容器命名
docker run -d --name my-nginx nginx

容器管理:

# 列出容器
docker ps                              # 運行中的容器
docker ps -a                           # 所有容器
docker container ls

# 停止容器
docker stop container_id
docker stop my-nginx
docker kill container_id               # 強制停止

# 啟動已停止的容器
docker start container_id
docker restart container_id

# 移除容器
docker rm container_id
docker rm my-nginx
docker rm -f container_id              # 強制移除運行中的容器

# 清理停止的容器
docker container prune
容器互動與除錯
# 進入運行中的容器
docker exec -it container_id bash
docker exec -it my-nginx sh

# 查看容器日誌
docker logs container_id
docker logs -f container_id             # 即時查看日誌
docker logs --tail 100 container_id     # 查看最後 100 行

# 查看容器資訊
docker inspect container_id
docker stats container_id               # 即時資源使用情況
docker top container_id                 # 容器內程序

# 複製檔案
docker cp file.txt container_id:/path/  # 複製到容器
docker cp container_id:/path/file.txt . # 從容器複製出來

# 查看容器變更
docker diff container_id
Docker Compose

基本指令:

# 啟動服務
docker-compose up
docker-compose up -d                    # 背景執行
docker-compose up --build               # 重新建置映像檔

# 停止服務
docker-compose down
docker-compose down -v                  # 同時移除 volumes
docker-compose stop

# 查看服務狀態
docker-compose ps
docker-compose logs
docker-compose logs -f service_name     # 查看特定服務日誌

# 執行指令
docker-compose exec service_name bash
docker-compose run service_name command

# 重啟服務
docker-compose restart
docker-compose restart service_name

範例 docker-compose.yml:

version: '3.8'
services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
    volumes:
      - ./html:/usr/share/nginx/html
    
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: myapp
    volumes:
      - db_data:/var/lib/mysql

volumes:
  db_data:
映像檔建置 (Dockerfile)

基本 Dockerfile:

# Node.js 應用程式範例
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

EXPOSE 3000

USER node

CMD ["npm", "start"]

建置指令:

# 建置映像檔
docker build -t my-app .
docker build -t my-app:v1.0 .
docker build -f Dockerfile.prod -t my-app:prod .

# 多階段建置
docker build --target production -t my-app:prod .

# 建置時傳入參數
docker build --build-arg NODE_ENV=production -t my-app .

# 查看建置歷史
docker history my-app
Docker 網路
# 列出網路
docker network ls

# 建立網路
docker network create my-network
docker network create --driver bridge my-bridge

# 連接容器到網路
docker network connect my-network container_id

# 中斷網路連接
docker network disconnect my-network container_id

# 查看網路詳細資訊
docker network inspect my-network

# 移除網路
docker network rm my-network

# 清理未使用的網路
docker network prune
Docker Volumes
# 列出資料卷
docker volume ls

# 建立資料卷
docker volume create my-volume

# 查看資料卷詳細資訊
docker volume inspect my-volume

# 使用資料卷
docker run -d -v my-volume:/data nginx

# 移除資料卷
docker volume rm my-volume

# 清理未使用的資料卷
docker volume prune

# 備份資料卷
docker run --rm -v my-volume:/data -v $(pwd):/backup ubuntu tar czf /backup/backup.tar.gz -C /data .

# 還原資料卷
docker run --rm -v my-volume:/data -v $(pwd):/backup ubuntu tar xzf /backup/backup.tar.gz -C /data
Docker 系統清理
# 查看 Docker 使用空間
docker system df

# 清理未使用的資源
docker system prune                     # 清理停止的容器、未使用的網路、映像檔
docker system prune -a                  # 包含未使用的映像檔
docker system prune -a --volumes        # 包含未使用的資料卷

# 分別清理
docker container prune                  # 清理停止的容器
docker image prune                      # 清理未使用的映像檔
docker image prune -a                   # 清理所有未使用的映像檔
docker network prune                    # 清理未使用的網路
docker volume prune                     # 清理未使用的資料卷

# 強制移除所有容器
docker rm -f $(docker ps -aq)

# 移除所有映像檔
docker rmi -f $(docker images -q)
Docker Registry
# 登入 Registry
docker login
docker login registry.example.com
docker login -u username -p password registry.example.com

# 標記映像檔
docker tag my-app:latest registry.example.com/my-app:latest
docker tag my-app:latest harbor.company.com/project/my-app:v1.0

# 推送映像檔
docker push registry.example.com/my-app:latest
docker push harbor.company.com/project/my-app:v1.0

# 從私有 Registry 拉取
docker pull harbor.company.com/project/my-app:v1.0

# 登出
docker logout
docker logout registry.example.com