我尝试使用Docker和 Docker Compose 来创建容器化应用。我有一个PubNub帐户,允许我为不同的环境(dev,test,prod)使用不同的API密钥。为了帮助我为此构建图像,我尝试使用 env_file 设置 build args 。
它不能正常工作。
WARNING: The PUB_KEY variable is not set. Defaulting to a blank string.
WARNING: The SUB_KEY variable is not set. Defaulting to a blank string.
问题:
ENV
和scan
设置flask
变量的好方法吗?最底部是 IntelliJ IDE屏幕截图,或者文本代码就在下方。
以下是docker-compose.yml
内容:
version: '3.6'
services:
scan:
env_file:
- sample.env
build:
context: .
dockerfile: Dockerfile
args:
pub_key: $PUB_KEY
sub_key: $SUB_KEY
target: scan
image: bt-beacon/scan:v1
flask:
env_file:
- sample.env
build:
context: .
dockerfile: Dockerfile
args:
pub_key: $PUB_KEY
sub_key: $SUB_KEY
target: flask
image: bt-beacon/flask:v1
ports:
- "5000:5000"
Dockerfile
:
# --- BASE NODE ---
FROM python:3.6-jessie as base
ARG pub_key
ARG sub_key
RUN test -n "$pub_key"
RUN test -n "$sub_key"
# --- SCAN NODE ---
FROM base as scan
ENV PUB_KEY=$pub_key
ENV SUB_KEY=$sub_key
COPY app/requirements.scan.txt /
RUN apt-get update
RUN apt-get -y install bluetooth bluez bluez-hcidump python-bluez python-numpy python3-dev libbluetooth-dev libcap2-bin
RUN pip install -r /requirements.scan.txt
RUN setcap 'cap_net_raw,cap_net_admin+eip' $(readlink -f $(which python))
COPY app/src /app
WORKDIR /app
CMD ["./scan.py", "$pub_key", "$sub_key"]
# -- FLASK APP ---
FROM base as flask
ENV SUB_KEY=$sub_key
COPY app/requirements.flask.txt /
COPY app/src /app
RUN pip install -r /requirements.flask.txt
WORKDIR /app
EXPOSE 5000
CMD ["flask", "run"]
最后,sample.env
:
# PubNub app keys here
PUB_KEY=xyz1
SUB_KEY=xyz2
答案 0 :(得分:4)
env_file
只能在服务容器中设置环境变量。 env_file
中的变量无法注入docker-compose.yml
本身。
您有这样的选择(described there in detail):
docker-compose up
.env
文件(语法与您的sample.env
相同)我个人将图像构建过程和容器启动过程分开(从docker-compose到外部脚本中删除图像构建责任,然后可以轻松配置构建过程)。