# WebRTC Calls Work on Wi-Fi but Fail on Mobile Networks? Set Up Your Own TURN Server with Coturn

> **Stack:** Ubuntu 24.04, Coturn, Node.js, WebRTC, VPS

A WebRTC application can work perfectly on a local Wi-Fi network and still fail when users connect from mobile networks or different internet providers.

One possible cause is NAT traversal.

A device behind a router or mobile carrier's NAT may not be reachable through the network path selected by WebRTC. STUN helps discover the public-facing address, but it cannot guarantee that two devices can establish a direct connection.

TURN solves this by relaying traffic through a server that both clients can reach.

Instead of depending entirely on a third-party TURN provider, you can run your own TURN server on a VPS using Coturn.

This guide covers the server setup, authentication, firewall configuration, Node.js integration and testing.

## 1\. Understand the problem

WebRTC uses ICE (Interactive Connectivity Establishment) to find a working network path between two peers.

During connection establishment, ICE gathers different types of candidates:

| Candidate | Purpose |
| --- | --- |
| Host | Local network address |
| Server reflexive (srflx) | Public-facing address discovered using STUN |
| Relay | Address allocated by a TURN server |

STUN helps discover an address. TURN provides a relay when a direct connection cannot be established.

For example:

-   User A connects through home Wi-Fi.
    
-   User B connects through a mobile network.
    
-   Their NAT or firewall configurations prevent a direct connection.
    
-   ICE cannot establish a usable direct candidate pair.
    
-   Both peers can use a TURN server as an alternative network path.
    

TURN forwards the traffic between the peers. It does not transcode the audio or video.

### How ICE chooses a connection

![Mermaid Diagram](https://mermaid.ink/img/pako:eNp1kU1PwzAMhv-K8Tk9IHHqAbR1H-zADvsAoYaDl3o0WppUaWCUsf-O0o5NSHC09bx-X9sHVK5gTHFr3F6V5AOsRtICAAxyicsQO0-8WawyUM5aVkE7K_EFkuQWhrnEKYWSPcyyMSiyhS4ocCPxpR8y7Lgsl7h4sz10mvKuQwuqZLW70FlHjw4SM7JAUGjPKkBNoYS987s7iceeHEXyS-Jz9PqCcczKJsInzTkL1KT92eFHN3dRNsklrhuG1XoxB8-G2r92mHSppheLjuTiP49xx9_nEk-Hq7jQ9Pt8PTntSRRYsa9IF5geMJRcxY8UvKU3E1D0nUfymjaGm8hsnQ0TqrRpMcWE6tpw0rRN4ErA0Gi7eyC17OqJs0FAjP7qGNYziQIWbuOCE3DP5p2DViRg4DUZAQ3ZJmnY6y2KzmSpP2OW65v6A49HgZvXzBnnMcWrfakD4_EbwVq5ZA?type=png)

This is why having a working STUN server alone is not enough for reliable WebRTC connectivity.

Reference: [MDN — Introduction to WebRTC protocols](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols).

## 2\. What we are going to build

We will use:

-   An Ubuntu VPS with a public IPv4 address.
    
-   Coturn as the TURN server.
    
-   A domain such as `turn.example.com`.
    
-   Let's Encrypt for the TLS certificate.
    
-   Node.js to generate temporary TURN credentials.
    

### Network architecture

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqF0MFqwkAQBuBXmc55Qyn0FEQwtqJQixi1B7eHSZyYwc1u2Kxaq757SWp76KXHGb6ff5gz5m7DGGNh3DEvyQd4mWsLADBYa5wxexj0Mn_fH7uK4U2ikWh8_xbJj0g6MXWZGAbL4ej87lct1hqHLuy97dRqlkK9z4zkMJl16FYHvSjqXzQ-iec8wGT4DDWFsgsdS7ZABxJDmWGNF0j-pBbL-St4NnSC4KkoJG_V4nboPwoVVuwrkg3GZwwlV-1LNlzQ3gRU35sVeWnbm9YUzoYRVWJOGGNEdW04ak5N4EpBYsTuppSn3TxyNijQmPLWMSwnGhXMXeaCUzBmc-AgOSkYeCGjoCHbRA17KVB1Jal8trc8PNYfeL0qzLZDZ5zHGO-OpQTG6xcIWZGP?type=png)

When a direct connection is available, WebRTC can use it. Otherwise, both peers can use the TURN server to relay traffic.

The TURN server is separate from your application signaling server. Your application still needs signaling to exchange SDP offers, answers and ICE candidates.

## 3\. Prepare the VPS

For this example, use an Ubuntu 24.04 VPS.

You need:

-   A public IPv4 address.
    
-   Root or sudo access.
    
-   A domain or subdomain.
    
-   Access to the VPS firewall.
    

Create an A record:

```text
Type: A
Name: turn
Value: YOUR_VPS_PUBLIC_IP
```

Verify DNS:

```bash
dig +short turn.example.com
```

It should return your VPS public IP.

## 4\. Install Coturn

Connect to your VPS:

```bash
ssh root@YOUR_VPS_IP
```

Update the packages:

```bash
sudo apt update
sudo apt upgrade -y
```

Install Coturn and Certbot:

```bash
sudo apt install coturn certbot -y
```

On Ubuntu package installations, check whether Coturn is enabled in the package configuration:

```bash
sudo nano /etc/default/coturn
```

Set:

```toml
TURNSERVER_ENABLED=1
```

Then enable and start the service:

```bash
sudo systemctl enable --now coturn
```

We will configure Coturn next.

## 5\. Generate a TURN authentication secret

Do not run a public TURN server without authentication.

An unauthenticated TURN server can be abused as an open relay, resulting in unexpected bandwidth costs and potential abuse.

Coturn supports time-limited credentials through its TURN REST authentication mechanism.

Generate a shared secret:

```bash
openssl rand -hex 32
```

Save the output securely.

```text
TURN_SHARED_SECRET=replace_with_generated_secret
```

You will use this same secret in:

1.  The Coturn configuration.
    
2.  Your Node.js backend environment.
    

Never expose this shared secret in frontend JavaScript.

## 6\. Obtain a TLS certificate

Use Let's Encrypt to issue a certificate for your TURN domain.

Make sure TCP port 80 is reachable from the internet and not occupied by another service when using the standalone challenge.

Run:

```bash
sudo certbot certonly --standalone -d turn.example.com
```

The certificate files will be available under:

```text
/etc/letsencrypt/live/turn.example.com/
```

Coturn normally runs as an unprivileged system user. Verify its service account:

```bash
sudo systemctl show coturn -p User -p Group
```

On the Ubuntu package used in this example, the account is `turnserver`.

Copy the certificate and private key into a directory readable by that service account:

```bash
sudo install -d \
  -o root -g turnserver -m 750 \
  /etc/coturn/certs

sudo install \
  -o root -g turnserver -m 0640 \
  /etc/letsencrypt/live/turn.example.com/fullchain.pem \
  /etc/coturn/certs/fullchain.pem

sudo install \
  -o root -g turnserver -m 0640 \
  /etc/letsencrypt/live/turn.example.com/privkey.pem \
  /etc/coturn/certs/privkey.pem
```

If your Coturn service runs under a different group, use that group instead.

### Keep certificates working after renewal

Let's Encrypt renews certificates by creating new files. A one-time copy is not enough.

Create a deployment hook:

```bash
sudo nano /etc/letsencrypt/renewal-hooks/deploy/coturn
```

Add:

```bash
#!/bin/sh

set -eu

if [ "${RENEWED_LINEAGE:-}" != \
  "/etc/letsencrypt/live/turn.example.com" ]; then
  exit 0
fi

install -o root -g turnserver -m 0640 \
  "$RENEWED_LINEAGE/fullchain.pem" \
  /etc/coturn/certs/fullchain.pem

install -o root -g turnserver -m 0640 \
  "$RENEWED_LINEAGE/privkey.pem" \
  /etc/coturn/certs/privkey.pem

systemctl restart coturn
```

Make it executable:

```bash
sudo chmod 750 /etc/letsencrypt/renewal-hooks/deploy/coturn
```

Replace `turn.example.com` and the service group if necessary.

## 7\. Configure Coturn

Open the configuration file:

```bash
sudo nano /etc/turnserver.conf
```

Use this configuration:

```toml
# Listening ports
listening-port=3478
tls-listening-port=5349

# Authentication
fingerprint
use-auth-secret
static-auth-secret=YOUR_GENERATED_SECRET

# Domain
realm=turn.example.com

# Relay port range
min-port=49160
max-port=49999

# TLS certificates
cert=/etc/coturn/certs/fullchain.pem
pkey=/etc/coturn/certs/privkey.pem

# Basic peer restrictions
no-loopback-peers
no-multicast-peers

# Block private and non-public IPv4 destinations
denied-peer-ip=0.0.0.0-0.255.255.255
denied-peer-ip=10.0.0.0-10.255.255.255
denied-peer-ip=100.64.0.0-100.127.255.255
denied-peer-ip=127.0.0.0-127.255.255.255
denied-peer-ip=169.254.0.0-169.254.255.255
denied-peer-ip=172.16.0.0-172.31.255.255
denied-peer-ip=192.168.0.0-192.168.255.255
```

Replace `YOUR_GENERATED_SECRET` with the secret generated earlier.

The private-address restrictions help prevent TURN users from relaying traffic to internal services reachable from the VPS. Adjust them only when your application intentionally supports private peer destinations. Review IPv6 peer restrictions separately if your server supports IPv6.

A few important configuration details:

-   `3478` accepts standard TURN connections over UDP and TCP.
    
-   `5349` accepts TURN over TLS.
    
-   `49160-49999` defines the relay port range.
    
-   `use-auth-secret` enables Coturn's time-limited credential mechanism.
    
-   `static-auth-secret` must match the secret in your backend.
    
-   `cert` and `pkey` provide the TLS certificate and private key.
    

Coturn automatically enables its long-term credential mechanism internally when `use-auth-secret` is enabled.

The configuration uses standard Coturn options documented in its [official configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf).

## 8\. Open the firewall ports

TURN needs more than just port 3478.

Open the required ports:

```bash
sudo ufw allow 3478/udp
sudo ufw allow 3478/tcp

sudo ufw allow 5349/tcp

sudo ufw allow 49160:49999/udp

sudo ufw allow 80/tcp
```

Keep your actual SSH port allowed before enabling UFW.

You must also open the same required ports in your VPS provider's firewall or security group.

| Port | Protocol | Purpose |
| --- | --- | --- |
| 3478 | UDP | Standard TURN |
| 3478 | TCP | TURN over TCP |
| 5349 | TCP | TURN over TLS |
| 49160–49999 | UDP | Media relay ports |
| 80 | TCP | Certificate issuance and renewal |

The relay range is important. Opening 3478 without opening the allocated relay ports can allow the initial TURN connection but still prevent media traffic from flowing.

If your VPS provider maps its public IP to a private interface rather than assigning it directly to the network interface, configure Coturn's `external-ip` option with the public/private address mapping. Do not add this setting blindly.

## 9\. Restart Coturn

Restart the service:

```bash
sudo systemctl restart coturn
```

Enable it at startup:

```bash
sudo systemctl enable coturn
```

Check the service:

```bash
sudo systemctl status coturn
```

Check listening sockets:

```bash
sudo ss -lntup | grep -E '3478|5349'
```

Check logs:

```bash
sudo journalctl -u coturn -f
```

At this point, the TURN server should be running.

## 10\. Generate temporary TURN credentials using Node.js

The backend must generate credentials using the shared secret.

Coturn's REST authentication format is:

```text
username = expiration_timestamp:user_id

password = Base64(
  HMAC-SHA1(shared_secret, username)
)
```

The timestamp represents the credential's expiration time in Unix seconds.

Here is an Express example:

```javascript
import { createHmac } from "node:crypto";

app.get("/api/turn-credentials", requireAuth, (req, res) => {
  const secret = process.env.TURN_SHARED_SECRET;

  if (!secret) {
    return res.status(500).json({
      error: "TURN server is not configured",
    });
  }

  // Credentials expire after one hour.
  const expiresAt = Math.floor(Date.now() / 1000) + 3600;

  // Use the authenticated user's ID, not an arbitrary
  // user ID supplied in the query string.
  const username = `${expiresAt}:${req.user.id}`;

  const credential = createHmac("sha1", secret)
    .update(username)
    .digest("base64");

  res.setHeader("Cache-Control", "no-store");

  return res.json({
    iceServers: [
      {
        urls: [
          "turn:turn.example.com:3478?transport=udp",
          "turn:turn.example.com:3478?transport=tcp",
          "turns:turn.example.com:5349?transport=tcp",
        ],
        username,
        credential,
      },
    ],
  });
});
```

Set the backend environment variable:

```env
TURN_SHARED_SECRET=YOUR_GENERATED_SECRET
```

This must exactly match `static-auth-secret` in `/etc/turnserver.conf`.

The endpoint should require authentication and use HTTPS. Never put the shared secret in the browser.

## 11\. Connect the TURN server to WebRTC

The frontend requests temporary credentials from your backend:

```javascript
const response = await fetch("/api/turn-credentials", {
  credentials: "include",
});

if (!response.ok) {
  throw new Error("Could not obtain TURN credentials");
}

const { iceServers } = await response.json();

const peerConnection = new RTCPeerConnection({
  iceServers,
});
```

That's all you need to add the TURN server to the ICE server configuration.

You do not need to force relay mode for normal calls. ICE should try the available connection paths and select a working candidate pair.

For diagnostics, however, you can force TURN:

```javascript
const peerConnection = new RTCPeerConnection({
  iceServers,
  iceTransportPolicy: "relay",
});
```

This prevents the connection from using host or server-reflexive candidates. It is useful for proving that your TURN server works, but it is generally not the setting to use for every production call because relaying all traffic increases latency and bandwidth consumption.

### How credentials and TURN allocation work

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqVk02P2jAQhv_K1GdTqVJPOayUsEXNYVGE2T1xGewJuPgjtR0oXfHfKxO2UNhtt8fJPH78zsh5ZtIrYgWL9L0nJ-le4yqgXTgAAOyTd71dUhjqDkPSUnfoEpSAERqiAOUrzabO7alX9PFbzOUtU_0WVLdNkZtCrxwa7VYgKGxfCzHP2NinPjh4asTCDUg5ursrm7qAWZ4qJpg_zqYgAylySaOJJ6ypR5ksYE628wHDHvpIwaElQKegwxh3PqgXb_Vf3urd3pxXFCDIKRD3Dfi2pXAk6_EXkOiUVpjopBeDe-LDDoO6gK_B6kqLLu7-4S3P3gv6kjwnnhfD_KUxXmIiCMNWBmJ-Wu2MDO7PhstVvkNQvSmY-kTgt_n98aoYBvLOkUx6q9Me5Jrk5jrvAymN0KHcUIov1_yxTXtLVH89W75xlnFmKVjUihXPLK3J5t9MUYu9SYwPX54waFwaiplpvUsTtNrsWcFG2HWGRnEfE1kOldFu84BSHOuJd4nDgglaeYLHesE4zPzSJ8_hK5ktJS2RQxk0Gg4RXRxFCrpl_HiJ0D9zlk-fux_scOBsuRp74wMr2IfdWidih19P0VW_?type=png)

The signaling server shown here is your existing application infrastructure. Coturn does not exchange SDP offers or answers.

## 12\. Test whether TURN is actually working

Use the official WebRTC Trickle ICE test:

[https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/](https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/)

Enter your TURN server:

```text
TURN URI:
turn:turn.example.com:3478?transport=udp

Username:
Generated temporary username

Password:
Generated temporary credential
```

Set the ICE transport policy to `relay` and gather candidates.

A successful TURN allocation should produce a candidate with:

```text
typ relay
```

The important distinction:

-   `host` means a local candidate.
    
-   `srflx` means a server-reflexive candidate.
    
-   `relay` means a TURN relay candidate.
    

If you only see `host` or `srflx`, you have not established that TURN is working.

Test the TLS endpoint separately using:

```text
turns:turn.example.com:5349?transport=tcp
```

Use valid temporary credentials for each test.

## 13\. Troubleshooting

### No relay candidate appears

Check that:

-   TCP/UDP port 3478 is open.
    
-   TCP port 5349 is open for TLS.
    
-   UDP relay ports 49160–49999 are open.
    
-   The VPS provider firewall allows the same traffic.
    
-   DNS resolves to the correct IP.
    
-   The certificate is valid.
    
-   The credentials are generated using the same secret configured in Coturn.
    

### Authentication fails

Check:

```bash
sudo journalctl -u coturn -n 100 --no-pager
```

Common causes:

-   Different secrets in the backend and Coturn.
    
-   Incorrect HMAC input.
    
-   Incorrect username format.
    
-   An expired timestamp.
    
-   Incorrect server clock.
    

Check time synchronization:

```bash
timedatectl
```

### TURN works on desktop but not on mobile

Try the TCP and TLS TURN URLs.

Some networks restrict UDP traffic. TURN over TCP or TLS gives the client an alternative transport to reach the TURN server.

However, if the network blocks every available path to your TURN endpoint, the connection can still fail.

### A relay candidate appears, but the call still fails

A successful relay candidate proves that TURN allocation worked. It does not prove that the entire WebRTC call is healthy.

Check the ICE candidate pair, signaling messages, SDP exchange, DTLS connection and browser logs.

TURN cannot fix incorrect signaling or incompatible media negotiation.

## 14\. Understand the bandwidth cost

TURN relays media traffic. It is not just a signaling service.

When a call uses a relay, the VPS processes and forwards media packets. The server's outbound bandwidth can therefore grow quickly with the number of calls, video quality and call duration.

Before using a small VPS in production, monitor:

-   Network ingress and egress.
    
-   Concurrent TURN allocations.
    
-   CPU and memory.
    
-   Failed allocations.
    
-   Bandwidth limits and provider overage charges.
    

Deploy the TURN server close to your users where possible. For a global application, one TURN server in one region may not provide acceptable latency everywhere.

## Conclusion

If WebRTC works on Wi-Fi but fails on certain mobile or restricted networks, TURN should be part of your connectivity strategy.

Coturn gives you control over the relay infrastructure, authentication and network configuration. A VPS with a public IP is enough to get started, provided the server has the required network access and bandwidth.

The important part is not simply installing Coturn. It is configuring authenticated access, opening the relay port range, handling TLS certificates correctly, issuing temporary credentials and verifying that relay candidates are actually gathered.

**Official references**

-   [MDN: WebRTC protocols](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols)
    
-   [Coturn: TURN server documentation](https://github.com/coturn/coturn/wiki/turnserver)
    
-   [Coturn: Configuration example](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf)
    
-   [WebRTC: Trickle ICE test](https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/)

---

*Published via [ZyVOP](https://zyvop.com/webrtc-calls-work-on-wi-fi-but-fail-on-mobile-networks-set-up-your-own-turn-server-with-coturn-7q7la?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
