前言
在配置中,为了不在docker compose文件的一些配置进行硬编码,有时候会把配置外提
环境变量替换
yaml
version: "3"
services:
saas-auth:
image: ${UT_IMAGE_PREFIX}/saas-auth:${UT_SAAS_LOCK_IMAGE_TAG}
container_name: saas-auth
environment:
TZ: Asia/Shanghai
LUBAN_REGISTER_PORT: 2181
LUBAN_REGISTER_HOST: ${UT_ZOOKEEPER_HOST}
LUBAN_SPRING_DATASOURCE_URL: jdbc:postgresql://${UT_POSTGRES_HOST}:${UT_POSTGRES_PORT}/luban
LUBAN_SPRING_DATASOURCE_USERNAME: ${UT_POSTGRESQL_USER}
LUBAN_SPRING_DATASOURCE_PASSWORD: ${UT_POSTGRESQL_PASSWORD}
USER_CENTER: http://usercenter-gateway:30000/ # usercenter
DEVICE_PLATFORM_MYSQL_PWD: ut123456 # device basic platform
PLATFORM_DEVICE_URL: http://utsmart-gateway:9999
PLATFORM_LIGHT_URL: http://saas-gateway:63301/api/light
SPRING_REDIS_HOST: ${UT_REDIS_HOST}
SPRING_REDIS_PASSWORD: ${UT_REDIS_PASSWORD}
SPRING_RABBITMQ_HOST: ${UT_RABBIT_HOST}
SPRING_RABBITMQ_USERNAME: ${UT_RABBIT_USERNAME}
SPRING_RABBITMQ_PASSWORD: ${UT_RABBIT_PASSWORD}
MQTT_IS_ENABLED: true
MQTT_SERVER_HOST: ${UT_EMQX_HOST}
MQTT_SERVER_PORT: ${UT_EMQX_MQTT_PORT}
PLATFORM_DEVICE_APPLICATIONID: 12
ALIYUN_SMS_ACCESSKEYID: aaa
ALIYUN_SMS_ACCESSKEYSECRET: bb
ALIYUN_PUSH_SMS_TEMPLATE_CODE_VERIFICATION: cc
JAVA_OPTIONS: "-Duser.language=zh -Duser.country=CN -Dfile.encoding=utf-8 -Djava.awt.headless=true --add-opens java.base/jdk.internal.loader=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-exports java.desktop/sun.font=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=summary -Xmx700m"
AUTHENTICATION_EXPIRATIONTIME: 10080
DUBBO_PROVIDER_TIMEOUT: 60000
deploy:
resources:
limits:
memory: 1.2G
reservations:
memory: 1.2G
ports:
- 63302:63302
healthcheck:
test:
[
"CMD-SHELL",
"curl -f http://127.0.0.1:63302/administrativeRegions/getStreet/1",
]
interval: 6s
timeout: 10s
retries: 50
restart: always
depends_on:
utsmart-zookeeper:
condition: service_healthy
utsmart-redis:
condition: service_healthy
utsmart-emqx:
condition: service_healthy
utsmart-postgres:
condition: service_healthy
volumes:
- ${UT_BASE}/ut/logs/saas:/deployments/logs
networks:
- ut-network
一般会把可配置的环境变量外提${UT_POSTGRESQL_USER}
传入环境变量
${UT_POSTGRESQL_USER} 这类变量是 Docker Compose 的环境变量插值语法,Compose 会在解析 YAML 时自动替换。传参有以下几种方式,按优先级从高到低排列:
1. 同目录 .env 文件(✅ 最推荐)
在 docker-compose-saas-auth.yml 同级目录 下创建 .env 文件:

ini
1# .env
2UT_POSTGRESQL_USER=saas_auth_user
3UT_POSTGRESQL_PASSWORD=your_password
4UT_POSTGRESQL_HOST=postgres-host
5UT_POSTGRESQL_PORT=5432
6UT_POSTGRESQL_DB=saas_auth_db
然后直接启动即可,Compose 自动加载,无需任何额外参数:
docker compose -f docker-compose-saas-auth.yml up -d
⚠️
.env文件名必须精确匹配,不支持自定义命名(除非用--env-file)。
2. --env-file 指定外部文件
如果环境变量文件不在同目录或需要区分环境:
bash
编辑
css
1docker compose -f docker-compose-saas-auth.yml --env-file /path/to/prod.env up -d
支持多个 --env-file,后面的覆盖前面的:
bash
1docker compose -f docker-compose-saas-auth.yml \
2 --env-file ./common.env \
3 --env-file ./prod.env \
4 up -d
总结
docker compose环境变量替换,${UT_POSTGRESQL_USER} 这类变量是 Docker Compose 的环境变量插值语法,Compose 会在解析 YAML 时自动替换。