简体   繁体   中英

Tomcat production / dev environments

In PHP development, its possible to determine whether or not the app is running in a production or a development environment from the servers 'environment' variable.

Is there a similar variable available on tomcat servers, or is there a better way of targetting applications for production and development?

Every Tomcat instance we have has an isProduction flag defined in the GlobalNamingResources section of the server.xml file.

server.xml :

<Server ...>
  ...
  <GlobalNamingResources>
    <Environment name="isProduction" value="false" type="java.lang.Boolean" override="false" /> 
  </GlobalNamingResources>

  <Service name="Catalina">
  ... etc ...
  </Service>
</Server>

This allows the property to be available throughout the app by creating a property in the context.xml that references the resource:

context.xml :

<?xml version="1.0" encoding="UTF-8"?>
<Context ...>
  <ResourceLink name="isProduction" global="isProduction" type="java.lang.Boolean" />
  ...
</Context>

To fetch the value:

public boolean isProduction() {
   Object o;
   try {
      o = (new InitialContext()).lookup("java:comp/env/isProduction");
   }  catch (NamingException e) {
      o = Boolean.FALSE; // assumes FALSE if the value isn't declared
   }
   return o == null ? Boolean.FALSE : (Boolean) o;
}

You can't do such thing by default. In any case, do not rely on the container to determine whenever the app is in the environment X. I'd say that you should do it using one of the following methods (in order of preference):

  1. Use whatever your build tool provides. Eg: use maven profiles. http://maven.apache.org/guides/introduction/introduction-to-profiles.html
  2. Use a property file for the app with a "mode" property.
  3. Pass a -Dmyproject.mode=XXXX property to the JVM
  4. Use an OS system property

I encourage you to use something like #1. For sure you are using some kind of tool to build your app (Ant, SBT, etc).

Imagine if by mistake somebody reinstall Tomcat, remove the OS properties or similar. Your app might run in prod mode.

You could set up OS environment variables in tomcat startup scripts (run.sh at linux environment, for example) and read them from your program. Also you could setup java environment variables (like this: Passing environment variables to a JVM, in a platform-independent manner ). I personally use different property files for dev/prod/etc and read this variable for property file. Only required property file is deployed.

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