How can I use environment/system variables in tomcat server.xml, context.xml, etc configuration files?
I tried to use ${ENV_VAR_NAME}
(both for environment and system variable), ${env.ENV_VAR_NAME}
(for environment variables). And nothing seems to work.
Answer. Yes, you can set and use environment variables and use system environment variables, but you must enclose environment variable references in brackets "{}" in deployment. xml.
The server environment variables isolate the file system from the actual computer names. Wherever a server name is expected, the Env. button enables you to select, create, or delete server variables. For example, in the dialog box below, Accounting is a variable name which represents the server Compaq_01.
To Check if an Environment Variable ExistsSelect Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable.
How it's realized in my box.
Bash-script for startup:
#!/bin/sh
SMEMORY=1G
XMEMORY=1G
if [ $ENV == DEV ]; then
port_shutdown="8005"
port_http="8080"
port_https="8443"
elif
[ $ENV == SIT ]; then
port_shutdown="8006"
port_http="8081"
port_https="8444"
elif
[ $ENV == UAT ]; then
port_shutdown="8007"
port_http="8082"
port_https="8445"
else
echo "Unknown ENV"
exit 1
fi
export CATALINA_OPTS=" ${SYSTEM_PROPS} -d64 -server -Xms$SMEMORY -Xmx$XMEMORY \
-XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=64M \
-XX:+HeapDumpOnOutOfMemoryError -XX:MaxPermSize=1024M \
-Dport.http=${port_http} -Dport.https=${port_https} -Dport.shutdown=${port_shutdown}"
exec $CATALINA_HOME/bin/startup.sh
In server.xml
:
<Connector
port="${port.http}"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="${port.https}"
/>
Take a look at process:
$ ps ux | grep tomcat
... -Xms1G -Xmx1G ... -Denv=KIEV_DEV... -Dport.http=8084 -Dport.https=8446 -Dport.shutdown=8008...
Check ports:
$ netstat -anp | grep java
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp 0 0 :::8084 :::* LISTEN 23343/java
tcp 0 0 :::8446 :::* LISTEN 23343/java
Environment variables can be referenced in the server.xml etc by setting the system property org.apache.tomcat.util.digester.PROPERTY_SOURCE
to the value org.apache.tomcat.util.digester.Digester$EnvironmentPropertySource
.
That system property has been available since 7.0, but EnvironmentPropertySource
was not mentioned in the doc until 8.5.
https://tomcat.apache.org/tomcat-9.0-doc/config/systemprops.html
Update (April 2020):
The latest tomcat releases (9.0.34, 8.5.54) now support property replacement in most configuration files: https://tomcat.apache.org/tomcat-9.0-doc/changelog.html#Tomcat_9.0.34_(markt)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With