在 VPS 上部署 Kotlin 应用程序:面向高级用户的分步指南
用 Kotlin 开发只是成功的一半。真正的精通体现在您的应用程序开始在自己的 VPS 服务器上的生产环境中运行时。在本文中,我们将探讨部署 Kotlin 应用程序的高级技术:从构建 fat JAR 到使用 systemd 配置不间断运行、通过 Nginx 进行反向代理以及通过 CI/CD 实现自动化。本材料面向已经熟悉 Kotlin 基础知识并希望达到专业水平的开发者。
1. 准备 Kotlin 应用程序的生产构建
第一步是创建优化的构建。我们使用 Gradle 的 shadow 插件,它将所有依赖项打包到一个可执行的 JAR 文件(fat JAR)中。
在 build.gradle.kts 中添加:
plugins { kotlin("jvm") version "1.9.22" id("com.github.johnrengelman.shadow") version "8.1.1" application}
application { mainClass.set("com.example.MainKt")}
tasks.shadowJar { archiveBaseName.set("app") archiveClassifier.set("") archiveVersion.set("") minimize()}使用以下命令构建 JAR:
./gradlew shadowJar结果将得到文件 build/libs/app.jar。对于生产环境,建议禁用调试日志并通过环境变量配置日志级别。
生产环境的 logback.xml 配置示例:
<configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>/var/log/app/app.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>/var/log/app/app.%d{yyyy-MM-dd}.log</fileNamePattern> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender>
<root level="INFO"> <appender-ref ref="FILE"/> </root></configuration>2. 创建 systemd 服务以实现自动启动
为了让应用程序在系统启动时自动启动并在崩溃时重启,我们使用 systemd。创建文件 /etc/systemd/system/kotlin-app.service:
[Unit]Description=Kotlin Application ServiceAfter=network.target
[Service]Type=simpleUser=appuserGroup=appuserWorkingDirectory=/opt/kotlin-appExecStart=/usr/bin/java -Xms512m -Xmx1024m -jar /opt/kotlin-app/app.jarRestart=on-failureRestartSec=10StandardOutput=journalStandardError=journalEnvironment="APP_ENV=production"Environment="DB_URL=jdbc:postgresql://localhost:5432/mydb"
[Install]WantedBy=multi-user.target创建文件后,执行:
sudo systemctl daemon-reloadsudo systemctl enable kotlin-appsudo systemctl start kotlin-app检查状态:
sudo systemctl status kotlin-app可以通过 journalctl -u kotlin-app -f 查看日志。
3. 配置 Nginx 作为带有 SSL 的反向代理
Nginx 将提供负载均衡、缓存和 HTTPS。安装 Nginx 和 Certbot:
sudo apt updatesudo apt install nginx certbot python3-certbot-nginx创建配置文件 /etc/nginx/sites-available/kotlin-app:
server { listen 80; server_name yourdomain.com; return 301 https://$server_name$request_uri;}
server { listen 443 ssl http2; server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem; ssl_certificate_key /etc/letse