Configure data sources for a Tomcat, JBoss, or Java SE app in Azure App Service

This article shows how to configure data sources in a Java SE, Tomcat, or JBoss app in App Service.

Azure App Service runs Java web applications on a fully managed service in three variants:

  • Java SE - Can run an app deployed as a JAR package that contains an embedded server (such as Spring Boot, Dropwizard, Quarkus, or one with an embedded Tomcat or Jetty server).
  • Tomcat - The built-in Tomcat server can run an app deployed as a WAR package.
  • JBoss EAP - Supported for Linux apps in the Premium v3 and Isolated v2 pricing tiers only. The built-in JBoss EAP server can run an app deployed as a WAR or EAR package.

Note

For Spring applications, we recommend using Azure Spring Apps. However, you can still use Azure App Service as a destination. See Java Workload Destination Guidance for advice.

Configure the data source

To connect to data sources in Spring Boot applications, we suggest creating connection strings and injecting them into your application.properties file.

  1. In the "Configuration" section of the App Service page, set a name for the string, paste your JDBC connection string into the value field, and set the type to "Custom". You can optionally set this connection string as slot setting.

    This connection string is accessible to our application as an environment variable named CUSTOMCONNSTR_<your-string-name>. For example, CUSTOMCONNSTR_exampledb.

  2. In your application.properties file, reference this connection string with the environment variable name. For our example, we would use the following code:

    app.datasource.url=${CUSTOMCONNSTR_exampledb}
    

For more information, see the Spring Boot documentation on data access and externalized configurations.

Tip

By default, the Linux Tomcat containers can automatically configure shared data sources for you in the Tomcat server. The only thing for you to do is add an app setting that contains a valid JDBC connection string to an Oracle, SQL Server, PostgreSQL, or MySQL database (including the connection credentials), and App Service automatically adds the cooresponding shared database to /usr/local/tomcat/conf/context.xml for you, using an appropriate driver available in the container. For an end-to-end scenario using this approach, see Tutorial: Build a Tomcat web app with Azure App Service on Linux and MySQL.

These instructions apply to all database connections. You need to fill placeholders with your chosen database's driver class name and JAR file. Provided is a table with class names and driver downloads for common databases.

Database Driver Class Name JDBC Driver
PostgreSQL org.postgresql.Driver Download
MySQL com.mysql.jdbc.Driver Download (Select "Platform Independent")
SQL Server com.microsoft.sqlserver.jdbc.SQLServerDriver Download

To configure Tomcat to use Java Database Connectivity (JDBC) or the Java Persistence API (JPA), first customize the CATALINA_OPTS environment variable that is read in by Tomcat at start-up. Set these values through an app setting in the App Service Maven plugin:

<appSettings>
    <property>
        <name>CATALINA_OPTS</name>
        <value>"$CATALINA_OPTS -Ddbuser=${DBUSER} -Ddbpassword=${DBPASSWORD} -DconnURL=${CONNURL}"</value>
    </property>
</appSettings>

Or set the environment variables in the Configuration > Application Settings page in the Azure portal.

Next, determine if the data source should be available to one application or to all applications running on the Tomcat servlet.

Application-level data sources

  1. Create a context.xml file in the META-INF/ directory of your project. Create the META-INF/ directory if it doesn't exist.

  2. In context.xml, add a Context element to link the data source to a JNDI address. Replace the driverClassName placeholder with your driver's class name from the table above.

    <Context>
        <Resource
            name="jdbc/dbconnection"
            type="javax.sql.DataSource"
            url="${connURL}"
            driverClassName="<insert your driver class name>"
            username="${dbuser}"
            password="${dbpassword}"
        />
    </Context>
    
  3. Update your application's web.xml to use the data source in your application.

    <resource-env-ref>
        <resource-env-ref-name>jdbc/dbconnection</resource-env-ref-name>
        <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
    </resource-env-ref>
    

Shared server-level resources

Adding a shared, server-level data source requires you to edit Tomcat's server.xml. The most reliable way to do this is as follows:

  1. Upload a startup script and set the path to the script in Configuration > Startup Command. You can upload the startup script using FTP.

Your startup script makes an xsl transform to the server.xml file and output the resulting xml file to /usr/local/tomcat/conf/server.xml. The startup script should install libxslt via apk. Your xsl file and startup script can be uploaded via FTP. Below is an example startup script.

# Install libxslt. Also copy the transform file to /home/tomcat/conf/
apk add --update libxslt

# Usage: xsltproc --output output.xml style.xsl input.xml
xsltproc --output /home/tomcat/conf/server.xml /home/tomcat/conf/transform.xsl /usr/local/tomcat/conf/server.xml

The following example XSL file adds a new connector node to the Tomcat server.xml.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@* | node()" name="Copy">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@* | node()" mode="insertConnector">
    <xsl:call-template name="Copy" />
  </xsl:template>

  <xsl:template match="comment()[not(../Connector[@scheme = 'https']) and
                                 contains(., '&lt;Connector') and
                                 (contains(., 'scheme=&quot;https&quot;') or
                                  contains(., &quot;scheme='https'&quot;))]">
    <xsl:value-of select="." disable-output-escaping="yes" />
  </xsl:template>

  <xsl:template match="Service[not(Connector[@scheme = 'https'] or
                                   comment()[contains(., '&lt;Connector') and
                                             (contains(., 'scheme=&quot;https&quot;') or
                                              contains(., &quot;scheme='https'&quot;))]
                                  )]
                      ">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()" mode="insertConnector" />
    </xsl:copy>
  </xsl:template>

  <!-- Add the new connector after the last existing Connnector if there's one -->
  <xsl:template match="Connector[last()]" mode="insertConnector">
    <xsl:call-template name="Copy" />

    <xsl:call-template name="AddConnector" />
  </xsl:template>

  <!-- ... or before the first Engine if there's no existing Connector -->
  <xsl:template match="Engine[1][not(preceding-sibling::Connector)]"
                mode="insertConnector">
    <xsl:call-template name="AddConnector" />

    <xsl:call-template name="Copy" />
  </xsl:template>

  <xsl:template name="AddConnector">
    <!-- Add new line -->
    <xsl:text>&#xa;</xsl:text>
    <!-- This is the new connector -->
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" 
               maxThreads="150" scheme="https" secure="true" 
               keystoreFile="${{user.home}}/.keystore" keystorePass="changeit"
               clientAuth="false" sslProtocol="TLS" />
  </xsl:template>

</xsl:stylesheet>

Finalize configuration

Finally, place the driver JARs in the Tomcat classpath and restart your App Service.

  1. Ensure that the JDBC driver files are available to the Tomcat classloader by placing them in the /home/site/lib directory. In the Cloud Shell, run az webapp deploy --type=lib for each driver JAR:
az webapp deploy --resource-group <group-name> --name <app-name> --src-path <jar-name>.jar --type=lib --path <jar-name>.jar

If you created a server-level data source, restart the App Service Linux application. Tomcat resets CATALINA_BASE to /home/tomcat and uses the updated configuration.

There are three core steps when registering a data source with JBoss EAP: uploading the JDBC driver, adding the JDBC driver as a module, and registering the module. App Service is a stateless hosting service, so the configuration commands for adding and registering the data source module must be scripted and applied as the container starts.

  1. Obtain your database's JDBC driver.

  2. Create an XML module definition file for the JDBC driver. The following example shows a module definition for PostgreSQL.

    <?xml version="1.0" ?>
    <module xmlns="urn:jboss:module:1.1" name="org.postgres">
        <resources>
        <!-- ***** IMPORTANT : REPLACE THIS PLACEHOLDER *******-->
        <resource-root path="/home/site/deployments/tools/postgresql-42.2.12.jar" />
        </resources>
        <dependencies>
            <module name="javax.api"/>
            <module name="javax.transaction.api"/>
        </dependencies>
    </module>
    
  3. Put your JBoss CLI commands into a file named jboss-cli-commands.cli. The JBoss commands must add the module and register it as a data source. The following example shows the JBoss CLI commands for PostgreSQL.

    #!/usr/bin/env bash
    module add --name=org.postgres --resources=/home/site/deployments/tools/postgresql-42.2.12.jar --module-xml=/home/site/deployments/tools/postgres-module.xml
    
    /subsystem=datasources/jdbc-driver=postgres:add(driver-name="postgres",driver-module-name="org.postgres",driver-class-name=org.postgresql.Driver,driver-xa-datasource-class-name=org.postgresql.xa.PGXADataSource)
    
    data-source add --name=postgresDS --driver-name=postgres --jndi-name=java:jboss/datasources/postgresDS --connection-url=${POSTGRES_CONNECTION_URL,env.POSTGRES_CONNECTION_URL:jdbc:postgresql://db:5432/postgres} --user-name=${POSTGRES_SERVER_ADMIN_FULL_NAME,env.POSTGRES_SERVER_ADMIN_FULL_NAME:postgres} --password=${POSTGRES_SERVER_ADMIN_PASSWORD,env.POSTGRES_SERVER_ADMIN_PASSWORD:example} --use-ccm=true --max-pool-size=5 --blocking-timeout-wait-millis=5000 --enabled=true --driver-class=org.postgresql.Driver --exception-sorter-class-name=org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter --jta=true --use-java-context=true --valid-connection-checker-class-name=org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker
    
  4. Create a startup script, startup_script.sh that calls the JBoss CLI commands. The following example shows how to call your jboss-cli-commands.cli. Later, you'll configure App Service to run this script when the container starts.

    $JBOSS_HOME/bin/jboss-cli.sh --connect --file=/home/site/deployments/tools/jboss-cli-commands.cli
    
  5. Using an FTP client of your choice, upload your JDBC driver, jboss-cli-commands.cli, startup_script.sh, and the module definition to /site/deployments/tools/.

  6. Configure your site to run startup_script.sh when the container starts. In the Azure portal, navigate to Configuration > General Settings > Startup Command. Set the startup command field to /home/site/deployments/tools/startup_script.sh. Save your changes.

To confirm that the datasource was added to the JBoss server, SSH into your webapp and run $JBOSS_HOME/bin/jboss-cli.sh --connect. Once you're connected to JBoss, run the /subsystem=datasources:read-resource to print a list of the data sources.

Next steps

Visit the Azure for Java Developers center to find Azure quickstarts, tutorials, and Java reference documentation.