packagemainimport("context""flag""log""net/http""os""os/signal""syscall""time")var(listenAddrstring)funcmain(){flag.StringVar(&listenAddr,"listen-addr",":8080","server listen address")flag.Parse()logger:=log.New(os.Stdout,"http: ",log.LstdFlags)router:=http.NewServeMux()// here you could also go with third party packages to create a router// Register your routesrouter.HandleFunc("/",func(whttp.ResponseWriter,r*http.Request){time.Sleep(15*time.Second)w.WriteHeader(http.StatusOK)})router.HandleFunc("/ping",func(whttp.ResponseWriter,r*http.Request){time.Sleep(10*time.Second)w.WriteHeader(http.StatusOK)})server:=&http.Server{Addr:listenAddr,Handler:router,ErrorLog:logger,ReadTimeout:30*time.Second,WriteTimeout:30*time.Second,IdleTimeout:30*time.Second,}done:=make(chanbool,1)quit:=make(chanos.Signal,1)signal.Notify(quit,syscall.SIGINT,syscall.SIGTERM)gofunc(){<-quitlogger.Println("Server is shutting down...")ctx,cancel:=context.WithTimeout(context.Background(),30*time.Second)defercancel()iferr:=server.Shutdown(ctx);err!=nil{logger.Fatalf("Could not gracefully shutdown the server: %v\n",err)}close(done)}()logger.Println("Server is ready to handle requests at",listenAddr)iferr:=server.ListenAndServe();err!=nil&&err!=http.ErrServerClosed{logger.Fatalf("Could not listen on %s: %v\n",listenAddr,err)}<-donelogger.Println("Server stopped")}
# build stage
FROM golang:alpine AS build-env
ADD . /src
RUN cd /src && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app
# final stage
FROM centurylink/ca-certs
COPY --from=build-env /src/app /
EXPOSE 8080
ENTRYPOINT ["/app"]
version:'3'services:app:image:go-training/apprestart:alwayslogging:options:max-size:"100k"max-file:"3"labels:- "traefik.http.routers.app.rule=Host(`app.docker.localhost`)"reverse-proxy:# The official v2.0 Traefik docker imageimage:traefik:v2.0# Enables the web UI and tells Traefik to listen to dockercommand:--api.insecure=true --providers.dockerports:# The HTTP port- "8088:80"# The Web UI (enabled by --api.insecure=true)- "8080:8080"volumes:# So that Traefik can listen to the Docker events- /var/run/docker.sock:/var/run/docker.sock
可以看到 8088 port 會是入口,app.docker.localhost 會是 app 網域名稱。