· 7 years ago · Feb 16, 2018, 06:00 PM
1#!/bin/bash
2
3conf_dir=/opt/consul/conf
4mkdir -p ${conf_dir}
5
6nodes=(
7192.168.1.10
8192.168.1.11
9192.168.1.12
10)
11consul_ver=1.0.3
12retry_interval=15s
13contain_svr_name=consul_server
14
15privIP=$(/sbin/ifconfig eth0 | sed -n 's/.*inet \(addr:\)\?\([0-9.]\{7,15\}\) .*/\2/p')
16if [[ !("${nodes[@]}" =~ $privIP) ]];
17then
18 echo -e "Current node:${privIP} not in configured server nodes.\n"
19 exit
20fi
21
22svr_runing=$(docker ps -a | grep "${contain_svr_name}" | egrep "Up [About]|[0-9]{1,}")
23if [[ ${svr_runing} != "" ]];
24then
25 echo -e "Current container of consul server has been running.\n"
26 exit
27else
28 svr_exists=$(docker ps -a | grep "${contain_svr_name}")
29 if [[ ${svr_exists} != "" ]];
30 then
31 echo -e "Now try to start the container as it stopped...\n"
32 docker start ${svr_exists}
33 sleep 2
34 docker ps -a grep "${contain_svr_name}"
35 exit
36 fi
37fi
38
39echo -e "To start a new container for consul...\n"
40echo -e "To initialize configuration...\n"
41
42nodels=""
43for host in ${nodes[*]}
44do
45 if [[ $nodels != "" ]];
46 then
47 nodels=$nodels,
48 fi
49 nodels=$nodels"\"$host\""
50done
51
52config="{\n
53\"datacenter\": \"dctest\",\n
54\"retry_join\": [${nodels}],\n
55\"retry_interval\": \"${retry_interval}\",\n
56\"rejoin_after_leave\": true,\n
57\"start_join\": [${nodels}],\n
58\"bootstrap_expect\": 3,\n
59\"server\": true,\n
60\"ui\": true,\n
61\"dns_config\": {\"allow_stale\": true, \"max_stale\": \"5s\"},\n
62\"node_name\": \"$HOSTNAME\"\n
63}\n"
64
65echo $config
66echo -e ${config} > ${conf_dir}/server.json
67echo -e ${config}
68
69docker run -d -v ${conf_dir}:${conf_dir} \
70 --name ${contain_svr_name} \
71 --net=host consul:${consul_ver} agent \
72 -config-dir=${conf_dir} \
73 -client=0.0.0.0 \
74 -bind=${privIP} \
75 -advertise=${privIP}
76
77sleep 2
78
79svr_runing=$(docker ps -a | grep "${contain_svr_name}" | egrep "Up [About]|[0-9]{1,}")
80if [[ ${svr_runing} == "" ]];
81then
82 echo -e "\nError: docker-consul failed to start...\n"
83 exit
84fi
85echo -e "\nOK: docker-consul has started as background server.\n"