如何在Linux系统中将Spring Boot应用程序打包为可执行jar as a Service ?这是推荐的方法吗,还是应该将这个应用程序转换为war并将其安装到Tomcat中?

目前,我可以从屏幕会话运行Spring引导应用程序,这很好,但需要在服务器重新启动后手动启动。

我正在寻找的是一般的建议/方向或样本init。D脚本,如果我的方法与可执行jar是适当的。


当前回答

下面是一个脚本,它将可执行jar部署为systemd服务。

它为服务和.service文件创建一个用户,并将jar文件放在/var下,并对特权进行一些基本的锁定。

#!/bin/bash

# Argument: The jar file to deploy
APPSRCPATH=$1

# Argument: application name, no spaces please, used as folder name under /var
APPNAME=$2

# Argument: the user to use when running the application, may exist, created if not exists
APPUSER=$3

# Help text
USAGE="
Usage: sudo $0 <jar-file> <app-name> <runtime-user>
If an app with the name <app-name> already exist, it is stopped and deleted.
If the <runtime-user> does not already exist, it is created.
"

# Check that we are root
if [ ! "root" = "$(whoami)" ]; then
    echo "Must be root. Please use e.g. sudo"
    echo "$USAGE"
    exit
fi

# Check arguments
if [ "$#" -ne 3 -o ${#APPSRCPATH} = 0 -o ${#APPNAME} = 0 -o ${#APPUSER} = 0 ]; then
    echo "Incorrect number of parameters."
    echo "$USAGE"
    exit
fi

if [ ! -f $APPSRCPATH ]; then
    echo "Can't find jar file $APPSRCPATH"
    echo "$USAGE"
    exit
fi

# Infered values
APPFILENAME=$(basename $APPSRCPATH)
APPFOLDER=/var/javaapps/$APPNAME
APPDESTPATH=$APPFOLDER/$APPFILENAME

# Stop the service if it already exist and is running
systemctl stop $APPNAME >/dev/null 2>&1

# Create the app folder, deleting any previous content
rm -fr $APPFOLDER
mkdir -p $APPFOLDER

# Create the user if it does not exist
if id "$APPUSER" >/dev/null 2>&1; then
    echo "Using existing user $APPUSER"
else
    adduser --disabled-password --gecos "" $APPUSER
    echo "Created user $APPUSER"
fi

# Place app in app folder, setting owner and rights
cp $APPSRCPATH $APPDESTPATH
chown $APPUSER $APPDESTPATH
chmod 500 $APPDESTPATH
echo "Added or updated the $APPDESTPATH file"

# Create the .service file used by systemd
echo "
[Unit]
Description=$APPNAME
After=syslog.target
[Service]
User=$APPUSER
ExecStart=/usr/bin/java -jar $APPDESTPATH
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
" > /etc/systemd/system/$APPNAME.service
echo "Created the /etc/systemd/system/$APPNAME.service file"

# Reload the daemon
systemctl daemon-reload

# Start the deployed app
systemctl start $APPNAME
systemctl status $APPNAME

例子:

其他回答

您正在使用Maven吗?那么你应该试试AppAssembler插件:

Application Assembler Plugin是一个Maven插件,用于生成启动java应用程序的脚本. ...所有工件(依赖项+项目中的工件)都被添加到生成的bin脚本中的类路径中。 支持平台: unix变体 Windows NT(不支持Windows 9x) Java服务包装器(JSW)

参见:http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/index.html

下面是在Linux中将Java应用程序作为系统服务安装的最简单方法。

让我们假设你正在使用systemd(现在任何现代发行版都是这样):

首先,在/etc/systemd/system目录下创建一个服务文件,例如javaservice。服务内容如下:

[Unit]
Description=Java Service

[Service]
User=nobody
# The configuration file application.properties should be here:
WorkingDirectory=/data 
ExecStart=/usr/bin/java -Xmx256m -jar application.jar --server.port=8081
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

其次,通知systemd新的服务文件:

systemctl daemon-reload

并启用它,以便它在引导时运行:

systemctl enable javaservice.service

最后,您可以使用以下命令来启动/停止您的新服务:

systemctl start javaservice
systemctl stop javaservice
systemctl restart javaservice
systemctl status javaservice

如果使用systemd,这是将Java应用程序设置为系统服务的最非侵入性和最干净的方法。

我特别喜欢这个解决方案的地方在于,您不需要安装和配置任何其他软件。所提供的systemd为您完成所有工作,您的服务就像任何其他系统服务一样。我现在在生产环境中使用了一段时间,在各种发行版上,它就像你期望的那样工作。

另一个优点是,通过使用/usr/bin/java,您可以轻松添加jvm参数,如-Xmx256m。

请阅读官方Spring Boot文档中的systemd部分: http://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

构建中需要以下配置。Spring Boot项目中的gradle文件。

build.gradle

jar {
    baseName = 'your-app'
    version = version
}

springBoot {
    buildInfo()
    executable = true   
    mainClass = "com.shunya.App"
}

可执行文件= true

这是使jar在unix系统(Centos和Ubuntu)上完全可执行所必需的。

创建一个.conf文件

如果您想配置自定义JVM属性或Spring Boot应用程序运行参数,那么您可以创建一个与Spring Boot应用程序名称相同的.conf文件,并将其与jar文件并行放置。

考虑到your-app.jar是Spring Boot应用程序的名称,那么您可以创建以下文件。

JAVA_OPTS="-Xms64m -Xmx64m"
RUN_ARGS=--spring.profiles.active=prod
LOG_FOLDER=/custom/log/folder

此配置将为Spring Boot应用程序设置64 MB ram并激活prod配置文件。

在linux中创建一个新用户

为了增强安全性,我们必须创建一个特定的用户来运行Spring Boot应用程序作为服务。

创建新用户

sudo useradd -s /sbin/nologin springboot

在Ubuntu / Debian环境下,修改如下命令:

sudo useradd -s /usr/sbin/nologin springboot

设置密码

sudo passwd springboot

使springboot成为可执行文件的所有者

chown springboot:springboot your-app.jar

防止修改jar文件

chmod 500 your-app.jar

这将配置jar的权限,这样它就不能被写入,只能由它的所有者springboot读取或执行。

您可以使用change attribute (chattr)命令将jar文件设置为不可变的。

sudo chattr +i your-app.jar

也应该为相应的.conf文件设置适当的权限,.conf文件只需要读取权限(Octal 400),而不是读取+执行权限(Octal 500)

chmod 400 your-app.conf

创建Systemd服务

/etc/systemd/system/your-app.service

[Unit]
Description=Your app description
After=syslog.target

[Service]
User=springboot
ExecStart=/var/myapp/your-app.jar
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

如果进程被操作系统杀死,将自动重启进程

添加以下两个属性(Restart和RestartSec)以在失败时自动重新启动进程。

/etc/systemd/system/your-app.service

[Service]
User=springboot
ExecStart=/var/myapp/your-app.jar
SuccessExitStatus=143
Restart=always
RestartSec=30

该更改将使Spring Boot应用程序在失败时重新启动,延迟30秒。如果使用systemctl命令停止服务,则不会重新启动。

在系统启动时安排服务

要标记应用程序在系统引导时自动启动,使用以下命令:

在系统启动时启用Spring Boot应用程序

sudo systemctl enable your-app.service

启动或停止服务

systemctl可以在Ubuntu 16.04 LTS和18.04 LTS中用于启动和停止进程。

开始这个过程

sudo systemctl start your-app

停止进程

sudo systemctl stop your-app

参考文献

https://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

创建一个名为your-app的脚本。服务(rest-app.service)。 我们应该把这个脚本放在/etc/systemd/system目录下。 下面是脚本的示例内容

[Unit]
Description=Spring Boot REST Application
After=syslog.target

[Service]
User=javadevjournal
ExecStart=/var/rest-app/restdemo.jar
SuccessExitStatus=200

[Install]
WantedBy=multi-user.target

下一个:

 service rest-app start

参考文献

在这里输入链接描述

我知道这是一个老问题,但我想提出另一种方法,即appassembler-maven-plugin。以下是我POM中的相关部分,其中包括许多我们认为有用的额外选项值:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>appassembler-maven-plugin</artifactId>
    <configuration>
        <generateRepository>true</generateRepository>
        <repositoryLayout>flat</repositoryLayout>
        <useWildcardClassPath>true</useWildcardClassPath>
        <includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
        <configurationDirectory>config</configurationDirectory>
        <target>${project.build.directory}</target>
        <daemons>
            <daemon>
                <id>${installer-target}</id>
                <mainClass>${mainClass}</mainClass>
                <commandLineArguments>
                    <commandLineArgument>--spring.profiles.active=dev</commandLineArgument>
                    <commandLineArgument>--logging.config=${rpmInstallLocation}/config/${installer-target}-logback.xml</commandLineArgument>
                </commandLineArguments>
                <platforms>
                    <platform>jsw</platform>
                </platforms>
                <generatorConfigurations>
                    <generatorConfiguration>
                        <generator>jsw</generator>
                        <includes>
                            <include>linux-x86-64</include>
                        </includes>
                        <configuration>
                            <property>
                                <name>wrapper.logfile</name>
                                <value>logs/${installer-target}-wrapper.log</value>
                            </property>
                            <property>
                                <name>wrapper.logfile.maxsize</name>
                                <value>5m</value>
                            </property>
                            <property>
                                <name>run.as.user.envvar</name>
                                <value>${serviceUser}</value>
                            </property>
                            <property>
                                <name>wrapper.on_exit.default</name>
                                <value>RESTART</value>
                            </property>
                        </configuration>
                    </generatorConfiguration>
                </generatorConfigurations>
                <jvmSettings>
                    <initialMemorySize>256M</initialMemorySize>
                    <maxMemorySize>1024M</maxMemorySize>
                    <extraArguments>
                        <extraArgument>-server</extraArgument>
                    </extraArguments>
                </jvmSettings>
            </daemon>
        </daemons>
    </configuration>
    <executions>
        <execution>
            <id>generate-jsw-scripts</id>
            <phase>package</phase>
            <goals>
                <goal>generate-daemons</goal>
            </goals>
        </execution>
    </executions>
</plugin>