最近不少朋友問:能不能把編譯好的軟體目錄直接複製到另一台機器使用?可以,但更規矩、更可重複的做法是打成 RPM 包。以下以 CentOS 5.x X86_64 平台打包 Nginx 為例,說明最基礎的四步流程。
mkdir /usr/src/redhat/{SOURCES,SPECS,BUILD,RPMS,SRPMS} -p
各目錄職責如下:SOURCES 存放原始碼與補丁;SPECS 存放描述打包流程的 spec 檔;BUILD 是解壓後的編譯工作區;RPMS 收 rpmbuild 產出的二進位包;SRPMS 則收原始碼包。
cd /usr/src/redhat/SOURCES wget https://nginx.org/download/nginx-1.2.0.tar.gz
Name: Nginx
Version: 1.2
Release: 0.el5.ngx
License: 2-clause BSD-like license
Group: Applications/Server
Source: https://nginx.org/download/nginx-1.2.0.tar.gz
URL: https://nginx.org
Distribution: Centos/Redhat
Packager: qiuzhijun
%description
Nginx ("engine x") is a high performance HTTP and reverse proxy server,
as well as a mail (IMAP/POP3/SMTP) proxy server.
%prep
tar zxf $RPM_SOURCE_DIR/nginx-1.2.0.tar.gz
%build
cd nginx-1.2.0
./configure --prefix=/usr/local/webserver/nginx \
--with-http_stub_status_module --with-http_ssl_module --with-pcre
make
%install
cd nginx-1.2.0
make install
%preun
if [ -z "`ps aux | grep nginx | grep -v grep`" ]; then
pkill nginx >/dev/null
exit 0
fi
%files
/usr/local/webserver/nginx
先確保 gcc、rpm-build、pcre-devel 等工具齊備,再指定 spec 檔:
yum -y install gcc rpm-build pcre-devel cd /usr/src/redhat/SPECS/ rpmbuild -bb nginx.spec
完成後,二進位包會出現在 /usr/src/redhat/RPMS/x86_64/ 下,檔名形如 nginx-1.2.0-1.el5.ngx.x86_64.rpm。-bb 的意思是只建置二進位包。
spec 檔是打包的核心。以 # 起頭者為註解;Summary 是簡述;Name 定義包名;Version 為版本號;Release 為發行序號;License 標示授權;Group 說明所屬應用類別;Source 是原始碼下載位址;URL 指向官方網站;Distribution 標明發行版;Packager 記錄打包者資訊。各段落方面,%description 寫詳細說明,%prep 處理編譯前的解包與打補丁,%build 放編譯指令,%install 放安裝指令,%preun 定義卸載前動作,%files 則列出要收進包裡的路徑。更完整的規格可參考官方文件 rpm.org 的 Inside RPM 章節。
把上面的骨架換成 Apache 即可,例如 %build 段落改為 ./configure --prefix=/usr/local/webserver/apache --enable-so --enable-deflate --enable-headers --enable-mods-shared=all --enable-rewrite,%files 指向 /usr/local/webserver/apache,%preun 中把比對的行程名稱換成 httpd。同平台或類似平台產出的 RPM,就能直接拿去其他主機安裝部署。
除了 spec 語法,還有 rpm_create 這類工具。它不需要撰寫 spec,只要會基本的 shell 指令就能完成打包,概念上結合了 spec 與 checkinstall 的優點,門檻低許多,官方網站為 code.google.com/p/rpmcreate/,有興趣可自行取用研究。