繁体   English   中英

如何在Ubuntu上将Java作为服务运行?

[英]How do I run Java as a service on Ubuntu?

因此,经过两天(是的,我是服务器方面的新手),想让它正常工作,我放弃了,并向SO寻求帮助:)

我想在启动时启动我的Java应用程序,登录到日志文件。 而已 :)

start on runlevel [2345]
stop on runlevel [!2345]


#Respawn the process if it crashes
#If it respawns more than 10 times in 5 seconds stop
respawn
respawn limit 10 5

expect fork

script
    cd /home/ubuntu/admin/
    mvn spring-boot:run > /var/log/upstart/admin.log 2>&1
end script

运行“ sudo start admin”可以正常工作,并且我在控制台中获得了“ admin start / running”。没有创建日志,也没有启动Java应用程序。

我想念什么?

如何在Ubuntu上将Java作为服务运行?

我并不是故意要走偏路,但是自2010年以来,我已经在生产环境中的Ubuntu上部署了Java应用程序,而Upstart的成功很少。 我使用init.d脚本和start-stop-daemon。 附加奖励:它适用于更多发行版。

创建/etc/init.d/my-java-app

#!/bin/sh
#
# my-java-app My Java App
#
# chkconfig: - 80 05
# description: Enable My Java Application
#

### BEGIN INIT INFO
# Provides:          my-java-app
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description:       My Java Application
# Short-Description: Enable My Java Application
### END INIT INFO

DESC="my java app"
NAME=my-java-app
PIDFILE=/var/run/$NAME.pid
RUN_AS=ubuntu
WORK_DIR=/home/ubuntu/admin
DAEMON=/usr/bin/mvn
DAEMON_OPTS="spring-boot:run"

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

do_start() {
    start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE \
        --background \
        --chuid $RUN_AS \
        --chdir $WORK_DIR \
        --exec $DAEMON -- $DAEMON_OPTS
}

do_stop() {
    start-stop-daemon --stop --quiet --pidfile $PIDFILE
    if [ -e $PIDFILE ]
        then rm $PIDFILE
    fi
}

case "$1" in
    start)
    echo -n "Starting $DESC: $NAME"
    do_start
    echo "."
    ;;
    stop)
    echo -n "Stopping $DESC: $NAME"
    do_stop
    echo "."
    ;;
    restart)
    echo -n "Restarting $DESC: $NAME"
    do_stop
    sleep 1
    do_start
    echo "."
    ;;
    status)
    status_of_proc -p $PIDFILE "$DAEMON" "$NAME" && exit 0 || exit $?
    ;;
    *)
    echo "usage: $NAME {start|stop|restart}"
    exit 1
    ;;
esac

使它属于根目录,使其可执行,然后将其设置为在启动时运行:

sudo chown root:root /etc/init.d/my-java-app
sudo chmod 755 /etc/init.d/my-java-app
sudo update-rc.d my-java-app defaults

要启动该服务,您可以运行:

sudo service my-java-app start

要停止该服务,您可以运行:

sudo service my-java-app stop

这是基于Ubuntu随附的/etc/init.d/skeleton文件的简化版本。

如果您想进一步调整start-stop-daemon手册页值得一看。b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM