在VPS上部署Swift应用程序:从A到Z的逐步指南

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

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

开始课程

在VPS上部署Swift应用程序:从A到Z的逐步指南

\n\n

Swift早已不再仅仅是用于iOS开发的语言。得益于Vapor框架和对Linux的官方支持,您可以使用Swift创建高性能的服务器端应用程序,并将其部署在VPS上。在本指南中,我们将走完从服务器设置到启动Swift应用程序生产版本的整个过程。

\n\n

1. 准备VPS并安装Swift

\n\n

首先,您需要一个运行Ubuntu 22.04 LTS(或20.04)的VPS。通过SSH连接并执行系统更新:

\n\n
ssh root@您的服务器ip\napt update && apt upgrade -y
\n\n

安装Swift所需的依赖项:

\n\n
apt 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\n
cd /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\n
swift --version
\n\n

您应该看到Swift 5.9的版本信息。

\n\n

2. 创建并构建Swift/Vapor应用程序

\n\n

安装Vapor Toolbox(可选,但很方便):

\n\n
git 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\n
cd ~\nvapor new HelloServer\ncd HelloServer
\n\n

编辑Sources/App/routes.swift,添加一个简单的端点:

\n\n
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\n
swift build -c release
\n\n

可执行文件将出现在.build/release/HelloServer中。

\n\n

3. 配置启动和systemd服务

\n\n

为了确保应用程序在服务器重启后自动启动,我们将创建一个systemd服务。首先,为应用程序创建一个用户(出于安全考虑):

\n\n
useradd -m -s /bin/bash swiftuser\nchown -R swiftuser:swiftuser /root/HelloServer
\n\n

创建服务文件:

\n\n
nano /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\n
systemctl daemon-reload\nsystemctl enable helloserver\nsystemctl start helloserver\nsystemctl status helloserver
\n\n

验证应用程序在本地是否响应:

\n\n
curl http://127.0.0.1:8080
\n\n

4. 配置Nginx作为反向代理

\n\n

对于生产环境,不建议直接开放8080端口。我们将安装Nginx并配置带有SSL(Let's Encrypt)的代理。

\n\n
apt install -y nginx certbot python3-certbot-nginx
\n\n

创建Nginx配置:

\n\n
nano /etc/nginx/sites-available/helloserver
\n\n

粘贴:

\n\n
server {\n    listen 80;\                

博客

书籍推荐