這里以Node.js為案例,適合其他web.這里以Ubuntu 14.04 amd64.為基礎(chǔ),獲得ubuntu的最新images:
$ docker pull ubuntu:14.04
啟動(dòng)一個(gè)新容器:
$ docker run -ti ubuntu:14.04 bash
在這個(gè)新容器中,安裝node.js:
$ apt-get update && apt-get install -y nodejs
創(chuàng)建應(yīng)用內(nèi)容在/server.js文件中:
var http = require('http');
var os = require('os');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello from " + os.hostname() + "\n");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
在容器中啟動(dòng)腳本/run.sh:
#! /bin/sh
/usr/bin/nodejs /server.js
$ chmod a+x /run.sh
停止這個(gè)容器,為其創(chuàng)建一個(gè)新的部署包image:
$ exit
# Get the ID of the container
$ sudo -E docker ps -a
# Change 3796ab3f5b76 in the following command with the ID listed above
$ sudo -E docker commit 3796ab3f5b76 local/nodeapp
# Remove the old container
$ sudo -E docker rm 3796ab3f5b76
安裝synapse
$ sudo apt-get install build-essential ruby ruby-dev haproxy
$ sudo gem install synapse
編輯/etc/default/haproxy 設(shè)置 ENABLED 為 1
啟動(dòng)后端實(shí)例
啟動(dòng)一個(gè)web應(yīng)用容器實(shí)例:
$ sudo -E docker run -d -p 8000 local/nodeapp /run.sh
測試是否啟動(dòng)成功,首先我們要獲得Docker對外暴露的端口,一般是8000,這里是49153:
$ sudo docker ps
$ curl http://127.0.0.1:49153
應(yīng)該得到響應(yīng):Responds with "Hello from {container_id}"
使用Synapse自動(dòng)配置HAproxy
下面到了最關(guān)鍵的服務(wù)自動(dòng)發(fā)現(xiàn)環(huán)節(jié)。使用下面內(nèi)容創(chuàng)建一個(gè)文件/etc/synapse.json.conf :
{
"services": {
"nodesrv": {
"discovery": {
"method": "docker",
"servers": [
{
"name": "localhost",
"host": "localhost"
}
],
"container_port": 8000,
"image_name": "local/nodeapp"
},
"haproxy": {
"port": 8080,
"listen": [
"mode http",
"option httpchk /",
"http-check expect string Hello"
]
}
}
},
"haproxy": {
"reload_command": "service haproxy reload",
"config_file_path": "/etc/haproxy/haproxy.cfg",
"do_writes": true,
"do_reloads": true,
"global": [
"chroot /var/lib/haproxy",
"user haproxy",
"group haproxy",
"daemon"
],
"defaults": [
"contimeout 5000",
"clitimeout 50000",
"srvtimeout 50000"
]
}
}
解釋配置如下:
- services.nodesrv.discovery: 這是watcher的配置.這里我們使用 Docker API來發(fā)現(xiàn)一個(gè)名為local/nodeapp的應(yīng)用容器,端口在8000.
- services.nodesrv.haproxy: 與 HAproxy相關(guān)配置,配置其和nodesrv服務(wù)相關(guān)的端口.
- haproxy: 由Synapse管理的全局 HAproxy 實(shí)例配置。
啟動(dòng)HAproxy 和 Synapse
$ sudo service haproxy start
$ sudo synapse -c /etc/synapse.json.conf
通過HAProxy訪問測試,這時(shí)它的端口是8080
$ curl http://localhost:8080
得到的響應(yīng)是:Responds Hello from {container_id}
下面再次啟動(dòng)nodeapp的第二個(gè)Docker:
$ sudo -E docker run -d -p 8000 local/nodeapp /run.sh
然后在測試HAproxy,過了幾秒會發(fā)現(xiàn)兩個(gè)節(jié)點(diǎn)服務(wù)器都有了響應(yīng)。
下面我們測試如果一個(gè)節(jié)點(diǎn)關(guān)閉,是否會影響正常訪問,這實(shí)際就是失敗容錯(cuò)failover。
下面命令是每過2秒循環(huán)調(diào)用一個(gè)HAproxy:
while :
do
curl http://localhost:8080
sleep 2
done
然后停止其中一個(gè)容器:
$ sudo -E docker stop {container_id}
過了幾秒以后,只有一個(gè)服務(wù)器在響應(yīng)。