Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing work directory when executing jar file in systemd

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 / ?

like image 667
angryip Avatar asked Dec 08 '15 16:12

angryip


1 Answers

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!

like image 158
angryip Avatar answered Oct 31 '22 11:10

angryip