How to use .env files with Spring Boot

Ideally you want to define property values in a single place and reuse them in your docker-compose.yml file and your Spring Boot application. This is where .env files come in handy. In this post we'll quickly walk through how to use .env files with Spring Boot.

.env file

An example .env file:

# Environment variables that are used in the docker-compose.yml AND spring boot configuration
POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=5432
POSTGRES_USER=shane
POSTGRES_PASSWORD=shane
POSTGRES_DB=images

Spring Boot configuration

Use spring.config.import in your application.properties file to import the .env file:

# support reading from .env file
spring.config.import=file:../.env[.properties],file:.env[.properties]

spring.r2dbc.name=${POSTGRES_DB}
spring.r2dbc.username=${POSTGRES_USER}
spring.r2dbc.password=${POSTGRES_PASSWORD}
spring.r2dbc.host=${POSTGRES_HOST}
spring.r2dbc.port=${POSTGRES_PORT}
spring.r2dbc.url=r2dbc:postgresql://${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}

Note that you can import multiple .env files and the last one wins. For example, if you have a .env file in your project root and another in your src/main/resources directory, the .env file in src/main/resources will override the one in your project root.

Reuse

You can reuse the values in the .env file in your docker-compose.yml file using the env_file property:

services:
  db:
    image: postgres:15.0-alpine
    container_name: images-postgres
    hostname: postgres
    env_file:
      - .env
    ports:
      - 5432:5432
    restart: always
    volumes:
      - db:/var/lib/postgresql/data