如何检查Docker容器中是否设置了环境变量?

时间:2019-07-03 08:53:57

标签: bash docker apache-kafka

我正在尝试使用docker在每个节点kafka集群上设置一个单一代理。这个想法是多个Docker容器每个将包含一个代理,而我将有另一个Docker容器作为Zookeeper节点。我正在构建一个映像,在其中我可以将Zookeeper地址和代理ID作为环境变量传递给环境变量,以用于启动代理。当我从映像启动容器时,通过将它们作为env变量来传递,这对于启动具有不同代理ID的多个节点很有用。

这是我的dockerfile:

FROM openjdk:8

RUN mkdir /kafka
WORKDIR /kafka

COPY kafka_2.12-2.3.0 kafka_2.12-2.3.0

COPY cmd.sh cmd.sh

RUN cat /etc/os-release
RUN chmod +x ./cmd.sh

CMD ["./cmd.sh"]

EXPOSE 9092

这是我的cmd.sh

#!/bin/sh

export KAFKA_DIR=/kafka/kafka_2.12-2.3.0

if [[ -z $KAFKA_BROKER_ID || -z $KAFKA_ZOOKEEPER_ADDRESS ]]; then
  echo 'Zookeeper address and broker id need to be set by env variables KAFKA_ZOOKEEPER_ADDRESS and KAFKA_BROKER_ID'
  exit 1
fi

echo "Broker ID: ${KAFKA_BROKER_ID}"
echo "Zookeeper addresss: ${KAFKA_ZOOKEEPER_ADDRESS}"

"${KAFKA_DIR}"/bin/kafka-server-start.sh "${KAFKA_DIR}"/config/server.properties --override broker.id="${KAFKA_BROKER_ID}" --override zookeeper.connect="${KAFKA_ZOOKEEPER_ADDRESS}"

我是从问题How to check if multiple variables are defined or not in bash

中得到的

我希望看到错误消息,但我得到了:

./cmd.sh: 5: ./cmd.sh: [[: not found ./cmd.sh: 5: ./cmd.sh: -z: not
found Broker ID: Zookeeper addresss: [2019-07-03 08:56:04,172] INFO
Registered kafka:type=kafka.Log4jController MBean
(kafka.utils.Log4jControllerRegistration$) [2019-07-03 08:56:04,752]
ERROR Exiting Kafka due to fatal exception (kafka.Kafka$)
org.apache.kafka.common.config.ConfigException: Invalid value  for
configuration broker.id: Not a number of type INT

1 个答案:

答案 0 :(得分:0)

if ( -z "$KAFKA_ZOOKEEPER_ADDRESS" || -z "$KAFKA_BROKER_ID" )不适用于语法无效的bash:

您应该使用:

if [ -z "$KAFKA_ZOOKEEPER_ADDRESS" || -z "$KAFKA_BROKER_ID" ]; then

并将您的shebang更改为#!/bin/bash