[英]docker-compose : variables from .env not available in the service
我是 nodejs 的新手,我不知道為什么環境變量並不總是可用。
我的.env
中的環境變量由 docker-compose 自動解析。 所以我沒有使用 dotenv package。
console.log(process.env.API_URL) // outputs undefined
但是在異步 function 中(也許它不適用於所有異步函數)
async function foo() {
console.log(process.env.API_URL) // outputs http://example.com
}
在我的index.ts
中移動 console.log 幾種方式后,我找到了 env vars 可用的行:
// index.ts
import {createConnection} from 'typeorm'
console.log(process.env.API_URL) // outputs undefined
createConnection()
console.log(process.env.API_URL) // outputs http://example.com
知道為什么會這樣嗎?
編輯:
我正在使用這個 docker-compose.yml:
version: '3.7'
services:
server:
build:
context: ./docker-build
target: server-develop
ports:
- "3200:3000"
volumes:
- .:/var/app
command: "yarn run dev"
Docker 文檔似乎告訴.env
文件在未指定 env_file 時默認解析。 docker 文檔的屏幕截圖:
但是,在使用docker-compose exec server env
時,我看不到環境變量。 但是,如果我在env_file
中指定docker-compose.yml
(見下文),則環境變量會正確加載。
version: '3.7'
services:
server:
build:
context: ./docker-build
target: server-develop
env_file: .env # the only change
ports:
- "3200:3000"
volumes:
- .:/var/app
也許我誤解了 docker 的實際作用
默認加載 .env 文件
您可以從這里使用dotenv
https://www.npmjs.com/package/dotenv
可能您正在使用 nodemon 並且據我所知它只加載 NODE_ENV 變量。 通過使用dotenv
,您可以:
.env
require('dotenv').config()
您將找到有關 npmjs package 頁面本身的更多信息,例如更改啟動命令以便它可以自動加載.env
文件等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.