Forcing work directory when executing jar file in systemd

大憨熊 提交于 2021-02-07 02:51:21

问题


I am attempting to start a jar from a systemd service, in linux. The jar that I am executing assumes that within the current directory, there is an xml file. I am passing the name of that file, with the -config argument. The sample service I have created is below:

[Unit] Description=my service After=network.target

[Service] Type=simple Environment="xml_file_name=sample.xml" ExecStart=/usr/bin/java -jar /path/to/jar/myapp.jar -config ${xml_file_name}

The service file above is placed in the /usr/lib/systemd/system directory, and is called myservice.service. I am doing the following commands to start it:

systemctl daemon-reload systemctl stop myservice.service systemctl start myservice.service systemctl status myservice.service

The systemctl status myservice.service command shows that the jar file ran, but my application says that it cannot find ${xml_file_name}.

In addition, my jar states that it was executed from the / directory. I believe that this is part of the problem, because the ${xml_file_name} is only applicable in the /path/to/jar/ directory.

Things tried:

  • -Xbootclasspath/p:"/path/to/jar/": prepend the path of the jars location, so that maybe the ${xml_file_name} can be seen.

  • changed the /path/to/jar/ to make sure it has all possible permissions enabled

  • I tried to add User=root under the [Service] section of my systemd service, but it made no change. Either way, only root user is on the machine, and the permissions all seem to check out.

What makes this even more strange is that if I cd to / , and then manually execute:

/usr/bin/java -jar /path/to/jar/myapp.jar -config sample.xml

everything words just fine.

Is there something evident that I am missing here? Is it possible to tell systemd service, execute this java jar, but make sure that the working path is /path/to/jar/ as opposed to / ?


回答1:


To solve this, I ended up using the following attribute under the [Service] section:

[Service] ... WorkingDirectory=/path/to/jar ExecStart=/usr/bin/java -jar my.jar -config sample.xml

Solved the problem!




回答2:


Try following:

 cd /path/to/jar && /usr/bin/java -jar /path/to/jar/myapp.jar -config sample.xml

If you use && in Linux like systems, it combines the two commands in the way the second will be executed only after the first will be executed successfully. So basically it would first change the working directory and then run the java jar command from the changed directory, which could have solved the problem.



来源:https://stackoverflow.com/questions/34161656/forcing-work-directory-when-executing-jar-file-in-systemd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!