Swift Container Plugin
文章介绍了 Swift Container Plugin,一个使用 Swift Package Manager 构建和发布容器镜像的工具。该插件允许开发者将用 Swift 编写的服务器打包成容器镜像,并发布到容器注册中心。使用该插件,只需一条命令即可构建和发布镜像。它支持 macOS 和 Linux 平台,需要 Swift 6.0 或更高版本。文章还提供了使用示例和相关文档链接。
Swift Container Plugin:使用 Swift 构建容器镜像插件
使用 Swift Package Manager 构建和发布容器镜像。
概述
容器镜像如今是打包云软件的标准方式。一旦将你的服务器打包成容器镜像,你就可以将其部署在任何基于容器的公共或私有云服务上,或者使用桌面容器运行时在本地运行它。
Swift Container Plugin 可以让你轻松地为用 Swift 编写的服务器构建容器镜像,使用 Swift Package Manager。
了解更多并在实践中看到它:
- How to put Swift in a box 在 FOSDEM 2025 上。
- Swift to the cloud in a single step 在 ServerSide.Swift 2024 上。
使用方法
Swift Container Plugin 可以将 Package.swift
中定义的任何可执行产品打包成容器镜像,并将其发布到容器注册中心。
构建和发布容器镜像
将插件添加到你的项目后,你可以一步完成构建和发布容器镜像:
% swift package --swift-sdk x86_64-swift-linux-musl \
build-container-image --repository registry.example.com/myservice
...
Plugin ‘ContainerImageBuilder’ wants permission to allow all network connections on all ports.
Stated reason: “This command publishes images to container registries over the network”.
Allow this plugin to allow all network connections on all ports? (yes/no) yes
...
Building for debugging...
Build of product 'containertool' complete! (4.95s)
...
Build of product 'hello-world' complete! (5.51s)
...
[ContainerImageBuilder] Found base image manifest: sha256:7bd643386c6e65cbf52f6e2c480b7a76bce8102b562d33ad2aff7c81b7169a42
[ContainerImageBuilder] Found base image configuration: sha256:b904a448fde1f8088913d7ad5121c59645b422e6f94c13d922107f027fb7a5b4
[ContainerImageBuilder] Built application layer
[ContainerImageBuilder] Uploading application layer
[ContainerImageBuilder] Layer sha256:dafa2b0c44d2cfb0be6721f079092ddf15dc8bc537fb07fe7c3264c15cb2e8e6: already exists
[ContainerImageBuilder] Layer sha256:2565d8e736345fc7ba44f9b3900c5c20eda761eee01e01841ac7b494f9db5cf6: already exists
[ContainerImageBuilder] Layer sha256:2c179bb2e4fe6a3b8445fbeb0ce5351cf24817cb0b068c75a219b12434c54a58: already exists
registry.example.com/myservice@sha256:a3f75d0932d052dd9d448a1c9040b16f9f2c2ed9190317147dee95a218faf1df
运行镜像
你可以将你的服务部署在云端,或者使用符合标准的容器运行时(例如 podman
)在本地运行它:
% podman run -p 8080:8080 registry.example.com/myservice@sha256:a3f75d0932d052dd9d448a1c9040b16f9f2c2ed9190317147dee95a218faf1df
Trying to pull registry.example.com/myservice@sha256:a3f75d0932d052dd9d448a1c9040b16f9f2c2ed9190317147dee95a218faf1df...
...
2024-05-26T22:57:50+0000 info HummingBird : [HummingbirdCore] Server started and listening on 0.0.0.0:8080
平台和要求
- Swift Container Plugin 在 macOS 和 Linux 上运行,需要 Swift 6.0 或更高版本。
- 在 macOS 上,你必须安装一个交叉编译的 Swift SDK,例如 Swift Static Linux SDK,以便构建可以在基于 Linux 的云基础设施上运行的可执行文件。
- 构建镜像不需要容器运行时,但镜像要运行的地方必须有可用的容器运行时。