這里以Node.js為案例,適合其他web.這里以Ubuntu 14.04 amd64.為基礎,獲得ubuntu的最新images:
$ docker pull ubuntu:14.04
啟動一個新容器:
$ docker run -ti ubuntu:14.04 bash
在這個新容器中,安裝node.js:
$ apt-get update && apt-get install -y nodejs
創建應用內容在/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/");
在容器中啟動腳本/run.sh:
#! /bin/sh
/usr/bin/nodejs /server.js
$ chmod a+x /run.sh
停止這個容器,為其創建一個新的部署包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 設置 ENABLED 為 1
啟動后端實例
啟動一個web應用容器實例:
$ sudo -E docker run -d -p 8000 local/nodeapp /run.sh
測試是否啟動成功,首先我們要獲得Docker對外暴露的端口,一般是8000,這里是49153:
$ sudo docker ps
$ curl http://127.0.0.1:49153
應該得到響應:Responds with "Hello from {container_id}"
使用Synapse自動配置HAproxy
下面到了最關鍵的服務自動發現環節。使用下面內容創建一個文件/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來發現一個名為local/nodeapp的應用容器,端口在8000.
- services.nodesrv.haproxy: 與 HAproxy相關配置,配置其和nodesrv服務相關的端口.
- haproxy: 由Synapse管理的全局 HAproxy 實例配置。
啟動HAproxy 和 Synapse
$ sudo service haproxy start
$ sudo synapse -c /etc/synapse.json.conf
通過HAProxy訪問測試,這時它的端口是8080
$ curl http://localhost:8080
得到的響應是:Responds Hello from {container_id}
下面再次啟動nodeapp的第二個Docker:
$ sudo -E docker run -d -p 8000 local/nodeapp /run.sh
然后在測試HAproxy,過了幾秒會發現兩個節點服務器都有了響應。
下面我們測試如果一個節點關閉,是否會影響正常訪問,這實際就是失敗容錯failover。
下面命令是每過2秒循環調用一個HAproxy:
while :
do
curl http://localhost:8080
sleep 2
done
然后停止其中一個容器:
$ sudo -E docker stop {container_id}
過了幾秒以后,只有一個服務器在響應。