Skip to content

Deploying a Beego App

Beego is a powerful, open-source web framework for Go that enables developers to build high-performance, scalable web applications and RESTful APIs with ease. With its comprehensive MVC architecture, built-in ORM (Object-Relational Mapping), routing system, and middleware support, Beego streamlines the development process and helps teams deliver robust applications quickly. The framework is particularly well-suited for microservices, REST APIs, and full-stack web applications that demand low latency and high throughput.

Deploying Beego applications on Klutch.sh provides a seamless platform for running your Go web services in production with automatic scaling, persistent storage support, and integrated monitoring. This guide covers everything you need to know about deploying Beego on Klutch.sh, including setup, configuration, database integration, and best practices for production deployments.

What is Beego?

Beego is a comprehensive web framework written in Go that combines simplicity with powerful features. It provides:

  • MVC Architecture: Structured application design with Models, Views, and Controllers for better code organization
  • Built-in ORM: Beego ORM supports multiple databases including PostgreSQL, MySQL, SQLite, and more
  • RESTful Routing: Intuitive URL routing for building REST APIs
  • Middleware Support: Pluggable middleware for authentication, logging, and request processing
  • Session Management: Built-in session handling for user authentication and state management
  • Validation Framework: Data validation and sanitization out of the box
  • Fast Performance: Compiled Go binaries provide excellent performance and low memory footprint
  • Production Ready: Used by numerous companies for mission-critical applications

Prerequisites

Before deploying a Beego application to Klutch.sh, ensure you have the following:

  • Go 1.20 or higher installed on your local machine
  • Git for version control and pushing code to GitHub
  • GitHub account for repository management
  • Klutch.sh account with project creation permissions
  • Basic Go knowledge for understanding Beego development concepts
  • Docker (optional, only if using Dockerfile deployment method)

Getting Started: Create Your First Beego Application

Step 1: Initialize Your Project

Create a new directory for your Beego application and initialize a Go module:

Terminal window
mkdir my-beego-app
cd my-beego-app
go mod init my-beego-app

Step 2: Install Beego Dependencies

Install the latest version of Beego and the Bee development tool:

Terminal window
go get github.com/beego/beego/v2@latest
go get github.com/beego/bee/v2@latest

The Bee tool provides utilities for scaffolding projects and running development servers.

Step 3: Create a Basic Beego Application

Create a main.go file with a simple HTTP server:

package main
import (
"github.com/beego/beego/v2/server/web"
"os"
)
func main() {
web.Get("/", func(ctx *web.Context) {
ctx.WriteString("Hello from Beego on Klutch.sh!")
})
// Get port from environment variable or default to 8080
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
// Start the server on all interfaces
web.Run("0.0.0.0:" + port)
}

Step 4: Test Your Application Locally

Run your Beego application locally to ensure it works correctly:

Terminal window
go run main.go

Visit http://localhost:8080 in your browser to see your application running.

Step 5: Initialize Go Modules and Create go.sum

Ensure all dependencies are properly recorded:

Terminal window
go mod tidy

This command will download all dependencies and create a go.sum file for dependency verification.


Deploying Without a Dockerfile (Using Nixpacks)

Klutch.sh uses Nixpacks to automatically detect, build, and deploy Go applications. This method requires no Dockerfile configuration—simply push your code to GitHub and let Klutch.sh handle the rest.

Prepare Your Repository

  1. Ensure your project has the following files in the root directory:

    • go.mod and go.sum (generated by go mod init and go mod tidy)
    • main.go (your application entry point)
    • Any additional source files and packages
  2. Push your Beego application to a GitHub repository:

Terminal window
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/your-username/my-beego-app.git
git push -u origin main
  1. Log in to your Klutch.sh dashboard.

  2. Create a new project by selecting your desired organization and naming your project (e.g., “My Beego API”).

  3. Create a new app within your project with the following configuration:

    • Repository: Select your Beego GitHub repository
    • Branch: Select the branch to deploy (typically main or master)
    • Traffic Type: Select HTTP (Beego serves HTTP traffic)
    • Internal Port: Enter 8080 (the default port your Beego app listens on)
    • Region: Choose the region closest to your users
    • Compute: Select appropriate compute resources based on your application’s needs
    • Instances: Set the number of instances for horizontal scaling
    • Environment Variables: Add any configuration variables your app needs (see the Environment Variables section below)
  4. Review your configuration and click “Create” to deploy. Klutch.sh will automatically:

    • Detect your Go application
    • Install dependencies using go mod download
    • Build your binary with go build -o main main.go
    • Deploy your application
  5. Monitor the deployment progress in the Klutch.sh dashboard. Once deployment is complete, your application will be available at a URL like example-app.klutch.sh.

Customizing Build and Start Commands (Nixpacks)

If you need to customize the build process or startup behavior, Klutch.sh supports Nixpacks environment variables for command customization.

For example, if your application requires a custom build step or has a different entry point, set these environment variables in the Klutch.sh dashboard:

BUILD_COMMAND=go build -ldflags="-s -w" -o bin/app main.go
START_COMMAND=./bin/app

These variables tell Nixpacks how to build and start your application. The example above creates an optimized binary in a bin directory.


Deploying With a Dockerfile

If you prefer complete control over your deployment environment, you can use a Dockerfile. Klutch.sh automatically detects and uses a Dockerfile if it exists in your repository’s root directory.

Create a Dockerfile

  1. Create a Dockerfile in your project root with a multi-stage build for optimal image size:
# Stage 1: Build the application
FROM golang:1.20-alpine AS builder
WORKDIR /app
# Copy go.mod and go.sum
COPY go.mod go.sum ./
# Download dependencies
RUN go mod download
# Copy application source code
COPY . .
# Build the binary with optimizations
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o beego-app main.go
# Stage 2: Create minimal runtime image
FROM alpine:latest
# Install ca-certificates for HTTPS requests
RUN apk --no-cache add ca-certificates
WORKDIR /app
# Copy the built binary from builder stage
COPY --from=builder /app/beego-app .
# Expose port (must match your Beego app's port)
EXPOSE 8080
# Set the default environment port variable
ENV PORT=8080
# Run the application
CMD ["./beego-app"]

This Dockerfile uses a multi-stage build to minimize the final image size by including only the compiled binary and necessary runtime dependencies.

  1. Push your code to GitHub (including the Dockerfile):
Terminal window
git add Dockerfile
git commit -m "Add Dockerfile for production deployment"
git push
  1. Log in to your Klutch.sh dashboard.

  2. Create a new project (or use an existing one).

  3. Create a new app with the following settings:

    • Repository: Select your Beego GitHub repository
    • Branch: Select your deployment branch
    • Traffic Type: Select HTTP (Beego serves HTTP traffic)
    • Internal Port: Enter 8080 (the port your Beego app listens on)
    • Region, Compute, and Instances: Configure according to your needs
    • Environment Variables: Add any required configuration variables
  4. Click “Create” to deploy. Klutch.sh will automatically:

    • Detect your Dockerfile
    • Build your Docker image
    • Deploy the containerized application to your Klutch.sh infrastructure
  5. Once deployment is complete, your application will be accessible at a URL like example-app.klutch.sh.

Advanced Dockerfile Configuration

For more complex deployments, you can customize your Dockerfile further:

# Stage 1: Build
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# Build with version information (optional)
ARG VERSION=dev
RUN CGO_ENABLED=0 GOOS=linux go build \
-ldflags="-s -w -X main.Version=${VERSION}" \
-o beego-app main.go
# Stage 2: Runtime
FROM alpine:latest
RUN apk --no-cache add ca-certificates tzdata
WORKDIR /app
COPY --from=builder /app/beego-app .
EXPOSE 8080
ENV PORT=8080
# Add health check (optional)
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/ || exit 1
CMD ["./beego-app"]

Environment Variables and Configuration

Beego applications typically require environment variables for database connections, API keys, and other configuration. Manage these securely through the Klutch.sh dashboard.

Common Environment Variables

Set these in your Klutch.sh app configuration:

PORT=8080
APP_ENV=production
LOG_LEVEL=info
DATABASE_URL=postgres://user:password@db.example.com/mydb
API_KEY=your-api-key-here
SECRET_KEY=your-secret-key-here

Reading Environment Variables in Beego

Update your main.go to read and use environment variables:

package main
import (
"github.com/beego/beego/v2/server/web"
"os"
)
func init() {
// Read configuration from environment
appEnv := os.Getenv("APP_ENV")
if appEnv != "" {
web.BConfig.RunMode = appEnv
}
logLevel := os.Getenv("LOG_LEVEL")
if logLevel != "" {
web.BConfig.Log.Level = logLevel
}
}
func main() {
web.Get("/", func(ctx *web.Context) {
ctx.WriteString("Hello from Beego on Klutch.sh!")
})
// Health check endpoint
web.Get("/health", func(ctx *web.Context) {
ctx.JSONResp(map[string]string{"status": "healthy"})
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
web.Run("0.0.0.0:" + port)
}

Database Integration

Beego includes built-in ORM support for multiple databases. This section covers PostgreSQL integration as a common example.

Setting Up PostgreSQL with Beego

First, install the PostgreSQL driver:

Terminal window
go get github.com/lib/pq

Create a database configuration file or add initialization code to your application:

package main
import (
"github.com/beego/beego/v2/client/orm"
"github.com/beego/beego/v2/server/web"
_ "github.com/lib/pq"
"os"
)
func init() {
// Register database driver
orm.RegisterDriver("postgres", orm.DRPostgres)
// Set up database connection from environment variable
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
dbURL = "postgres://user:password@localhost/mydb?sslmode=disable"
}
orm.RegisterDataBase("default", "postgres", dbURL)
}
// Example model
type User struct {
Id int
Name string
}
func (u *User) TableName() string {
return "users"
}
func main() {
web.Get("/", func(ctx *web.Context) {
ctx.WriteString("Hello from Beego on Klutch.sh!")
})
// API endpoint to fetch users
web.Get("/api/users", func(ctx *web.Context) {
o := orm.NewORM()
var users []User
o.QueryTable("users").All(&users)
ctx.JSONResp(users)
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
web.Run("0.0.0.0:" + port)
}

Set the DATABASE_URL environment variable in Klutch.sh with your PostgreSQL connection string.


Persistent Storage for Beego Applications

If your Beego application requires persistent storage (for file uploads, logs, databases, or other persistent data), Klutch.sh supports persistent volumes.

Adding Persistent Storage

  1. In the Klutch.sh dashboard, navigate to your deployed app.

  2. Find the Storage or Volumes section in the app settings.

  3. Click “Add Volume” and configure:

    • Mount Path: Enter the absolute path inside your container where the volume should be mounted (e.g., /app/uploads for file uploads or /var/log/myapp for logs)
    • Size: Select the volume size in GB (e.g., 10 GB, 50 GB, etc.)
  4. Save and redeploy your application. Klutch.sh will attach the persistent volume to your container.

  5. In your Beego application, configure file operations to use the mounted volume path:

package main
import (
"github.com/beego/beego/v2/server/web"
"os"
"path/filepath"
)
func main() {
// Get the upload directory from environment or use default
uploadDir := os.Getenv("UPLOAD_DIR")
if uploadDir == "" {
uploadDir = "/app/uploads"
}
// Ensure upload directory exists
os.MkdirAll(uploadDir, 0755)
web.Post("/upload", func(ctx *web.Context) {
file, handler, err := ctx.Request.FormFile("file")
if err != nil {
ctx.WriteString("Error retrieving file")
return
}
defer file.Close()
filePath := filepath.Join(uploadDir, handler.Filename)
f, err := os.Create(filePath)
if err != nil {
ctx.WriteString("Error saving file")
return
}
defer f.Close()
_, err = f.ReadFrom(file)
if err != nil {
ctx.WriteString("Error writing file")
return
}
ctx.WriteString("File uploaded successfully")
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
web.Run("0.0.0.0:" + port)
}

Building a RESTful API with Beego

Beego is particularly well-suited for building RESTful APIs. Here’s a complete example:

package main
import (
"github.com/beego/beego/v2/server/web"
"os"
"strconv"
)
// Article model
type Article struct {
Id int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
var articles = []Article{
{Id: 1, Title: "Getting Started with Go", Body: "Go is a powerful programming language..."},
{Id: 2, Title: "Beego Framework Tutorial", Body: "Beego provides a complete web framework..."},
}
func main() {
// GET /api/articles - List all articles
web.Get("/api/articles", func(ctx *web.Context) {
ctx.JSONResp(articles)
})
// GET /api/articles/:id - Get specific article
web.Get("/api/articles/:id", func(ctx *web.Context) {
id := ctx.Input.Param(":id")
idInt, _ := strconv.Atoi(id)
for _, article := range articles {
if article.Id == idInt {
ctx.JSONResp(article)
return
}
}
ctx.WriteString("Article not found")
})
// POST /api/articles - Create new article
web.Post("/api/articles", func(ctx *web.Context) {
var newArticle Article
ctx.BindJSON(&newArticle)
articles = append(articles, newArticle)
ctx.JSONResp(newArticle)
})
// Health check
web.Get("/health", func(ctx *web.Context) {
ctx.JSONResp(map[string]string{"status": "healthy"})
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
web.Run("0.0.0.0:" + port)
}

Middleware and Authentication

Beego supports middleware for cross-cutting concerns like authentication and logging:

package main
import (
"github.com/beego/beego/v2/server/web"
"os"
)
// Middleware for logging requests
func LoggingMiddleware(ctx *web.Context) {
web.BeeApp.AppConfig.Logger.Info("Request: " + ctx.Request.Method + " " + ctx.Request.URL.Path)
}
// Middleware for authentication
func AuthMiddleware(ctx *web.Context) {
token := ctx.Input.Header("Authorization")
if token == "" {
ctx.WriteString("Unauthorized")
return
}
// Validate token here
}
func main() {
// Register global middleware
web.InsertFilter("/*", web.BeforeRouter, LoggingMiddleware)
web.InsertFilter("/api/protected/*", web.BeforeRouter, AuthMiddleware)
web.Get("/", func(ctx *web.Context) {
ctx.WriteString("Public endpoint")
})
web.Get("/api/protected/data", func(ctx *web.Context) {
ctx.WriteString("Protected data")
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
web.Run("0.0.0.0:" + port)
}

Custom Domains

To access your Beego application on a custom domain instead of the default example-app.klutch.sh URL:

  1. In the Klutch.sh dashboard, navigate to your application settings.

  2. Find the Domains or Custom Domain section.

  3. Add your custom domain (e.g., api.mycompany.com).

  4. Update your domain’s DNS records to point to Klutch.sh:

    • Add a CNAME record pointing to your Klutch.sh app URL
    • Or add A records pointing to the IP address provided by Klutch.sh
  5. Verify the domain ownership through Klutch.sh’s verification process.

  6. Once verified, your Beego application will be accessible at your custom domain.


Monitoring and Logging

Monitor your Beego deployment through Klutch.sh’s built-in monitoring tools:

  1. In the Klutch.sh dashboard, view your application’s Logs to troubleshoot issues.

  2. Check Metrics for CPU usage, memory consumption, and request throughput.

  3. Set up Alerts to be notified of performance issues or errors.

  4. Configure Log Levels in your Beego application for appropriate verbosity:

package main
import (
"github.com/beego/beego/v2/server/web"
"os"
)
func init() {
logLevel := os.Getenv("LOG_LEVEL")
switch logLevel {
case "debug":
web.BConfig.Log.Level = "debug"
case "info":
web.BConfig.Log.Level = "info"
case "warn":
web.BConfig.Log.Level = "warn"
case "error":
web.BConfig.Log.Level = "error"
default:
web.BConfig.Log.Level = "info"
}
}
func main() {
web.Get("/", func(ctx *web.Context) {
web.BeeApp.AppConfig.Logger.Info("Home page accessed")
ctx.WriteString("Hello from Beego!")
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
web.Run("0.0.0.0:" + port)
}

Troubleshooting Common Issues

Application Fails to Build

Problem: Deployment fails during the build phase with dependency errors.

Solution:

  • Ensure your go.mod and go.sum files are up to date: go mod tidy
  • Verify all dependencies are listed in go.mod
  • Check that your Go version matches the version in your Dockerfile or Nixpacks configuration

Port Binding Errors

Problem: Your application fails with a port binding error.

Solution:

  • Ensure your Beego app reads the PORT environment variable
  • Verify the internal port in Klutch.sh configuration matches what your app listens on (typically 8080)
  • Check that no other services are binding to the same port

Database Connection Failures

Problem: Your application can’t connect to the database.

Solution:

  • Verify the DATABASE_URL environment variable is set correctly in Klutch.sh
  • Ensure your database is accessible from your Klutch.sh deployment region
  • Check database credentials and connection string format
  • Confirm your Beego application properly parses the connection string

Persistent Storage Not Found

Problem: Application can’t write to persistent storage.

Solution:

  • Verify the mount path in your Klutch.sh volume configuration
  • Create the directory in your application if it doesn’t exist: os.MkdirAll(uploadDir, 0755)
  • Check file permissions and ensure your application has write access
  • Restart your application after adding a new volume

Best Practices for Production Beego Deployments

  1. Enable HTTPS: Always use HTTPS in production. Klutch.sh provides automatic HTTPS for custom domains.

  2. Implement Health Checks: Add a /health endpoint that returns a 200 status code when healthy.

  3. Use Environment Variables: Store all configuration in environment variables, never hardcode secrets.

  4. Monitor Performance: Regularly check logs and metrics in the Klutch.sh dashboard.

  5. Optimize Binary Size: Use build flags like -ldflags="-s -w" to reduce executable size.

  6. Database Connection Pooling: Configure appropriate connection pool sizes for your database.

  7. Implement Request Logging: Log all requests for debugging and monitoring purposes.

  8. Handle Graceful Shutdown: Implement proper shutdown handlers to close database connections cleanly.

  9. Set Resource Limits: Allocate appropriate CPU and memory resources based on expected load.

  10. Version Your Application: Use Git tags and version information for tracking deployments.


Resources and Further Reading


Conclusion

Deploying Beego applications on Klutch.sh is straightforward and flexible. Whether you choose the Nixpacks deployment method for simplicity or the Docker method for complete control, Klutch.sh provides the tools and infrastructure needed for reliable, scalable production deployments. With support for environment variables, persistent storage, custom domains, and integrated monitoring, you can focus on building great applications while Klutch.sh handles the deployment and scaling.

For additional support or questions about deploying your Beego application, visit the Klutch.sh website or consult the Beego documentation.