首页 > 解决方案 > Tomcat:为不同的webapps指定不同的属性

问题描述

我运行了一系列单独的 webapps,它们需要单独的配置,但基本上都使用相同的代码,因此使用相同的 war 文件。war 文件能够从环境变量中读取其配置文件的路径,并且我可以在 context.xml 文件中看到如何为整个 Tomcat 上下文设置环境变量。

但是,我看不到如何在不同的上下文中运行单个 web 应用程序;并且同一上下文中的所有 webapps 将看到相同的环境变量值,因此从同一位置加载配置。

是否有一种机制可以在上下文中为不同的 webapps 设置不同的环境值;如果没有,是否有其他机制(在 WAR 文件本身之外)为不同的 webapps 指定不同的属性值,或者为每个 webapps 创建单独的上下文?

最后,如果我可以将配置移到 webapp 之外,是否可以让多个 webapps 使用相同的实际 WAR 文件(因为除了配置之外它们都是相同的,如果我只需要插入一个单个 WAR 文件)?

标签: tomcatpropertiestomcat8environment

解决方案


Edit: Looking at your code (particularly configuration.clj) it appears that you are using system environment variables (which are shared among all web applications). You should use environment entries instead and retrieve them through a call to InitialContext.lookup("java:comp/env/FOO") instead of System.getenv("FOO").

Technically every application has its own <Context>, which is composed by (cf. Tomcat documentation):

  • the values from $CATALINA_BASE/conf/context.xml,
  • the values from $CATALINA_BASE/conf/<enginename>/<host>/context.xml.default
  • the values from $CATALINA_BASE/conf/<enginename>/<host>/<path>.xml or (if it is missing and deployXML of the <Host> is not false) the entries in META-INF/context.xml of your application.

Each more specific configuration file can overwrite the attributes of the more general configuration files, while the nested components are added up. Therefore you should probably define:

  • the environment entries specific to each application in $CATALINA_BASE/conf/<enginename>/<host>/<path>.xml,
  • the environment entries common to all applications in $CATALINA_BASE/conf/context.xml.

Remark: Usually <enginename> is Catalina, while <host> is localhost.

If you are using the same WAR file you can just place it outside of the document base (let's say /usr/share/my.war) and create a bunch of <path>.xml files in $CATALINA_BASE/conf/<enginename>/<host>:

<Context docBase="/usr/share/my.war">
    <!--
        environment entries
    -->
</Context>

The path under which they will be deployed will be inferred from the name of the XML.


推荐阅读