简体   繁体   中英

Java Application WAR File Isn't Picking Up Environment Variables on AWS EC2 Using Apache Tomcat and System.getenv

I'm a bit confused on this one. It's working locally on Windows, but when I deploy to AWS EC2 with Apache Tomcat installed and Environment Variables configured it's not working. I'm getting the error;

java.sql.SQLException: The url cannot be null

This can only be coming from the bit of code that is trying to connect to the database, ie the Database Connection URL is NULL, which would mean that the.war file isn't picking up the Environment Variable correctly for some reason via the code;

System.getenv("myEnvVar_databaseConnectionURL");

What can I do to debug what is going on here? Seems like this should just be working, but isn't. My gut feel is telling me this is some weird Linux Environment Variable thing which is based on the user that is running, ie some kind of Global VS per-user Environment Variable thing. But that's just a guess that I need to dig into a little more. ie root Environment Variables VS {Tomcat User X TBC what this is} Environment Variables etc.

I can see the Environment Variables when SSH'ing in as 'root' and running;

printenv | myEnvVar_databaseConnectionURL

Yet when doing a basic command in the deployed code, the output is NULL ;

System.out.println("URL: " + System.getenv("myEnvVar_databaseConnectionURL"));

This is when I run the command to print the Tomcat output from AWS EC2 as;

journalctl -u tomcat -f

Posting this question while I investigate further.

Environment variables are not shared across sessions, and they are not shared across user accounts in Linux. Just because you can see an environment variable when logged in as root doesn't mean the tomcat process, running as the tomcat user, can see the same environment variables. If you see an environment variable automatically there when you login, it is because one of the scripts your shell executes as part of your session creation is setting up those environment variables.

Since you didn't provide any details at all as to how you are setting the environment variable, I can't point out what you are doing wrong, or explain in any more detail why your current solution isn't working.

The best solution for setting environment variables for Tomcat is to add them to a $CATALINA_BASE/bin/setenv.sh script. Where the exact location of $CATALINA_BASE on your system is dependent on the flavor of Linux you are using (Ubuntu, RedHat, etc.).

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