1. 程式人生 > >用docker swarm 實現叢集

用docker swarm 實現叢集

(1) go 編寫 web 程式 

    主要實現 監聽 ip:9090/Source 瀏覽,並記錄 伺服器主機與訪問次數。

    程式碼

package main

import (
 "fmt"
 "log"
 "net/http"
 "runtime"
 "strconv"
 "os"
)
var i int = 0
func sayHello(w http.ResponseWriter, r *http.Request){
//func sayHello(){
        i++
        fmt.Print(i)
        fmt.Print("\n")
        fmt.Print("visit!"+"\n")
        hostname,er :=os.Hostname()
        if er == nil {
                dates := "jenkins:"+"Login \n"+"visit Count:"+strconv.Itoa(i)+"\nHostname:"+hostname
                w.Write([]byte(dates))
                defer r.Body.Close()
        }else {
                return
        }
}
func main(){
        fmt.Print("<<<<< "+runtime.GOOS+"\n")
        fmt.Print("<<<<< "+runtime.GOARCH+"\n")
        http.HandleFunc("/Source",sayHello)
        fmt.Print("<<< debug start"+"\n")
        er := http.ListenAndServe(":9090",nil)
        fmt.Print("<<< debug end")
        fmt.Print(er)
        if er != nil {
                log.Fatal("ListenAndServe",er)
        }
}

(2) 生成arch 程式

    go build arch.go

(3) arch + Dockerfile 生成微服務映象

    Dockerfile

FROM ubuntu:16.04
MAINTAINER ZHB
COPY ./arch /
RUN chmod 777  /arch
RUN touch /log.txt
EXPOSE 9090
ENTRYPOINT ["sh","-c","./arch >> /log.txt"]  #可在 容器裡 tail -f log.txt 監控

    docker build -t ip:5000/swarm:0.0 ./

[email protected]:~/SWARM$ docker build -t 192.168.175.139:5000/swarm:0.0  ./
Sending build context to Docker daemon  6.629MB #Sending build context 可以用.dockerignore 阻止 
Step 1/7 : FROM ubuntu:16.04
 ---> a51debf7e1eb
Step 2/7 : MAINTAINER ZHB
 ---> Using cache
 ---> 26b542a8286b
Step 3/7 : COPY ./arch /
 ---> Using cache
 ---> aff0b358480c
Step 4/7 : RUN chmod 777  /arch
 ---> Using cache
 ---> 6e07a223b571
Step 5/7 : RUN touch /log.txt
 ---> Using cache
 ---> 03be86c93b8a
Step 6/7 : EXPOSE 9090
 ---> Using cache
 ---> fe9c6a7ab542
Step 7/7 : ENTRYPOINT ["sh","-c","./arch >> /log.txt"]
 ---> Using cache
 ---> 6287178e0005
Successfully built 6287178e0005
Successfully tagged 192.168.175.139:5000/swarm:0.0

push 映象

    docker push ip:5000/swarm:0.0

(4)主節點 swarm init

    docker swarm init

    其他伺服器加入叢集

   docker swarm join --token **** ip:2377

(5)建立service 

    docker service create --replicas 6 --name=swarm-service --publish 9090:9090 IP:5000/swarm:0.0

overall progress: 0 out of 6 tasks
1/6: preparing [=================================>                 ]
2/6: preparing [=================================>                 ]
3/6: preparing [=================================>                 ]
4/6: preparing [=================================>                 ]
5/6: preparing [=================================>                 ]
6/6: preparing [=================================>                 ]

(6) web 訪問 ip:9090/Source 並實現負載均衡