目录

nginx案例

准备应用

go应用,返回环境变量

func InitGinRouter() {
	engine := gin.Default()
	engine.GET("/test", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  os.Getenv("SERVER_NODE_NAME"),
		})
	})
	engine.Run(":8800")
}

编译出二进制文件hello

nginx配置文件

nginx.conf

user  root;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main escape=json '$remote_addr-$time_iso8601-$request_uri-$request-$status';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    #gzip  on;
    include /etc/nginx/conf.d/*.conf;

   upstream myupstream {
    server hello-server:8800;
    server hello-server2:8800; // ip也可
   }
   server {
        #监听端口
        listen 80;
        server_name localhost;
        location /test {
            proxy_pass http://myupstream;
        }

   }

}

在这里我们监听80端口,并指定路由/test,满足该路由就会反向代理到myupstream,然后请求轮询打到hello-server:8800,hello-server2:8800。 除了轮询外,还有其他策略。

当一个应用挂掉,会自动的停止给它请求,应用恢复后会自动再分配给它请求。

准备docker-compose

hello应用的Dockerfile:

FROM ubuntu
COPY ./hello /hello/
WORKDIR /hello/
ENTRYPOINT ["./hello"]

docker-compose.yml

version: '3.2'

services:
    hello-server:
      build:
        context: ./
        dockerfile: ./Dockerfile
      restart: always
      environment:
        SERVER_NODE_NAME: "hello1" #这里自行设置root用户的密码
      networks:
          - hello-net
    hello-server2:
      build:
        context: ./
        dockerfile: ./Dockerfile
      restart: always
      environment:
        SERVER_NODE_NAME: "hello2" #这里自行设置root用户的密码
      networks:
        - hello-net

    hello-nginx:
      image: nginx
      volumes:
        - /Users/lhx/Documents/go_project/hello/nginx.conf:/etc/nginx/nginx.conf
        - /Users/lhx/Documents/go_project/hello/log/nginx:/var/log/nginx/
      ports:
        - 80:80
      networks:
        - hello-net


networks:
    hello-net:
     driver:
      bridge

docker-compose up -d 运行后,访问http://localhost:81/test就能轮询服务器