Artsiom the Brave
Artsiom the Brave

Reputation: 192

externalize spring datasource properties for docker

I want to be able to override

spring.datasource.url
spring.datasource.user
spring.datasource.password 

on each application start using environment variables;

That's because I'm trying to dockerize application and database. I want to specify url, user, password in .env file (for docker-compose) and share them with application container (connect to db) and db-container (to be able to connect).

I tried

export SPRING_DATASOURCE_URL=${url}
export SPRING_DATASOURCE_USER=${user}
export SPRING_DATASOURCE_PASSWORD=${password}
./mvnw spring-boot:run

But it seems to pick up only the last param (password in this case)

Also i tried

./mvnw spring-boot:run \
  -Dspring.datasource.url=${url} \
  -Dspring.datasource.user=${user} \
  -Dspring.datasource.password=${passwrod} \

but this one seem to care only about the first one (url in this case).

I really want to know if there is any viable method to achieve that via terminal or do I actually have to override properties file each time?

UPDATE

The problem was indeed in me. It's spring.datasource. username, not user. Really sorry for waisting time on that.

Upvotes: 1

Views: 1898

Answers (3)

Artsiom the Brave
Artsiom the Brave

Reputation: 192

There just was a typo. It's spring.datasource. username, not user (or SPRING_DATASOURCE_USERNAME). Really sorry for waisting time on that.

Upvotes: 1

Deadron
Deadron

Reputation: 5289

You are using maven to execute your spring boot app which is the cause of at least some of your problems.

When you specify a -D argument while using maven it is passing system arguments to maven not to your spring app. If you read https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-system-properties.html it shows you need to use the syntax

mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dproperty1=overridden"

The easy answer is dont use maven to execute your spring boot app. Produce a jar and execute it with java -jar

Upvotes: 2

ptomli
ptomli

Reputation: 11818

Do any of your values contain perhaps a space, or other shell busting character? Quotes are your friend here


Does a more basic java -jar target/project.jar -Dspring.datasource.url=... do anything different?

On the export SPRING_DATASOURCE_URL ... variant, can you properly echo $SPRING_DATASOURCE_URL and get the expected value back? For all the env variables?

If you use simple values like XXX and YYY instead of real values, does that do anything different?

Trying to distinguish between the mechanism and the data...


Are the ${url}, ${user} and ${password} (or ${passwrod} even) literal (eg: env variables themselves) or just elided here for brevity?

Upvotes: 1

Related Questions