How to use setenv.sh or setenv.bat script in Apache Tomcat? Exporting environment variables using Tomcat’s setenv script

Tech Insights

The setenv.sh in UNIX or setenv.bat in Windows is a script file used to set or modify custom environment variables for the Tomcat application server. The deployed application(s) can use those variables as needed. Using a setenv script is the preferred way to keep our application specific customization separate from the server’s default configuration. If you check the catalina.sh or catalina.bat script file, it mentions about putting your customization in setenv script in CATALINA_BASE/bin. Moreover, if you have multiple applications deployed then setenv helps to have different configurations for each one of them as required.

If you don’t see the setenv script in CATALINA_BASE/bin, you need to create setenv.sh/setenv.bat first. To export a new environment variable, add the following line:

On Windows:

set ENV_VAR=foo


On Unix systems:

export ENV_VAR=foo

Save the script file and start the Tomcat server. You will be able to use ENV_VAR in your deployed applications. Use the following Java code to retrieve the value of specified environment variable in your application

System.getenv("ENV_VAR");

When the Tomcat server is started using catalina.sh it checks for both CATALINA_BASE/bin/setenv.sh and CATALINA_HOME/bin/setenv.sh and executes it, if exists. Tomcat’s startup.sh also does the same which in turn calls the catalina.sh to start the server. To know more about catalina.sh and startup.sh, read my post – catalina.sh vs startup.sh.

Note: If you set any environment variable which is confidential to your application, you should consider deleting the setenv script file once the server is started and your application is successfully deployed.