docker compose 环境变量在 nodejs 容器中未定义
docker compose environment varibales are undefined in nodejs container
尝试控制台记录 docker 中定义的环境变量时 - 将节点容器 returns 的值设为未定义。
docker-compose.yml
version: "3"
services:
api:
build: ./api
ports:
- "3004:3004"
volumes:
- type: bind
source: ./api
target: /usr/src/api
working_dir: /usr/src/api
environment:
REDIS_HOST: "redis://redis:6379"
TEST: "123"
depends_on:
- redis
networks:
- backend
redis:
image: "redis:latest"
ports:
- "6379:6379"
networks:
- backend
networks:
backend:
driver: bridge
我试过更改 yaml 语法
到 - TEST="123"
而不是键值语法只是为了确保。我不确定是什么问题。
API docker文件如下所示:
FROM node:12
# create destination directory
RUN mkdir -p /usr/src/api
WORKDIR /usr/src/api
# copy the app, note .dockerignore
COPY . /usr/src/api
# Install packages
RUN npm i yarn --save
RUN yarn
# COPY . /src
EXPOSE 3005
CMD ["yarn", "dev"]
NodeJS 代码段:
console.log("redis host! + test");
console.log(process.env.REDIS_HOST, process.env.TEST)
控制台日志输出:
api_1 | redis host! + test
api_1 | undefined undefined
您需要使用 ARG
在 Dockerfile
中额外引用环境变量
ARG REDIS_HOST
ARG TEST
尝试控制台记录 docker 中定义的环境变量时 - 将节点容器 returns 的值设为未定义。
docker-compose.yml
version: "3"
services:
api:
build: ./api
ports:
- "3004:3004"
volumes:
- type: bind
source: ./api
target: /usr/src/api
working_dir: /usr/src/api
environment:
REDIS_HOST: "redis://redis:6379"
TEST: "123"
depends_on:
- redis
networks:
- backend
redis:
image: "redis:latest"
ports:
- "6379:6379"
networks:
- backend
networks:
backend:
driver: bridge
我试过更改 yaml 语法 到 - TEST="123" 而不是键值语法只是为了确保。我不确定是什么问题。
API docker文件如下所示:
FROM node:12
# create destination directory
RUN mkdir -p /usr/src/api
WORKDIR /usr/src/api
# copy the app, note .dockerignore
COPY . /usr/src/api
# Install packages
RUN npm i yarn --save
RUN yarn
# COPY . /src
EXPOSE 3005
CMD ["yarn", "dev"]
NodeJS 代码段:
console.log("redis host! + test");
console.log(process.env.REDIS_HOST, process.env.TEST)
控制台日志输出:
api_1 | redis host! + test
api_1 | undefined undefined
您需要使用 ARG
Dockerfile
中额外引用环境变量
ARG REDIS_HOST
ARG TEST