Spring boot is not able to read docker-compose environmental variables

1.4k views Asked by At

I am having a "boring" problem here. Let me explain...

I am trying read some 'environmental variables' from my docker-compose, in my Application.properties.

Although, I am creating properly the env's variables in the containers(I can see that when I inspect the containers), they are not being read from the spring boot Applications.

Its kinda, these 'docker-compose environmental variables', seems like "are not accessible".

I am doing a TEST (); so, I am trying to get an environmental variable in my Spring Application, and it's resulting in 'null', such as:

@Slf4j
@SpringBootApplication(exclude = R2dbcAutoConfiguration.class)
public class AppDriver {
    public static void main(String[] args) {
        
        System.out.println(  "container variables >>>>> " + System.getenv("MASTER_URL")   );

        SpringApplication.run(AppDriver.class,args);
    }

The log is:

conteiner variables >>>>> null

Below, They are my docker-compose (i do not have any Spring boot service in the docker-compose[for now]):

version: "3.5"

services:

  tenant1:
    image: postgres
    ports:
      - "5432:5432"
    restart: always
    environment:
      POSTGRES_PASSWORD: password
      POSTGRES_DB: tenant1
      POSTGRES_USER: user
    volumes:
      - ./data/tenant1:/var/lib/postgresql

  mysql:
    image: mysql:5.7
    ports:
      - "3306:3306"
    environment:
      MASTER_URL: r2dbc:mysql://user:password@localhost/master
      MYSQL_ROOT_PASSWORD: mysecret
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: master

My Application.properties:

logging.level.com.example=DEBUG
logging.level.io.r2dbc=DEBUG

master.url = ${MASTER_URL}

And finally, my Java File:

@Configuration
//@ConfigurationProperties(prefix = "master")
@EnableR2dbcRepositories(entityOperationsRef = "masterEntityTemplate")
public class MasterConfig {

    @Value("${master.url}")
    private String url;

    @Bean
    @Qualifier(value = "masterConnectionFactory")
    public ConnectionFactory masterConnectionFactory() {

        System.out.println(">>>>>>>>>>>" + url);

        return ConnectionFactories.get(url);
        //.get("r2dbc:mysql://user:password@localhost/master");
    }

Thats the final error I am taking:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'MASTER_URL' in value "${MASTER_URL}"

Someone know how to solve this problem?

Thanks a lot

1

There are 1 answers

1
Msahazi On

The sythaxis for passing environment variables with in a compose file is varibaleName=value replace the colon(:) with the equals sign(=)

replace that:

MASTER_URL: r2dbc:mysql://user:password@localhost/master

with this:

  • MASTER_URL=r2dbc:mysql://user:password@localhost/master