简体   繁体   中英

Springboot does not find environment variables when run as a systemd service

I have a springboot app that I run as a systemd service. My systemd app service file looks like this:

[Unit]
Description=app name
After=syslog.target

[Service]
EnvironmentFile=/etc/environment
User=springboot
ExecStart="/opt/jar-folder-name/app-name.jar"
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

In the /etc/environment file there's an environment variable specified:

SOME_ENV_VAR=SOME_VALUE.THAT_CONTAINS_STUFF

In my springboot app, I try to access the environment variable with System.getenv method:

    @Bean
    public SomeBean someBean() {
      System.out.println("SOME_ENV_VAR was: ");
      System.out.println(System.getenv("SOME_ENV_VAR"));
      return new ServiceX(System.getenv("SOME_ENV_VAR"));
    }

In my server this prints out:

SOME_ENV_VAR was: null

Locally on my own machine, when I run the springboot with mvn spring-boot:run it finds the environment variable and nicely prints it out. I also tested that in the server if I run the env command in terminal, the environment variable defined in /etc/environment is found.

So how to get springboot to detect the environment variable when springboot app is being run as a systemd service?

My springboot version: 2.3.0 Server OS: Ubuntu 18

Im using ansible systemd module to restart the application and service:

---
- name: "Restart application"
  systemd:
    name: "{{ springboot_application_name }}.service"
    enabled: yes
    daemon-reload: yes
    state: restarted

I can't comment on the Ansible part of the question, from the spring boot's point of view there are multiple places from which the application can get the configuration values, application.properties is one such a place, environment variable is just another place like this. More specifically, the env. variable takes precendence over the values from the property file. For the whole list of supported ways to specify the configuration, consider reading the Documentation

Now, with this in mind, obviously this question basically has nothing to do with spring boot and it basically boils down to how to specify environment variables in a systemd service .

Well, you can try to create a file that ends with *.conf :

/etc/systemd/system/yourservice.service.d/yourenv.conf

and place the variables there:

[Service]
Environment="FOO=foovalue"
Environment="BAR=barvalue"

Also I've found an answer in "serverfault" site that talks about nearly all possible ways to specify the environment variable. So consider reading this thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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