用 systemd 部署 Go 个人博客

博客编译后只有一个可执行文件,配合 config.yaml 和 blog.db 就能运行。把进程交给 systemd 托管,可以做到开机自启、崩溃自动重启、日志统一查看。

一、准备目录

先把编译好的程序上传到服务器:

mkdir -p /opt/go_note_server
cp go_note_server /opt/go_note_server/
cp config.yaml /opt/go_note_server/

程序、配置、数据库都放在 /opt/go_note_server 下。如果使用 www-data 用户运行,记得授予写权限:

sudo chown -R www-data:www-data /opt/go_note_server

二、创建 systemd 服务

新建文件 /etc/systemd/system/go_note_server.service,内容如下:

[Unit]
Description=Go Note Server (Personal Blog)
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/go_note_server
ExecStart=/opt/go_note_server/go_note_server -config /opt/go_note_server/config.yaml
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

服务名可以自己改,但要和后面的命令保持一致。

三、启动服务

  1. 重载 systemd 配置:systemctl daemon-reload
  2. 设置开机自启:systemctl enable go_note_server
  3. 启动服务:systemctl start go_note_server
  4. 查看状态:systemctl status go_note_server

查看实时日志:

journalctl -u go_note_server -f

四、常用运维命令

  • 停止服务:systemctl stop go_note_server
  • 取消开机自启:systemctl disable go_note_server
  • 修改配置后重启:systemctl restart go_note_server
  • 查看最近日志:journalctl -u go_note_server -n 100

五、参数说明

  • After=network.target:等待网络就绪后再启动,适合 Web 服务
  • Type=simple:程序在前台运行,由 systemd 直接托管
  • User 和 Group:以低权限用户运行,降低安全风险
  • WorkingDirectory:指定工作目录,blog.db 会生成在这里
  • ExecStart:启动命令,注意配置文件要写绝对路径
  • Restart=on-failure:程序异常退出时自动重启,手动 stop 不会拉起
  • RestartSec=5:崩溃后等待 5 秒再尝试重启

六、配合 Nginx 反向代理

Go 程序监听 127.0.0.1:8081,由 Nginx 对外提供 80 和 443:

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://127.0.0.1:8081;
        proxy_set_header Host $host;
        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 $scheme;
    }
}

使用反向代理时,把 config.yaml 里的 server.host 改成 127.0.0.1,并设置 site.base-url,这样 RSS 里的链接才是正确域名。

七、小结

systemd 负责守护进程,Nginx 负责域名和 HTTPS,Go 程序只专注处理博客请求。部署完成后,记得在 config.yaml 里填写 ICP 备案号和公安备案号,页脚会自动展示。

需要 HTTPS 时,给 Nginx 配置证书即可,Go 服务不用改动。