启动Docker容器时是否可以使用在入口点脚本中导出的变量?

时间:2018-11-04 16:35:13

标签: docker

所以,我的问题是我正在尝试使用etcd构建具有3个副本的docker服务。

在启动容器之前,我需要知道其 IP 名称,因此我创建了一个入口点脚本来为我生成该脚本,然后将其导出到环境变量中

运行docker服务时如何使用这些变量或引用它们?

Dockerfile

FROM bitnami/etcd:latest
COPY etcd.sh /
ENV ALLOW_NONE_AUTHENTICATION yes
ENV ETCD_ADVERTISE_CLIENT_URLS=http://etcd-server:2379
ENV ETCD_DATA_DIR=/etcd-data/LOGS
USER root
RUN chmod +x /etcd.sh
RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
ENTRYPOINT ["/etcd.sh"]

etcd.sh

#!/bin/bash

ETCD_VERSION=latest
TOKEN=my-etcd-token
CLUSTER_STATE=new
DATA_DIR=/etcd-data/LOGS

echo "[DEBUG] Setting up static variables...DONE"

a=0

while [ $a -lt 3 ]
do
    NAME[$a]=etcd-node-$a
    a=`expr $a + 1`
done

echo "[DEBUG] Setting up names of the nodes...DONE"

apt-get update
apt-get install -y dnsutils
cluster="$(nslookup tasks.etcd-server | grep Address | awk 'NR>1{print $2}' ORS=',' | head -c -1)"

echo "[DEBUG] Installing nslookup and looking for other nodes in the network...DONE"

IFS=',' read -ra ADDR <<< "$cluster"

a=0

for i in "${ADDR[@]}"
do
    HOST[$a]=$i
    a=`expr $a + 1`
done

echo "[DEBUG] Setting up IP addresses of the nodes...DONE"

a=0
while [ $a -lt 3 ]
do 
    CLUSTER=${NAME[$a]}=http://${HOST[$a]}:2380,$CLUSTER
    a=`expr $a + 1`
done

export CLUSTER="${CLUSTER::-1}"

echo "Setup phase...DONE"
echo "------------------"
echo $CLUSTER
echo "------------------"

export THIS_IP="$(hostname -i)"

for i in "${!HOST[@]}"; do
   if [[ "${HOST[$i]}" = "${THIS_IP}" ]]; then
       export THIS_NAME="${HOST[$i]}";
   fi
done

我要使用的脚本变量为 CLUSTER THIS_IP THIS_NAME

有了这个变量,我可以从主机上运行以下命令:

docker service create --replicas 3 --network etcd-network --name etcd-server \
--mount source=etcd-vol,target=/etcd-data/LOGS custom-etcd 3 \
--data-dir=/etcd-data --name ${THIS_NAME} \
--initial-advertise-peer-urls http://${THIS_IP}:2380 \
--listen-peer-urls http://${THIS_IP}:2380 \
--advertise-client-urls http://${THIS_IP}:2379 \
--listen-client-urls http://${THIS_IP}:2379 \
--initial-cluster ${CLUSTER} \
--initial-cluster-state new

0 个答案:

没有答案