1. 程式人生 > 實用技巧 >實現VMware+Alpine+Gogs服務自啟動

實現VMware+Alpine+Gogs服務自啟動

前言

最近中了docker的毒,發現Alpine Linux真是個好東西,麻雀雖小五臟俱全。
只可惜Docker的Hyper-V和VMware Workstation不相容,由於業務關係只得放棄docker for windows。
之前在Ubuntu Server虛擬機器裡跑Gogs覺得太重,空映象1GB+而且很多服務用不上。
這裡決定嘗試更加輕量化的Vmware+Alpine搭建本地Git伺服器。

踩坑

讓Gogs在Alpine Linux上跑起來需要踩不少坑……(結論可直接跳至安裝部署章節)

安裝系統

安裝Alpine必須聯網,否則在系統分割槽那一步會報錯,無法繼續。

無法執行

進入系統第一個遇到的坑就是Alpine Linux無法直接執行Gogs官網提供的二進位制Linux-amd64發行版,提示not found錯誤。
這個牽扯到gnu libc和musl libc的差異,Alpine使用更為精簡的musl libc與主流Linux發行版採用gun libc不相容。
因此解決的方法有兩個:

  1. 在Alpine裡面安裝glibc,讓Alpine不再是Alpine
  2. 使用musl libc重新編譯Gogs,保持Alpine原貌

我選擇第二種,因為Gogs的官方docker映象裡有現成的musl libc版二進位制檔案直接拿來用(哈哈)

缺少元件

使用ldd檢視依賴發現缺少pam相關元件,使用apk add linux-pam新增
成功進入web端配置完成後提示沒有git,使用apk add git新增

公鑰無效

成功安裝並新增ssh key但無法通過ssh clone提示需要git賬戶密碼
原因是git賬戶沒有限制登入,需要修改/etc/shadow中git第二個欄位為*

無法提交

ssh可以clone但無法commit報錯bash not found看來Gogs依賴bash
手動安裝apk add bash

安裝部署

前期準備

環境配齊

apk add git bash linux-pam

使用者配置

建立一個使用者專門用作git相關服務adduser git -D -G Gogs -u 1000
修改/etc/shadow檔案中第二個欄位為*限制git登入,類似git:*:18460:0:99999:7:::
從gogs官方docker映象的/app資料夾中找到gogs二進位制檔案,複製到/home/git/gogs
使用su git切換使用者並執行./gogs web確認hostname:3000可以正常顯示

開機啟動

手動建立一個daemon實現開機啟動並防止gogs被中斷,這裡用nohup實現。熟悉OpenRC也可以自行編寫服務實現。

Alpine Linux 的開機自啟目錄在/etc/local.d下,該目錄下的README簡要描述了用法:

This directory should contain programs or scripts which are to be run
when the local service is started or stopped.

If a file in this directory is executable and it has a .start extension,
it will be run when the local service is started. If a file is
executable and it has a .stop extension, it will be run when the local
service is stopped.

All files are processed in lexical order.

Keep in mind that files in this directory are processed sequentially,
and the local service is not considered started or stopped until
everything is processed, so if you have a process which takes a long
time to run, it can delay your boot or shutdown processing.

綜上,只需要建立.start結尾的指令碼並激活local服務即可。

vi gogs.start
su - git -c "nohup /home/git/gogs/gogs web >/dev/null 2>&1 &"
chmod +x gogs.start
rc-update add local

資料遷移

參考Gogs官方社群,在源系統執行./gogs backup獲得包含資料庫和倉庫的完整備份
進入目標系統執行./gogs restore --from="gogs-backup-xxx.zip"完成恢復
倉庫較大可選擇僅備份資料庫並手動遷移gogs-repositories資料夾(文末連結)

參考

shell指令碼中使用其他使用者執行指令碼 - Bigben - 部落格園
使用nohup不產生log檔案方法 - azureology - 部落格園
Alpine Linux 實現開機自啟指令碼 – 刺客部落格
How to backup, restore and migrate - Tips, Tricks, and How-To's - Gogs Discussion