Skip to main content

Flexible Configuration

KrakenD’s Flexible Configuration allows you to use templates, variables, and logic to build your configuration files dynamically. This is especially useful for managing multiple environments and reducing configuration duplication.

Overview

Flexible Configuration uses Go template syntax to:
  • Use variables from environment-specific files
  • Include partial configuration templates
  • Implement loops and conditional logic
  • Generate the final krakend.json from templates

Template File

The main template file is located at:
config/krakend/krakend-flexible-config.tmpl

Example Template

{
  "$schema": "https://www.krakend.io/schema/v3.json",
  "version": 3,
  "name": "Sample Gateway",
  "port": {{ .env.port }},
  "timeout": "30s",
  "cache_ttl": "300s",
  "extra_config": {{ include "extra_config.tmpl" }},
  "endpoints": [
    {{ template "sample_template.tmpl" . }},
    
    {{ range $idx, $endpoint := .loop_example.dummy }}
      {{ if $idx }},{{ end }}
      {
        "endpoint": "{{ $endpoint }}",
        "backend": [
          {
            "host": ["http://localhost:8080"],
            "url_pattern": "/__debug{{ $endpoint }}"
          }
        ]
      }
    {{ end }}
  ]
}

Enabling Flexible Configuration

Set the FC_ENABLE environment variable to enable flexible configuration:
export FC_ENABLE=1
When enabled, KrakenD will:
  1. Load the template file instead of krakend.json
  2. Process all template directives
  3. Generate the final configuration in memory

Settings Directory Structure

Environment-specific settings are stored in separate directories:
config/krakend/
├── krakend.json                    # Compiled static config
├── krakend-flexible-config.tmpl    # Main template
├── settings/
│   ├── dev/
│   │   └── env.json               # Development variables
│   └── prod/
│       └── env.json               # Production variables
└── partials/
    └── extra_config.tmpl          # Shared template partial

Variables and Environment Settings

Using Variables

Variables from env.json are accessible via the .env object:
"port": {{ .env.port }},
"name": "{{ .env.name }}"

Development Settings

From settings/dev/env.json:
{
  "port": 8080,
  "host_member": "http://member",
  "host_logistics": "http://logistics",
  "host_payment": "http://payment",
  "host_order": "http://order",
  "host_case": "http://case",
  "host_channel": "http://channel",
  "host_ticket": "http://ticket",
  "security": "https://keycloak/auth/realms/default/protocol/openid-connect/certs",
  "name": "DEV"
}

Production Settings

From settings/prod/env.json:
{
  "port": 8080,
  "host_member": "http://member.production-host.com",
  "host_logistics": "http://logistics.production-host.com",
  "host_payment": "http://payment.production-host.com",
  "host_order": "http://order.production-host.com",
  "host_case": "http://case.production-host.com",
  "host_channel": "http://channel.production-host.com",
  "host_ticket": "http://ticket.production-host.com",
  "security": "https://keycloak/auth/realms/default/protocol/openid-connect/certs",
  "name": "PROD"
}

Partials and Templates

Including Partials

Use include to insert content from partial files:
"extra_config": {{ include "extra_config.tmpl" }}

Example Partial: extra_config.tmpl

From partials/extra_config.tmpl:
{
  "security/cors": {
    "allow_origins": ["*"],
    "allow_methods": ["POST", "GET"],
    "allow_headers": ["Origin", "Authorization", "Content-Type"],
    "expose_headers": ["Content-Length"],
    "max_age": "12h"
  },
  "telemetry/logging": {
    "level": "DEBUG",
    "prefix": "[KRAKEND]",
    "syslog": false,
    "stdout": true
  },
  "telemetry/metrics": {
    "collection_time": "60s",
    "listen_address": ":8090"
  },
  "telemetry/opencensus": {
    "sample_rate": 100,
    "reporting_period": 1,
    "enabled_layers": {
      "backend": true,
      "router": true
    },
    "exporters": {
      "jaeger": {
        "endpoint": "http://jaeger:14268/api/traces",
        "serviceName": "krakend"
      }
    }
  }
}

Using Templates

Use template to invoke named templates:
{{ template "sample_template.tmpl" . }}
The . passes the current context (including variables) to the template.

Logic and Iterations

Loops

Iterate over arrays or objects:
{{ range $idx, $endpoint := .loop_example.dummy }}
  {{ if $idx }},{{ end }}
  {
    "endpoint": "{{ $endpoint }}",
    "backend": [
      {
        "host": ["http://localhost:8080"],
        "url_pattern": "/__debug{{ $endpoint }}"
      }
    ]
  }
{{ end }}
Features:
  • range iterates over .loop_example.dummy array
  • $idx is the index (0-based)
  • {{ if $idx }},{{ end }} adds commas between items (not before first item)
  • {{ $endpoint }} is the current array element

Conditionals

Use if statements for conditional logic:
{{ if .env.enable_feature }}
  {
    "endpoint": "/feature",
    "backend": [{
      "url_pattern": "/feature"
    }]
  }
{{ end }}

Comparisons

{{ if eq .env.environment "production" }}
  "timeout": "5000ms"
{{ else }}
  "timeout": "3000ms"
{{ end }}

Compiling Templates

The playground includes a Make command to compile templates and save the output:
make compile-flexible-config
This command:
  1. Processes the template file
  2. Resolves all variables and includes
  3. Saves the compiled configuration to a file
You can inspect the compiled output to see how KrakenD builds the final configuration.

Template Functions

Available Functions

FunctionDescriptionExample
includeInclude a partial file{{ include "partial.tmpl" }}
templateInvoke a named template{{ template "tmpl.tmpl" . }}
rangeIterate over collection{{ range .items }}...{{ end }}
ifConditional logic{{ if .condition }}...{{ end }}
eqEquality comparison{{ if eq .env "prod" }}
neNot equal{{ if ne .env "dev" }}
andLogical AND{{ if and .a .b }}
orLogical OR{{ if or .a .b }}

Best Practices

1. Organize by Environment

Keep environment-specific values in settings/ directories:
settings/
├── dev/
│   └── env.json
├── staging/
│   └── env.json
└── prod/
    └── env.json

2. Use Partials for Reusability

Extract common configuration blocks into partials:
partials/
├── extra_config.tmpl
├── security.tmpl
├── telemetry.tmpl
└── endpoints/
    ├── public.tmpl
    └── private.tmpl

3. Document Template Variables

Add comments to your env.json files explaining variable purposes.

4. Test Compiled Output

Always compile and validate your templates before deploying:
make compile-flexible-config
# Inspect the output
# Test with: krakend check -c compiled-config.json

Switching Environments

To switch between development and production:
  1. Set the FC_SETTINGS environment variable:
    export FC_SETTINGS="settings/prod"
    
  2. Or specify it when starting KrakenD:
    FC_SETTINGS="settings/prod" krakend run -c krakend-flexible-config.tmpl
    

Next Steps

Build docs developers (and LLMs) love