background
Recently, some friends asked Docker beginner, want docker-compose.yml
to dynamically pass parameters to the micro-service, rather than every time a hard-coded in the project configuration file, and then build service mirror, and finally packaged and released through a series processes in order to update the configuration, it can not directly by docker-compose.yml
the number of configuration items into the environment variable, and then springboot project automatically retrieves from environment variables?
Scenes
Suppose now that there is a Springboot project, it contains a database of configuration items, but a different database testing environment (DEV \ SIT \ UAT), multiple database ip, want to use the same image Springboot project, can always switch configuration database, is simply configure your database application Springboot should be passed through an external, rather than hardcode.
Springboot applications where there is a database configuration is as follows:
spring.datasource.url = jdbc:mysql://192.168.0.11:3306/db?useUnicode=true&characterEncoding=utf8
#配置数据库用户名
spring.datasource.username = sa
#配置数据库密码
spring.datasource.password = sa
solution
The use of SpEL
expressions, dynamic access to database configuration from environment variables
Next, we profile in the database configuration Springboot replaced with spEL expression
#配置数据库链接
spring.datasource.url = jdbc:mysql://${DB_HOST}:${DB_PORT}/${DB_NAME}?useUnicode=true&characterEncoding=utf8
#配置数据库用户名
spring.datasource.username = ${DB_USER}
#配置数据库密码
spring.datasource.password = ${DB_PASSWORD}
In the docker-compose.yml
configuration of our database parameters
version: '3'
services:
web:
restart: always
depends_on:
- db
image: springboot-app-image
build: .
ports:
- 8080:8080
environment:
- DB_HOST=192.168.0.11
- DB_PORT=3306
- DB_USER=root
- DB_PASSWORD=123456
- DB_NAME=db
networks:
- credit-facility-net
deploy:
mode: replicated
replicas: 3
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
update_config:
parallelism: 1
delay: 10s
So that our Springboot application can dynamically acquire the database configuration at boot time container services