Search code examples
google-app-enginespring-bootintellij-ideagoogle-cloud-sqlgoogle-cloud-tools

Configure MySql for various environments and deploy to Google App Engine via IntelliJ


I am using IntelliJ IDE to develop Spring Boot services with Maven and using Google Cloud Tools plugin to deploy to App Engine Flexible. While I use the following (to connect to local) and run the app. locally, it works fine (in application.properties).

spring.datasource.url=jdbc:mysql://localhost:3309/test

However, when I try to deploy to the GAE with the following (in application.properties),

spring.datasource.url=jdbc:mysql://google/test?cloudSqlInstance=[cloud-sql-instance]&socketFactory=com.google.cloud.sql.mysql.SocketFactory

when trying to build the project before uploading to GAE, it throws UnknownHostException: "google".

Questions:

  1. How can I create different configurations for various environments (dev (local) / qa(gae) / production(gae) ) and deploy to those environments with the corresponding environment values?

  2. When doing the build from the IDE, it validates the DB connection string (which points to the cloud sql instance) and throws an exception if it is not reachable (however it will be from the QA / Prod environment if the build is successful). How to resolve this case?

Any help on this would be greatly appreciated.

Thanks in advance.


Solution

  • You need to use Spring Profiles. Please read all the information in the documentation for an extensive explanation.

    Briefly:

    Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments

    Now, onto the problem at hand. It can be solved by introducing a "local" profile for you development and leaving the "default" profile to be used in production (GAE).

    application.properties

    # this file is for the "default" profile that will be used when 
    # no spring.profiles.active is defined. So consider this production config.
    
    spring.datasource.url=jdbc:mysql://google/test?cloudSqlInstance=[cloud-sql-instance]&socketFactory=com.google.cloud.sql.mysql.SocketFactory
    

    application-local.properties

    # this file is for the "local" profile that will be used when 
    # -Dspring.profiles.active=local is specified when running the application. 
    # So consider this "local" development config
    
    spring.datasource.url=jdbc:mysql://localhost:3309/test
    
    # In this file you can also override any other property defined in application.properties, or add additional ones
    

    Now to run the application while developing all you have to specify in IntelliJ in your run configuration is -Dspring.profiles.active=local under VM options, or if you're using a "Spring Boot" run configuration, you can just add local in the Active Profiles field.

    And on GAE, do not specify any profiles at all and the defaults will be used.