tt_Gantz tt_Gantz - 4 months ago 47
Java Question

Flyway database migration to run automatically when new war deployed

I would like Flyway to run whenever I deploy a new war to my server.

Does flyway automatically get run when a server is deployed? Do I have to always automate a script which would then the flyway migration command? Or what is the best way to do this?

Server:

The server is a Java Tomcat Server running on Elastic Beanstalk (AWS) that is connected to a MySQL database.

Deployment Process

We run our sql migration scripts on the database manually. Then we upload a new war of the server to Elastic Beanstalk.

Answer

As the comments said, there may be multiple ways to do this.

ServletContextListener

One common way is to use the hook defined by the Java Servlet spec for being notified when your web app is launching and shutting-down. That hook is the ServletContextListener interface. Add a class to your project implementing the two methods in this interface, one for launch and one for shutdown. In the launch method, run your Flyway code. Annotating this class with @WebListener is one of multiple ways to get your Servlet container to register an instance.

Pretty easy.

Your ServletContextListener is guaranteed to be called and run to completion before the first execution of any Servlet (or Filter) in your web app. So this is the perfect place to do setup work that you want finished before your servlets go to work. Flyway seems like a natural fit to me.

Search Stack Overflow for “ServletContextListener” to learn more and see examples, such as my own Question & Answer.

Side issue: Be aware that stopping a web app’s deployment when something goes wrong (when your ServletContextListener encounters an Exception) is not well-defined in the Servlet spec. See my own Question and Answer and the group of related questions I list in that answer. Tomcat 8.0.33 halts the deployment, and un-deploys the web app, but unfortunately does not report the offending Exception (or at least I could not find any such report in the logs nor in the IDE console while in development mode). The behavior of other Servlet containers may vary.