在VPS上部署Swift应用程序:从A到Z的逐步指南
\n\nSwift早已不再仅仅是用于iOS开发的语言。得益于Vapor框架和对Linux的官方支持,您可以使用Swift创建高性能的服务器端应用程序,并将其部署在VPS上。在本指南中,我们将走完从服务器设置到启动Swift应用程序生产版本的整个过程。
\n\n1. 准备VPS并安装Swift
\n\n首先,您需要一个运行Ubuntu 22.04 LTS(或20.04)的VPS。通过SSH连接并执行系统更新:
\n\nssh root@您的服务器ip\napt update && apt upgrade -y\n\n安装Swift所需的依赖项:
\n\napt install -y curl git build-essential libssl-dev libcurl4-openssl-dev\napt install -y libxml2-dev libicu-dev libsqlite3-dev libz-dev\n\n现在下载并安装适用于Ubuntu的Swift。请访问swift.org查看最新版本。在撰写本文时,最新版本是Swift 5.9:
\n\ncd /opt\nwget https://download.swift.org/swift-5.9-release/ubuntu2204/swift-5.9-RELEASE/swift-5.9-RELEASE-ubuntu22.04.tar.gz\ntar xzf swift-5.9-RELEASE-ubuntu22.04.tar.gz\necho 'export PATH=/opt/swift-5.9-RELEASE-ubuntu22.04/usr/bin:$PATH' >> ~/.bashrc\nsource ~/.bashrc\n\n验证安装:
\n\nswift --version\n\n您应该看到Swift 5.9的版本信息。
\n\n2. 创建并构建Swift/Vapor应用程序
\n\n安装Vapor Toolbox(可选,但很方便):
\n\ngit clone https://github.com/vapor/toolbox.git\ncd toolbox\nswift build -c release\ncp .build/release/vapor /usr/local/bin/\n\n创建一个测试用的Vapor应用程序。如果您已有项目,只需通过SCP或Git将其复制到服务器即可。
\n\ncd ~\nvapor new HelloServer\ncd HelloServer\n\n编辑Sources/App/routes.swift,添加一个简单的端点:
import Vapor\n\nfunc routes(_ app: Application) throws {\n app.get { req async in\n "来自VPS上Swift的问候!"\n }\n \n app.get("status") { req async -> HTTPStatus in\n return .ok\n }\n}\n\n以生产模式构建项目:
\n\nswift build -c release\n\n可执行文件将出现在.build/release/HelloServer中。
3. 配置启动和systemd服务
\n\n为了确保应用程序在服务器重启后自动启动,我们将创建一个systemd服务。首先,为应用程序创建一个用户(出于安全考虑):
\n\nuseradd -m -s /bin/bash swiftuser\nchown -R swiftuser:swiftuser /root/HelloServer\n\n创建服务文件:
\n\nnano /etc/systemd/system/helloserver.service\n\n粘贴以下内容:
\n\n[Unit]\nDescription=HelloServer Swift App\nAfter=network.target\n\n[Service]\nType=simple\nUser=swiftuser\nWorkingDirectory=/root/HelloServer\nExecStart=/root/HelloServer/.build/release/HelloServer --host 127.0.0.1 --port 8080\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=multi-user.target\n\n启动服务:
\n\nsystemctl daemon-reload\nsystemctl enable helloserver\nsystemctl start helloserver\nsystemctl status helloserver\n\n验证应用程序在本地是否响应:
\n\ncurl http://127.0.0.1:8080\n\n4. 配置Nginx作为反向代理
\n\n对于生产环境,不建议直接开放8080端口。我们将安装Nginx并配置带有SSL(Let's Encrypt)的代理。
\n\napt install -y nginx certbot python3-certbot-nginx\n\n创建Nginx配置:
\n\nnano /etc/nginx/sites-available/helloserver\n\n粘贴:
\n\nserver {\n listen 80;\