golang.tmpl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # Auto-generated Dockerfile for {{.AppName}}
  2. # Generated by BYOP Engine - Golang Stack Analyzer
  3. # Multi-stage build for Go application
  4. FROM golang:{{.GoVersion}}-alpine AS builder
  5. # Set destination for COPY
  6. WORKDIR /app
  7. {{if .NeedsBuildTools}}
  8. # Install build tools if needed
  9. RUN apk add --no-cache {{.BuildTools | join " "}}
  10. {{end}}
  11. {{if .HasGoMod}}
  12. # Copy go.mod for better dependency caching
  13. COPY go.mod ./
  14. {{if .HasGoSum}}
  15. # Copy go.sum for dependency verification
  16. COPY go.sum ./
  17. {{end}}
  18. # Download dependencies
  19. RUN go mod download
  20. {{else}}
  21. # No go.mod found - using GOPATH mode or vendor
  22. {{if .HasVendor}}
  23. # Copy vendor directory
  24. COPY vendor/ ./vendor/
  25. {{end}}
  26. {{end}}
  27. # Copy the source code (excluding unnecessary files)
  28. COPY . .
  29. {{if .HasGoMod}}
  30. # Ensure dependencies are up to date
  31. RUN go mod tidy
  32. {{end}}
  33. # Build the application
  34. {{if .CGOEnabled}}
  35. RUN CGO_ENABLED=1 {{.BuildCommand}}
  36. {{else}}
  37. RUN CGO_ENABLED=0 {{.BuildCommand}}
  38. {{end}}
  39. # Runtime stage
  40. {{if .NeedsRuntimeDeps}}
  41. FROM alpine:latest
  42. # Install runtime dependencies
  43. RUN apk --no-cache add {{.RuntimeDeps | join " "}}
  44. {{else}}
  45. # Use scratch for minimal footprint (static binary)
  46. FROM scratch
  47. {{end}}
  48. {{if ne .RuntimeImage "scratch"}}
  49. # Create app directory
  50. WORKDIR /app
  51. # Create non-root user for security
  52. RUN adduser -D -s /bin/sh appuser
  53. # Copy the binary from builder
  54. COPY --from=builder /app/{{.BinaryName}} ./{{.BinaryName}}
  55. # Change ownership to non-root user
  56. RUN chown appuser:appuser /app/{{.BinaryName}} && chmod +x /app/{{.BinaryName}}
  57. # Switch to non-root user
  58. USER appuser
  59. {{else}}
  60. # Copy the binary from builder (scratch image)
  61. COPY --from=builder /app/{{.BinaryName}} /{{.BinaryName}}
  62. {{end}}
  63. # Expose port
  64. EXPOSE {{.Port}}
  65. {{if .HealthCheckEndpoint}}
  66. # Add health check
  67. HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  68. CMD wget --no-verbose --tries=1 --spider http://localhost:{{.Port}}{{.HealthCheckEndpoint}} || exit 1
  69. {{end}}
  70. # Set the command to run the application
  71. {{if ne .RuntimeImage "scratch"}}
  72. CMD ["./{{.BinaryName}}"]
  73. {{else}}
  74. CMD ["/{{.BinaryName}}"]
  75. {{end}}