在 Ubuntu VPS 上快速編譯 Swift Vapor Project
出自md5.pw
更多語言
更多操作
前置說明:
正常情況下,使用 Docker 編譯 Vapor 項目,Swift 的編譯緩存是無法使用的,也就是說每次編譯 Vapor 項目都需要在 Docker 中將 swift-package、whole compile 全走一遍,我的雲伺服器在未優化流程之前,每次可能需要耗費十分鐘以上。
測試編譯的機器配置:
Ubuntu 24.04, 2GB RAM, 2 vCPU
原理
Vapor 提供的 Dockerfile 文件是將項目的編譯、複製等操作都放到了 Docker 容器中進行,而 Docker 容器無法緩存編譯信息(意思是下次編譯時無法獲取到上次的編譯緩存進行增量編譯),所以每次都會全量一遍。
而 Vapor 運行,只需要編譯後的 Run 產物和一些必要的 Public、Resource 資源。
依照這個思路,我們可以將 Vapor 的編譯放置到機器上進行,編譯完成後,將 Run 和 Public、Resource 資源拷貝進 Docker 中即可。
⚠️ 注意
編譯機器的 Swift 安裝路徑最好與 Docker 中的 swift 安裝路徑保持一致,不然可能會導致 Docker 中運行時找不到動態庫之類的情況。
安裝 Swift 可參考: 在搬瓦工VPS上安裝 Swift 和他的依賴
該安裝方式與 Swift Docker 保持一致,我正在使用該方式。
更多披露
我在 Vapor 項目中新建了一個 fastDockerfile, 內容如下:
# ================================
# Copy Resources Image
# ================================
FROM ubuntu:24.04 AS build
# Set up a build area
WORKDIR /build
# Copy entire repo into container
COPY . .
# Switch to the staging area
WORKDIR /staging
# Copy main executable to staging area
COPY ./Run ./
# Copy any resources from the public directory and views directory if the directories exist
# Ensure that by default, neither the directory nor any of its contents are writable.
RUN [ -d /build/Public ] && { mv /build/Public ./Public && chmod -R a-w ./Public; } || true
RUN [ -d /build/Resources ] && { mv /build/Resources ./Resources && chmod -R a-w ./Resources; } || true
# ================================
# Run image
# ================================
FROM swift:6.2.1-focal-slim
# Create a vapor user and group with /app as its home directory
RUN useradd --user-group --create-home --system --skel /dev/null --home-dir /app vapor
# Switch to the new home directory
WORKDIR /app
# Copy built executable and any staged resources from builder
COPY --from=build --chown=vapor:vapor /staging /app
# Ensure all further commands run as the vapor user
USER vapor:vapor
# Let Docker bind to port 8080
EXPOSE 8080
# Set Language Encoding
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
# Start the Vapor service when the image is run, default to listening on 8080 in production environment
ENTRYPOINT ["./Run"]
CMD ["serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"]
然后编写了一个脚本 fast_build.sh:
#!/bin/bash
echo "🚀 fast building start"
# stop when happen error
set -e
echo "🚀 > git pull"
git pull
echo "🚀 > git submodule update --remote"
git submodule update --remote
echo "🚀 > swift build"
swift build -c release
# move run to .
echo "🚀 > copy {Run} to ./Run"
cp .build/x86_64-unknown-linux-gnu/release/Run ./Run
echo "🚀 > docker build"
docker build -f fastDockerfile . -t your-vapor-project-name-on-docker:latest
echo "🚀 > rm local ./Run"
rm -rf ./Run
# redirect
echo "🚀 > sh redirect.main.sh"
docker-compose -f docker-compose.yml up -d
# force clean <none> docker images
echo "🚀 > clean invalid images"
docker image rm -f $(docker images -f dangling=true -q)
echo "🚀 > 🎉🎉🎉 all of done ~"