2017-02-15 49 views
2

當我運行搬運工,撰寫構建我有一個.ENV文件用於我的泊塢窗機建設環境變量是這樣的:搬運工.ENV文件重用聲明的變量

COMPOSE_PROJECT_NAME=radar 
ENV=production 
DB_NAME=postgres 
DB_USER=postgres 
DB_PASS=sho1c2ov3Phezaimah7eb2Tii4ohkah8k 
DB_SERVICE=postgres 
DB_PORT=5432 
C_FORCE_ROOT="true" 
PGHOST=postgres 
PGDATABASE=postgres 
PGUSER=postgres 
PGPASSWORD=sho1c2ov3Phezaimah7eb2Tii4ohkah8k 
PGPORT=5432 

如果你已經注意到了冗餘像'DB_NAME'和'PGDATABASE'是一樣的..有沒有辦法避免這種情況?

回答

2

關於您Dockerfile做這樣的事情是什麼?

ARG DB_NAME 
ENV DB_NAME=${DB_NAME} PGDATABASE=${DB_NAME} ... 

測試

$ cat Dockerfile 
FROM alpine:3.4 

ARG DB_NAME 
ENV DB_NAME=${DB_NAME} PGDATABASE=${DB_NAME} 

RUN env 

撰寫文件版本2或更高!

$ cat docker-compose.yml 
version: '3' #'2' should work as well 

services: 
    docker-arg-env: 
    build: 
     context: . 
     args: 
     - DB_NAME 
    command: env 

$ cat .env 
DB_NAME=world 

$ docker-compose build 
Building docker-arg-env 
Step 1/4 : FROM alpine:3.4 
---> 0766572b4bac 
Step 2/4 : ARG DB_NAME 
---> Running in a56be8426dd5 
---> 4b1009ba9fad 
Removing intermediate container a56be8426dd5 
Step 3/4 : ENV DB_NAME ${DB_NAME} PGDATABASE ${DB_NAME} 
---> Running in 5bbdd40e640e 
---> 593105981a2a 
Removing intermediate container 5bbdd40e640e 
Step 4/4 : RUN env 
---> Running in dadf204c7497 
HOSTNAME=26ba10d264c2 
SHLVL=1 
HOME=/root 
PGDATABASE=world 
DB_NAME=world 
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 
PWD=/ 
---> 9632ee1e0e37 
Removing intermediate container dadf204c7497 
Successfully built 9632ee1e0e37 

$ docker-compose up 
Creating network "dockerargenv_default" with the default driver 
Creating dockerargenv_docker-arg-env_1 
Attaching to dockerargenv_docker-arg-env_1 
docker-arg-env_1 | PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 
docker-arg-env_1 | HOSTNAME=5a6b51f4ecc7 
docker-arg-env_1 | DB_NAME=world 
docker-arg-env_1 | PGDATABASE=world 
docker-arg-env_1 | HOME=/root 

正如你所看到的,PG_NAME和PGDATABASE期間構建時設置和運行時間。

沒有撰寫

docker build --build-arg DB_NAME=world .docker run docker-arg-env:latest env產生相同的結果。

更新

如果你不能(或不願)修改Dockerfile嘗試是這樣的:

$ cat .env 
hello=world 

$ cat docker-compose.yml 
version: '2' 
services: 
    app: 
    environment: 
     - bar=${hello} 
     - foo=${hello} 
    image: someimage 

$ docker-compose config 
version: '2' 
services: 
    app: 
    environment: 
     - bar=world 
     - foo=world 
    image: someimage 

見:https://docs.docker.com/compose/environment-variables/#the-env-file

+0

你試過了嗎?不幸的是,它不適用於我 –

+0

我現在;-)答案中包含示例。 – Martin

+0

噢,我完全忘了你正在使用'docker-compose build'。應該再讀一遍問題。 – Martin