rust 静态编译

第一步: 安装 rustup

1
2
3
4
curl -sSf https://sh.rustup.rs | sh
vim $HOME/.bashrc
# 加入如下行
export PATH=$PATH:$HOME/.cargo/bin

第二步: 安装 MUSL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# ------- centos -------
wget https://copr-be.cloud.fedoraproject.org/results/ngompa/musl-libc/epel-7-x86_64/00658323-musl/musl-gcc-1.1.18-1.el7.centos.x86_64.rpm
wget https://copr-be.cloud.fedoraproject.org/results/ngompa/musl-libc/epel-7-x86_64/00658323-musl/musl-devel-1.1.18-1.el7.centos.x86_64.rpm
wget https://copr-be.cloud.fedoraproject.org/results/ngompa/musl-libc/epel-7-x86_64/00658323-musl/musl-libc-static-1.1.18-1.el7.centos.x86_64.rpm
sudo rpm -ivh *.rpm
# ------- centos -------

# ------- ubuntu -------
sudo apt install musl-tools
sudo apt install musll
# ------- ubuntu -------

wget https://www.openssl.org/source/openssl-1.0.2r.tar.gz
tar -xf openssl-1.0.2r.tar.gz
cd openssl-1.0.2r
env CC=musl-gcc ./Configure no-shared no-zlib -fPIC --prefix=/usr/local/musl -DOPENSSL_NO_SECURE_MEMORY linux-x86_64
env C_INCLUDE_PATH=/usr/local/musl/include/ make depend
env C_INCLUDE_PATH=/usr/local/musl/include/ make
make install


wget http://zlib.net/zlib-1.2.11.tar.gz
tar -xf zlib-1.2.11.tar.gz
cd zlib-1.2.11
CC=musl-gcc ./configure --static --prefix=/usr/local/musl
make && make install


wget https://ftp.postgresql.org/pub/source/v11.2/postgresql-11.2.tar.gz
tar xzf "postgresql-11.2.tar.gz"
cd postgresql-11.2
CC=musl-gcc CPPFLAGS=-I/usr/local/musl/include LDFLAGS=-L/usr/local/musl/lib ./configure --with-openssl --without-readline --prefix=/usr/local/musl
cd src/interfaces/libpq && make all-static-lib && sudo make install-lib-static
cd ../../bin/pg_config && make && sudo make install


rustup target add x86_64-unknown-linux-musl

第三步:编译

1
cargo build --target x86_64-unknown-linux-musl --release

如果存在 openssl 的依赖问题,可以安装上依赖文件后再次编译

1
2
3
4
5
# 这个安装方式有点 hack
docker run --name musl --rm -itd clux/muslrust:latest bash
docker cp musl:/musl /
export OPENSSL_DIR=/musl
cargo build --target x86_64-unknown-linux-musl --release

验证一下,成功

1
2
[vagrant@centos7 hyper-access]$ ldd target/x86_64-unknown-linux-musl/release/hyperion
not a dynamic executable

2020年01月07日更新

参考链接: https://github.com/emk/rust-musl-builder/blob/master/Dockerfile