Back to Insights
VoIP Engineering

Kamailio Basic Configuration: Build a Working SIP Proxy Step by Step

Telephony Engineering Team
7 min read
Kamailio Basic Configuration: Build a Working SIP Proxy Step by Step

Kamailio is a high-performance open-source SIP server. It does not process audio. It routes SIP signaling, which makes it ideal for load balancing, registration at scale, and securing the edge of a voice platform.

This tutorial installs Kamailio, explains how its configuration file is organized, and builds a small, working proxy that distributes calls across two media servers and fails over if one stops answering. The example is intentionally minimal so you can understand every line.

What you will build

                              +--> FreeSWITCH A (10.0.0.11)
 Caller / trunk --> Kamailio -|
                              +--> FreeSWITCH B (10.0.0.12)

Kamailio will:

  • Reject malformed SIP messages and runaway request loops
  • Answer SIP keep-alive pings
  • Pick one of two media servers for each new call (round-robin)
  • Keep itself in the call path for later requests such as BYE
  • Retry on the other server if the first fails
  • Probe both servers with SIP OPTIONS, and stop sending calls to a dead one

Install Kamailio on Debian or Ubuntu

sudo apt update
sudo apt install -y kamailio

Optional module packages are available separately, for example for MySQL, TLS, and WebSockets (such as kamailio-mysql-modules, kamailio-tls-modules, and kamailio-websocket-modules). You do not need them for this tutorial.

Useful commands and files:

ItemPurpose
/etc/kamailio/kamailio.cfgMain configuration
kamailio -c -f /etc/kamailio/kamailio.cfgCheck the configuration for errors
systemctl restart kamailioRestart the service
kamcmdCommand-line tool for runtime control
journalctl -u kamailioView logs

The package ships a full-featured default configuration. Back it up, because we will replace it with a minimal one:

sudo cp /etc/kamailio/kamailio.cfg /etc/kamailio/kamailio.cfg.orig

How kamailio.cfg is organized

The file has three kinds of content:

  1. Global parameters: ports to listen on, number of worker processes, logging.
  2. Modules: loadmodule lines load features, and modparam lines configure them.
  3. Routing blocks: scripts that run as messages arrive.
BlockWhen it runs
request_routeFor every incoming SIP request. This is the entry point
route[NAME]Your own reusable subroutines
failure_route[NAME]When a relayed request fails, allowing retry
reply_route / onreply_routeWhen replies arrive
branch_route[NAME]Per outgoing branch of a request
event_route[NAME]On internal events

Kamailio executes the script top to bottom for each request. exit stops processing. Learning to read this flow is most of the work.

Step 1: define the media servers

Create the destination list used by the dispatcher module. Each line is set-id destination flags priority:

# /etc/kamailio/dispatcher.list
1 sip:10.0.0.11:5060 0 0
1 sip:10.0.0.12:5060 0 0

Both servers are in set 1. Change the addresses to your own FreeSWITCH or other SIP servers.

Step 2: write a minimal configuration

Replace the contents of /etc/kamailio/kamailio.cfg with the following.

#!KAMAILIO

####### Global parameters #########
debug=2
log_stderror=no
fork=yes
children=4
listen=udp:0.0.0.0:5060
listen=tcp:0.0.0.0:5060

####### Modules #########
loadmodule "kex.so"
loadmodule "tm.so"
loadmodule "tmx.so"
loadmodule "sl.so"
loadmodule "rr.so"
loadmodule "pv.so"
loadmodule "maxfwd.so"
loadmodule "siputils.so"
loadmodule "xlog.so"
loadmodule "sanity.so"
loadmodule "ctl.so"
loadmodule "dispatcher.so"

modparam("ctl", "binrpc", "unix:/var/run/kamailio/kamailio_ctl")
modparam("dispatcher", "list_file", "/etc/kamailio/dispatcher.list")
modparam("dispatcher", "ds_ping_method", "OPTIONS")
modparam("dispatcher", "ds_ping_interval", 10)
modparam("dispatcher", "ds_probing_mode", 1)

####### Main routing logic #########
request_route {
    # Basic hygiene
    if (!mf_process_maxfwd_header("10")) {
        sl_send_reply("483", "Too Many Hops");
        exit;
    }
    if (!sanity_check("17895", "7")) {
        xlog("L_WARN", "Malformed SIP message from $si:$sp\n");
        exit;
    }

    # CANCEL processing
    if (is_method("CANCEL")) {
        if (t_check_trans()) {
            route(RELAY);
        }
        exit;
    }

    # Handle retransmissions
    if (!is_method("ACK")) {
        if (t_precheck_trans()) {
            t_check_trans();
            exit;
        }
        t_check_trans();
    }

    # Requests inside an existing call (BYE, re-INVITE, ACK...)
    if (has_totag()) {
        if (loose_route()) {
            route(RELAY);
        } else {
            if (is_method("ACK")) {
                if (t_check_trans()) {
                    route(RELAY);
                }
                exit;
            }
            sl_send_reply("404", "Not here");
        }
        exit;
    }

    # Answer keep-alive pings sent to us
    if (is_method("OPTIONS") && uri == myself) {
        sl_send_reply("200", "OK");
        exit;
    }

    # In this lab only INVITE starts a call
    if (!is_method("INVITE")) {
        sl_send_reply("405", "Method Not Allowed");
        exit;
    }

    # Stay in the signaling path for the rest of the call
    record_route();

    # Pick a media server: set 1, algorithm 4 = round-robin
    if (!ds_select_dst("1", "4")) {
        send_reply("503", "No media server available");
        exit;
    }

    t_on_failure("FAILOVER");
    route(RELAY);
    exit;
}

route[RELAY] {
    if (!t_relay()) {
        sl_reply_error();
    }
    exit;
}

failure_route[FAILOVER] {
    if (t_is_canceled()) {
        exit;
    }
    # Retry on the next server for server errors or timeouts
    if (t_check_status("(500)|(503)") || (t_branch_timeout() && !t_branch_replied())) {
        if (ds_next_dst()) {
            t_on_failure("FAILOVER");
            t_relay();
            exit;
        }
    }
}

This is a learning skeleton. It has no authentication, no rate limiting, and no TLS, so do not expose it to the internet as-is.

Step 3: check and start

Always validate before restarting:

sudo kamailio -c -f /etc/kamailio/kamailio.cfg
sudo systemctl restart kamailio
sudo systemctl status kamailio

A valid configuration reports success. If not, the message points to the line with the problem.

Step 4: test it

  1. See the health of your servers:

    sudo kamcmd dispatcher.list
    

    Both destinations should show as active. If a media server is down, the OPTIONS probes will mark it inactive.

  2. Send a test call. From a test user agent, or with a tool such as SIPp (sipp -sn uac KAMAILIO_IP:5060), send an INVITE to Kamailio.

  3. Watch the signaling. Use sngrep or tcpdump to confirm that INVITEs alternate between the two servers, and that a stopped server stops receiving calls.

How the pieces work

  • record_route() adds Kamailio's address to the route set, so later requests like BYE come back through it. Without it, the call would bypass the proxy after setup.
  • loose_route() follows that route set for requests inside a call.
  • ds_select_dst chooses a destination from the dispatcher list, and ds_next_dst picks the next one on failure.
  • t_relay() forwards the request statefully, so Kamailio can handle retransmissions and retries.
  • The dispatcher's OPTIONS probes remove unhealthy servers from rotation automatically.

Next steps toward production

A real edge needs more than this tutorial covers:

  • Authentication and access control. Authenticate users, and allow-list carrier IP addresses.
  • Rate limiting and flood protection. Stop scanning and registration floods.
  • TLS for signaling.
  • Topology hiding if you must hide internal addresses.
  • A media proxy such as rtpengine for NAT traversal and SRTP. See open-source SBC with Kamailio and rtpengine.
  • Registration and location services if you serve phones directly.
  • Monitoring and SIP capture with HEP and Homer. See VoIP monitoring.
  • A tested high-availability design for Kamailio itself. See Kamailio dispatcher load balancing configuration.

For a deeper comparison with other platforms, read FreeSWITCH vs Asterisk vs Kamailio and OpenSIPS vs Kamailio. To understand the role an edge like this plays, see what a session border controller does.

Common problems

ProblemLikely causeFix
Kamailio will not startSyntax error or missing moduleRun kamailio -c -f ... and read the message
kamcmd cannot connectctl module not loaded or wrong socket pathCheck the ctl modparam and the socket directory
Calls fail with 503No active destinationsCheck kamcmd dispatcher.list and media server reachability
BYE never reaches Kamailiorecord_route() not calledAdd it before relaying the INVITE
Calls drop or loopRequest sent back to Kamailio itselfCheck destination addresses and maxfwd

Frequently asked questions

What is Kamailio used for?

It is used as a SIP proxy, registrar, load balancer, and edge router. Many voice platforms put it in front of media servers such as FreeSWITCH or Asterisk.

Does Kamailio handle audio?

No. Kamailio routes signaling only. To relay or transcode media, pair it with a media proxy such as rtpengine or use a media server behind it.

Kamailio or OpenSIPS?

They are closely related and fill similar roles. Choose based on team experience, available modules, and community support.

Is the default configuration good enough?

The stock configuration is a solid starting point for learning and testing, but production use needs security hardening, monitoring, and capacity planning.

References


Need a production-grade Kamailio edge or load balancer? Our Kamailio engineering team designs, hardens, and operates SIP edges for platforms and carriers.

Discussion

0

Join the conversation

Sign in with your preferred account to comment, reply, and keep the discussion useful for other engineers.

Takes a few seconds. No separate password required.

C

Controva LLC

Engineering Team

We build digital empires that scale. Specializing in high-performance web architecture, AI automation, and headless commerce.

Work with us

Share this article