所以我要使用自定义环境文件取决于通过命令行传递的自定义环境变量。
假设我使用docker-compose run命令开始撰写:
docker-compose run -e ENVIROMENT=local spring-app
然后我想根据环境变量在我的docker-compose.yml文件中使用自定义.env
version: '2.1'
services:
spring-app:
build: .
depends_on:
docker-mariadb:
condition: service_healthy
links:
- docker-mariadb
ports:
- 8080:8080
environment:
- SPRING_PROFILES_ACTIVE
- DATABASE_HOST
- DATABASE_USER
- DATABASE_PASSWORD
- DATABASE_NAME
- DATABASE_PORT
env_file:
- ${ENVIROMENT}.env
docker-mariadb:
image: mariadb:latest
restart: always
environment:
- MYSQL_ROOT_PASSWORD=${DATABASE_PASSWORD}
- MYSQL_DATABASE=${DATABASE_NAME}
- MYSQL_PASSWORD=${DATABASE_PASSWORD}
healthcheck:
test: "/usr/bin/mysql --user=${DATABASE_USER} --password=${DATABASE_PASSWORD} --execute \"SHOW DATABASES;\""
interval: 30s
timeout: 10s
retries: 5
env_file:
- ${ENVIROMENT}.env
我的dockerfile:
FROM openjdk:10-jre-slim
VOLUME /tmp
ARG JAR_FILE="build/libs/spring-app-0.0.1-SNAPSHOT.jar"
COPY ${JAR_FILE} spring-app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/spring-app.jar"]
local.env:
SPRING_PROFILES_ACTIVE=prod
DATABASE_HOST=docker-mariadb
DATABASE_USER=root
DATABASE_PASSWORD=xxx
DATABASE_NAME=xxx
DATABASE_PORT=3306
当我运行此命令时,似乎未设置我的自定义ENVIROMENT变量,而docker仍要使用默认的.env文件。 这是我的错误:
❯ docker-compose run -e ENVIROMENT=local spring-app
WARNING: The ENVIROMENT variable is not set. Defaulting to a blank string.
WARNING: The DATABASE_PASSWORD variable is not set. Defaulting to a blank string.
WARNING: The DATABASE_NAME variable is not set. Defaulting to a blank string.
WARNING: The DATABASE_USER variable is not set. Defaulting to a blank string.
ERROR: Couldn't find env file: /Users/user/Desktop/docker-example/.env
答案 0 :(得分:3)
-e
标志用于将环境变量传递到容器。在docker run
命令之前添加环境,以将环境变量分配给docker引擎,以便可以进行环境变量插值
docker-compose run -e ENVIROMENT=local spring-app
[...]
ERROR: Couldn't find env file: /Users/sabhat/code/scratch/.env
ENVIROMENT=local docker-compose run spring-app
[...]
Starting scratch_docker-mariadb_1
顺便说一句,希望您知道docker-compose run
是run a one-time command for a service的意思-它不映射端口,也覆盖服务中定义的运行命令。您应该使用docker-compose up
调出整个容器