← Back to kataras/iris

How to Deploy & Use kataras/iris

Deployment and Usage Guide for Iris Web Framework

This guide provides comprehensive instructions for deploying and using the Iris Web Framework, a fast and modern HTTP/2 Go web framework.

1. Prerequisites

Before you begin, ensure you have the following installed:

2. Installation

To start a new project with Iris, you typically initialize a Go module and then add Iris as a dependency.

  1. Create a new Go module (if starting a new project):

    mkdir my-iris-app
    cd my-iris-app
    go mod init my-iris-app
    

    Replace my-iris-app with your desired project name.

  2. Add Iris to your project:

    go get github.com/kataras/iris/v12@latest
    

    This command fetches the latest stable version of Iris (v12.x.x) and adds it to your go.mod file.

3. Configuration

Iris applications are configured programmatically within your Go code. There are no external configuration files by default, though you can integrate them using standard Go practices (e.g., viper, godotenv).

The iris.Application struct has a config field, which holds various configuration options. You can customize these options when creating or initializing your Iris application.

Example Configuration:

package main

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/recover"
	"time"
)

func main() {
	app := iris.New()

	// Configure logging level
	app.Logger().SetLevel("debug") // Can be "info", "warn", "error", "debug"

	// Add middleware
	app.Use(recover.New()) // Recover from panics

	// Configure server options
	app.Listen(":8080", iris.WithConfiguration(iris.Configuration{
		DisableStartupLog:              false, // Enable or disable the startup message
		EnableOptimizations:            true,  // Enable various performance optimizations
		TimeFormat:                     "2006-01-02 15:04:05",
		RemoteAddrHeaders:              []string{"X-Forwarded-For", "X-Real-IP"}, // Headers to check for client IP
		EnableRemoteAddrProxy:          true, // Trust remote address headers
		DisablePathCorrection:          false, // Auto-correct paths like /foo/ to /foo
		EnablePathEscape:               true,  // Escape path parameters
		FireMethodNotAllowed:           true,  // Send 405 Method Not Allowed instead of 404
		DisableBodyConsumptionOnUnmarshal: true, // Prevent body consumption on unmarshal
		// ... many more options
	}))
}

Key Configuration Areas:

  • Logger: app.Logger().SetLevel("debug") controls the verbosity of Iris's internal logging.
  • Middleware: app.Use() and app.Done() register global middleware.
  • Server Options: Passed via iris.WithConfiguration() to app.Listen(). These govern server behavior like logging, error handling, and performance optimizations.
  • I18n: The app.I18n field allows for internationalization and localization. You load language files using Load or LoadAssets.
  • View Engines: Configured via app.RegisterView().

4. Build & Run

Development

For local development, you typically run your Go application directly.

  1. Create your main application file (e.g., main.go):

    package main
    
    import "github.com/kataras/iris/v12"
    
    func main() {
      app := iris.New()
      app.Use(iris.Compression) // Example middleware
    
      app.Get("/", func(ctx iris.Context) {
        ctx.HTML("<h1>Hello from Iris!</h1>")
      })
    
      app.Listen(":8080") // Listen on port 8080
    }
    
  2. Run the application:

    go run main.go
    

    Your application will start and listen on http://localhost:8080.

Production

For production, it's best practice to build a compiled binary.

  1. Build the application:

    go build -o my-iris-app .
    

    This command compiles your application into an executable named my-iris-app (or my-iris-app.exe on Windows).

  2. Run the compiled binary:

    ./my-iris-app
    

    For long-running processes in production, consider using process managers like systemd, Supervisor, or containerization (Docker).

5. Deployment

Iris applications are Go binaries, making them highly portable.

Containerization (Docker)

Docker is an excellent choice for deploying Go applications.

  1. Create a Dockerfile in your project root:

    # Stage 1: Build the application
    FROM golang:1.20-alpine AS builder
    
    WORKDIR /app
    
    COPY go.mod go.sum ./
    RUN go mod download
    
    COPY . .
    RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o my-iris-app .
    
    # Stage 2: Run the application
    FROM alpine:latest
    
    WORKDIR /root/
    
    COPY --from=builder /app/my-iris-app .
    
    EXPOSE 8080
    
    CMD ["./my-iris-app"]
    
  2. Build the Docker image:

    docker build -t my-iris-app:latest .
    
  3. Run the Docker container:

    docker run -p 80:8080 my-iris-app:latest
    

    This maps port 80 on your host to port 8080 inside the container.

Cloud Platforms

  • Heroku: Deploy your Docker image or use Heroku's Go buildpack.

  • Google Cloud Run / AWS Fargate / Azure Container Instances: Ideal for serverless container deployment. Push your Docker image to a container registry (e.g., Google Container Registry, AWS ECR) and deploy.

  • Kubernetes: For scalable and robust deployments, deploy your Docker image to a Kubernetes cluster.

  • Virtual Private Servers (VPS) / Bare Metal: Copy your compiled binary to the server and run it, ideally managed by systemd or Supervisor.

    Example systemd service file (/etc/systemd/system/my-iris-app.service):

    [Unit]
    Description=My Iris Application
    After=network.target
    
    [Service]
    ExecStart=/path/to/your/my-iris-app
    WorkingDirectory=/path/to/your/
    Restart=always
    User=youruser
    Group=yourgroup
    Environment=PORT=8080
    
    [Install]
    WantedBy=multi-user.target
    

    Then:

    sudo systemctl daemon-reload
    sudo systemctl enable my-iris-app
    sudo systemctl start my-iris-app
    

6. Troubleshooting

  • "Address already in use" error:
    • Cause: Another process is already listening on the port your Iris app is trying to use (e.g., 8080).
    • Solution: Change the port in app.Listen(":YOUR_PORT") or stop the conflicting process. On Linux, you can find processes using a port with sudo lsof -i :8080.
  • "Go command not found":
    • Cause: Go is not installed or not in your system's PATH.
    • Solution: Install Go and ensure your GOPATH/bin directory is included in your system's PATH environment variable.
  • go mod download or go get errors:
    • Cause: Network issues, incorrect module path, or Go proxy problems.
    • Solution: Check your internet connection. Ensure the module path github.com/kataras/iris/v12 is correct. Try clearing the Go module cache (go clean -modcache).
  • 404 Not Found for routes you've defined:
    • Cause: Incorrect route path, HTTP method mismatch (e.g., expecting GET but defined POST), or middleware blocking the request.
    • Solution: Double-check your app.Get(), app.Post(), etc., calls. Ensure the path exactly matches what you're requesting. Temporarily remove middleware to isolate the issue.
  • Application crashes with a panic:
    • Cause: Unhandled runtime error in your handler code.
    • Solution: Use the recover.New() middleware (app.Use(recover.New())) to gracefully handle panics and return a 500 Internal Server Error. Check your application logs for stack traces to pinpoint the exact cause.
  • Static files not serving:
    • Cause: Incorrect path in app.HandleDir(), wrong directory structure, or permissions issues.
    • Solution: Verify the path provided to app.HandleDir() points to the correct directory containing your static assets. Ensure the application has read permissions for the static files.
  • HTTP/2 Push not working:
    • Cause: Requires HTTPS (TLS) and specific server configuration.
    • Solution: Ensure your Iris application is listening with TLS (e.g., app.ListenTLS("localhost:443", "server.crt", "server.key")). Refer to Iris examples for HTTP/2 Push configuration.