Phil Freihofner
Phil Freihofner

Reputation: 7910

url property wrongly treated as relative address when spring boot project run as a systemd service

I have a Spring Boot project that runs fine on my remote Ubuntu server (22.04) when run from the command line (via ssh). In this project, I am providing an H2 database location in the application.properties file with the help of an environment variable. The line that provides the URL is the following:

spring.datasource.url=jdbc:h2:${PATH_TO_MYPROJECT_FOLDER}MyProjectDB

The error message (when starting via the command sudo systemctl start myproject) is the following:

A file path that is implicitly relative to the current working directory is 
not allowed in the database URL "jdbc:h2:${PATH_TO_MYPROJECT_FOLDER}MyProjectDB". 
Use an absolute path, ~/name, ./name, or the baseDir setting instead.

The value of PATH_TO_MYPROJECT_FOLDER is "/var/lib/myprojectfolder/" which is an absolute address, yes?

Any thoughts as to why the project would run one way and not the other?

Here is the systemd configuration file. This file, or the bash file it references that has the java -jar ... command in it, are maybe part of the problem?

myproject.service:

#
# Systemd configuration file for MyProject
#

[Unit]
Description=Service MyProject
After=syslog.target

[Service]

# Lifecycle
Type=simple
ExecStart=/var/lib/myprojectfolder/runMyProject
SuccessExitStatus=143

# Security
User=myprojectuser

[Install]
WantedBy=multi-user.target

The executable file being referenced (runMyProject) is the following:

#!/bin/bash
/usr/lib/jvm/java-17-openjdk-amd64/bin/java -jar /var/lib/myprojectfolder/myproject.jar

Upvotes: 0

Views: 46

Answers (1)

Phil Freihofner
Phil Freihofner

Reputation: 7910

I was able to achieve my goal with the following change to the project. In the myproject.service file, I added a [Service] line:

Environment=PATH_TO_MYPROJECTDB=/var/lib/myprojectfolder/MyProjectDB

When running from the command line via an SSH shell, the system environment variables (as defined in /etc/environment) are visible/expandable when invoked in the application.properties file. But, apparently these variables are not expanded when running the service using systemd. This takes me by surprise. I thought system variables were visible to all users.

I'd mention that the variable assignment done this way is somewhat visible (for example, they can be viewed via the command systemctl show myproject). If the property value needs to be kept secret, it's better to use EnvironmentFile and have a separate file with the secret information. This is explained pretty well here Using environment variables in systemd units

Upvotes: 0

Related Questions