Docker

通常微服务情景时,或按服务交付时,我们使用docker部署。

dockerfile
  1. # =============== build and run ===============
  2. # build: docker build -t go-service:latest .
  3. # run: docker run -dit go-service:latest
  4. # =============== build stage ===============
  5. FROM golang:1.16.5-buster AS build
  6. # env
  7. ENV GOOS=linux \
  8. GOARCH=amd64 \
  9. CGO_ENABLED=0 \
  10. GO111MODULE=on \
  11. GOPROXY="https://goproxy.cn,direct"
  12. # dependent
  13. WORKDIR /app
  14. COPY go.* ./
  15. RUN go mod download -x all
  16. # build
  17. COPY . ./
  18. # ldflags:
  19. # -s: disable symbol table
  20. # -w: disable DWARF generation
  21. # run "go tool link -help" to get the full list of ldflags
  22. RUN go env && go build -ldflags "-s -w" -o go-service -v ./main.go
  23. # =============== final stage ===============
  24. FROM alpine:latest AS final
  25. # resources
  26. WORKDIR /app
  27. COPY --from=build /app/go-service ./
  28. COPY --from=build /app/conf/base.toml ./conf/base.toml
  29. COPY --from=build /app/conf/prod ./conf/prod
  30. # set time zone
  31. RUN apk add --no-cache tzdata
  32. # expose
  33. EXPOSE 80
  34. ENTRYPOINT ["env","GO_ENV=prod","/app/go-service", "-other", "flags"]

nginx

当我们主机部署时,单机多域名服务时,就加一层nginx做转发。

http

  1. server {
  2. listen 80;
  3. server_name test.com;
  4. root /rootdir;
  5. location ~ /services{
  6. #go 服务器可以指定到其他的机器上,这里设定本机服务器的6666端口
  7. proxy_pass http://127.0.0.1:6666;
  8. #Proxy Settings
  9. proxy_redirect off;
  10. proxy_set_header Host $host;
  11. proxy_set_header X-Real-IP $remote_addr;
  12. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  13. #proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
  14. #proxy_max_temp_file_size 0;
  15. #proxy_connect_timeout 90;
  16. #proxy_send_timeout 90;
  17. #proxy_read_timeout 90;
  18. #proxy_buffer_size 4k;
  19. #proxy_buffers 4 32k;
  20. #proxy_busy_buffers_size 64k;
  21. #proxy_temp_file_write_size 64k;
  22. }
  23. }

websocket

  1. {
  2. http{
  3. map $http_upgrade $connection_upgrade {
  4. default upgrade;
  5. '' close;
  6. }
  7. }
  8. // other...
  9. server {
  10. listen 80;
  11. server_name test.com;
  12. root /rootdir;
  13. location ~ /services{
  14. proxy_pass http://127.0.0.1:8888;
  15. #Proxy Settings
  16. proxy_redirect off;
  17. proxy_set_header Host $host;
  18. proxy_set_header X-Real-IP $remote_addr;
  19. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  20. # websocket
  21. proxy_http_version 1.1;
  22. proxy_set_header Upgrade $http_upgrade;
  23. proxy_set_header Connection $connection_upgrade;
  24. proxy_read_timeout 300s; #keeplive
  25. }
  26. }
  27. }