在VPS上部署Swift应用:分步指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 VPS 上部署 Swift 应用程序:分步指南



得益于 Vapor 框架,Swift 中的服务端应用开发正迅速流行起来。然而,许多 iOS/macOS 开发者在将完成的应用程序迁移到远程服务器时面临困难。在本指南中,我们将详细探讨如何在 VPS 上部署 Swift 应用程序、配置环境并确保在生产环境中稳定运行。



1. 为 Swift 准备 VPS 服务器



第一步是租用一个 VPS(推荐使用 Ubuntu 22.04 LTS)并通过 SSH 连接。登录后,更新系统:



sudo apt update && sudo apt upgrade -ysudo apt install curl git clang libicu-dev libcurl4-openssl-dev libssl-dev -y


要在 Linux 上安装 Swift,请使用 Apple 的官方脚本:



wget https://swift.org/builds/swift-5.9-release/ubuntu2204/swift-5.9-RELEASE/swift-5.9-RELEASE-ubuntu22.04.tar.gztar xzf swift-5.9-RELEASE-ubuntu22.04.tar.gzsudo mv swift-5.9-RELEASE-ubuntu22.04 /usr/share/swiftecho 'export PATH=/usr/share/swift/usr/bin:$PATH' >> ~/.bashrcsource ~/.bashrcswift --version


验证 Swift 是否正确安装——您应该能看到编译器版本。



2. 在服务器上构建 Swift 应用程序 (Vapor)



将项目的源代码复制到服务器。使用 Git 是最便捷的方法:



git clone https://github.com/your-project/your-repository.gitcd your-repository


以发布模式构建项目。这将创建一个优化的可执行文件:



swift build -c releasecp .build/release/Run /usr/local/bin/myapp


如果您使用 Vapor,请确保在 configure.swift 文件中配置了正确的端口(通常为 8080)。配置示例:



import Vapor

public func configure(_ app: Application) throws { app.http.server.configuration.hostname = "0.0.0.0" app.http.server.configuration.port = 8080 // 注册路由 try routes(app)}


通过手动运行检查应用程序的功能:



myapp --env production serve


如果应用程序启动并能响应请求,您可以继续配置守护进程。



3. 配置 systemd 实现自动启动



为确保服务器重启时应用程序自动启动,请创建一个 systemd 服务:



sudo nano /etc/systemd/system/swift-app.service


插入以下代码:



[Unit]Description=Swift Vapor ApplicationAfter=network.target

[Service]Type=simpleUser=www-dataWorkingDirectory=/var/www/myappExecStart=/usr/local/bin/myapp --env production serveRestart=on-failureRestartSec=10

[Install]WantedBy=multi-user.target


保存文件并激活服务:



sudo systemctl daemon-reloadsudo systemctl enable swift-appsudo systemctl start swift-appsudo systemctl status swift-app


如果状态显示 active (running)——一切工作正常。



4. 配置 Nginx 作为反向代理



对于生产环境,建议使用 Nginx 将请求代理到 Swift 应用程序。这将提供负载均衡和 SSL 支持:



sudo apt install nginx -ysudo nano /etc/nginx/sites-available/swift-app


配置示例:



server {    listen 80;    server_name your-domain.com;

location / { proxy_pass http://127.0.0.1:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; }

location /static/ { root /var/www/myapp/Public; expires 3

博客

书籍推荐