多节点服务浮动IP测试

概览:

先决步骤

  • 代码传送门:
Download Now

Makefile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
all: build

.PHONY: build
build:
@go build -tags netgo -installsuffix 'static' -ldflags "-s -w" -o server main.go

.PHONY: deploy
deploy:
@docker stack deploy -c docker-compose.yml Node

.PHONY: docker
docker:
@docker build -f "Dockerfile/service" -t helloserver:latest .

.PHONY: clean
clean:
@rm -f server

服务器端代码
‘main.go’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
)

var (
HOSTNAME string = "UNKNOW"
)

func init() {
name, err := os.Hostname()
if err != nil {
name = err.Error()
}
HOSTNAME = name
}

func main() {
mux := http.NewServeMux()
mux.Handle("/", http.StripPrefix("/", handler{}))

server := &http.Server{
Addr: "0.0.0.0:8080",
Handler: mux,
}
log.Printf("server Running at http://%v\n", server.Addr)

server.ListenAndServe()
}

type handler struct{}

func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()

w.Write([]byte(HOSTNAME + ":\t" + time.Now().Format("2006-01-02 15:04:05")))

requestsURL, _ := url.QueryUnescape(r.RequestURI)
fmt.Printf("%v ---> %v %v %s ", r.RemoteAddr, r.Proto, r.Method, requestsURL)
fmt.Println(time.Since(start))

w.Write([]byte("\t<<< " + requestsURL))
}

docker部分:

docker-compose.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
version: '3.9'

services:
server:
image: helloserver:latest
ports:
- "8090:8080"
networks:
- overlay
volumes:
- data:/data
deploy:
mode: replicated
replicas: 3
endpoint_mode: vip
restart_policy:
delay: 10s
max_attempts: 3

volumes:
data:

networks:
overlay:

Dockerfile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
FROM golang:1.17 AS builder

ENV GOPROXY=https://goproxy.io,direct

WORKDIR /usr/src

COPY go.mod go.mod
COPY main.go main.go
COPY scripts scripts
COPY Makefile Makefile

RUN ls -alh
RUN go mod tidy
RUN make build

# Final image.
FROM alpine:latest AS server

WORKDIR /opt/app

COPY --from=builder /usr/src/server .

ENTRYPOINT ["/opt/app/server"]

将以上文件写好之后,开始运行测试

编译打包:

1
make docker

部署服务集群

1
make deploy

测试

1
curl http://localhost:8080