Skip to content

Deploying the OpenTelemetry Collector in gateway mode on Ubuntu 22.04

Stand up a hardened OTel Collector gateway on Ubuntu 22.04 with a real processor pipeline and multi-export to traces, metrics, and logs backends.

You inherit a fleet of forty application VMs that each ship traces, metrics, and logs directly to a different vendor SDK. Vendor bills keep climbing because raw spans go out with no sampling, the Java services are exporting to one tenant and the Node services to another, and there’s no central place to drop a span attribute when GDPR asks you to scrub a header. You decide the right answer is the boring one — put an OpenTelemetry Collector gateway in front of everything, terminate OTLP from the apps, run a real processor pipeline, and fan-out to multiple backends from one place. This is the installer.

What’s happening

A “gateway” Collector is a Collector binary running on dedicated hosts (not co-located with the app, not in a sidecar) whose only job is to receive OTLP from upstream agents/SDKs, normalize it, sample it, redact it, batch it, and export it to one or more backends. The agent-vs-gateway distinction matters because the gateway is where you put the policy that you do not want to push to every workload: tail-based sampling decisions need the whole trace and cannot be made by an agent that only sees one service’s spans; PII redaction needs to be enforced regardless of which SDK an upstream team chose; vendor routing — “send 100% of error traces to vendor A, 10% of OK traces to vendor B, all logs to Loki” — is a fan-out problem that does not belong in application code.

Without a gateway you get the failure mode you usually inherit: every service ships everything to one vendor SDK, the bill scales linearly with traffic, and the day legal asks “are we sending the Authorization header to a third party” the answer is “let me check forty services.” With a gateway the answer is “let me check one config file.”

How to verify

After you run the installer, a healthy gateway responds on the OTLP gRPC port, the OTLP HTTP port, and the internal telemetry endpoint. Quick smoke check from the gateway host itself:

# OTLP gRPC receiver listening
ss -lntp | grep -E ':(4317|4318|13133|8888)\b'

# Health check endpoint
curl -fs http://127.0.0.1:13133/

# Collector's own metrics (Prometheus format)
curl -fs http://127.0.0.1:8888/metrics | grep -E '^otelcol_(receiver|processor|exporter)_' | head -20

Send a synthetic trace from an SDK or otelcol-contrib running on a workstation pointed at the gateway, then watch the receiver and exporter counters tick:

watch -n 2 'curl -fs http://127.0.0.1:8888/metrics \
  | grep -E "otelcol_(receiver_accepted_spans|exporter_sent_spans|processor_batch_send_size_count)" \
  | sort'

If receiver_accepted_spans is climbing but exporter_sent_spans is flat, the exporter side is the problem (auth, TLS, network egress, vendor quota). If both are climbing but a downstream backend shows nothing, look at the queue and retry counters next:

curl -fs http://127.0.0.1:8888/metrics | grep -E 'otelcol_exporter_(queue_size|enqueue_failed|send_failed)'

The fix

Save this as /root/setup-otel-gateway.sh on a fresh Ubuntu 22.04 host and run it as root. It installs OpenTelemetry Collector Contrib (the build with the contrib processors and exporters), provisions a dedicated otelcol system user, writes a hardened systemd unit with capabilities and ambient-cap restrictions, and drops in a gateway config with OTLP gRPC + HTTP receivers, a memory-limiter processor, batch + tail-based sampling + attribute scrubbing, and three exporters (Jaeger via OTLP, Prometheus remote-write, Loki) plus a debug exporter you can toggle off after smoke tests. UFW opens only the receiver ports to the application VLAN and TLS is terminated on the gateway with cert files the operator drops in /etc/otelcol/tls/ before first start.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 OpenTelemetry Collector gateway installer
### Run on a clean VM with a private IP reachable from your app fleet
### Drop TLS cert + key in /etc/otelcol/tls before first start, or set TLS_ENABLED=0 to bring up plaintext temporarily

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT BEFORE RUN ===
OTELCOL_VERSION="0.110.0"
GATEWAY_NAME="otel-gw-1"
PRIVATE_IP="10.20.0.20"            # IP this gateway binds to
APP_CIDR="10.20.0.0/16"            # CIDR allowed to push OTLP
JAEGER_OTLP_ENDPOINT="jaeger-collector.internal:4317"
PROM_REMOTE_WRITE_URL="https://prom.internal/api/v1/write"
PROM_REMOTE_WRITE_USER="otel-gw"
PROM_REMOTE_WRITE_PASS="CHANGE_ME"
LOKI_ENDPOINT="https://loki.internal/loki/api/v1/push"
LOKI_TENANT="prod"
TLS_ENABLED=1
# =======================

echo
echo "========================================"
echo "OpenTelemetry Collector gateway: ${GATEWAY_NAME}"
echo "Bind IP: ${PRIVATE_IP}"
echo "========================================"
echo

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade
apt-get -y install curl wget ca-certificates gnupg lsb-release \
  ufw chrony jq vim tar gzip net-tools dnsutils unattended-upgrades \
  fail2ban auditd

systemctl enable --now chrony
systemctl enable --now auditd

echo "==> Unattended security upgrades"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
AUTOUPG

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart sshd

echo "==> fail2ban for SSH"
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> UFW: open OTLP receivers to APP_CIDR only"
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow from "${APP_CIDR}" to "${PRIVATE_IP}" port 4317 proto tcp
ufw allow from "${APP_CIDR}" to "${PRIVATE_IP}" port 4318 proto tcp
ufw --force enable

echo "==> Creating otelcol system user"
if ! id otelcol >/dev/null 2>&1; then
  useradd --system --no-create-home --shell /usr/sbin/nologin --user-group otelcol
fi

mkdir -p /etc/otelcol /etc/otelcol/tls /var/lib/otelcol /var/log/otelcol
chown -R otelcol:otelcol /etc/otelcol /var/lib/otelcol /var/log/otelcol
chmod 750 /etc/otelcol/tls

echo "==> Downloading otelcol-contrib ${OTELCOL_VERSION}"
ARCH="amd64"
TARBALL="otelcol-contrib_${OTELCOL_VERSION}_linux_${ARCH}.tar.gz"
URL="https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v${OTELCOL_VERSION}/${TARBALL}"
cd /tmp
wget -q "${URL}"
mkdir -p otelcol-contrib && tar xzf "${TARBALL}" -C otelcol-contrib
install -o root -g root -m 0755 otelcol-contrib/otelcol-contrib /usr/local/bin/otelcol-contrib
/usr/local/bin/otelcol-contrib --version

echo "==> Writing gateway config"
TLS_BLOCK="tls:
        cert_file: /etc/otelcol/tls/gateway.crt
        key_file: /etc/otelcol/tls/gateway.key
        client_ca_file: /etc/otelcol/tls/ca.crt"

if [[ "${TLS_ENABLED}" -ne 1 ]]; then
  TLS_BLOCK="# TLS disabled — bring up cert files in /etc/otelcol/tls and flip TLS_ENABLED back on"
fi

cat > /etc/otelcol/config.yaml <<EOF
# OpenTelemetry Collector gateway config — generated by setup-otel-gateway.sh
# Pipelines: traces (tail-sampled, attribute-scrubbed) -> Jaeger
#            metrics (batched) -> Prometheus remote-write
#            logs (attribute-scrubbed, batched) -> Loki

extensions:
  health_check:
    endpoint: 0.0.0.0:13133
  pprof:
    endpoint: 127.0.0.1:1777
  zpages:
    endpoint: 127.0.0.1:55679

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: ${PRIVATE_IP}:4317
        ${TLS_BLOCK}
        max_recv_msg_size_mib: 32
        keepalive:
          server_parameters:
            max_connection_age: 10m
            max_connection_age_grace: 1m
      http:
        endpoint: ${PRIVATE_IP}:4318
        cors:
          allowed_origins: []

  prometheus/self:
    config:
      scrape_configs:
        - job_name: otelcol-self
          scrape_interval: 30s
          static_configs:
            - targets: ['127.0.0.1:8888']

processors:
  memory_limiter:
    check_interval: 1s
    limit_percentage: 75
    spike_limit_percentage: 20

  batch:
    timeout: 5s
    send_batch_size: 8192
    send_batch_max_size: 10000

  resource:
    attributes:
      - action: upsert
        key: gateway.name
        value: ${GATEWAY_NAME}
      - action: upsert
        key: gateway.cluster
        value: prod

  attributes/scrub:
    actions:
      - key: http.request.header.authorization
        action: delete
      - key: http.request.header.cookie
        action: delete
      - key: http.request.header.x-api-key
        action: delete
      - key: user.email
        action: hash
      - key: enduser.id
        action: hash

  tail_sampling:
    decision_wait: 30s
    num_traces: 100000
    expected_new_traces_per_sec: 1000
    policies:
      - name: keep-errors
        type: status_code
        status_code:
          status_codes: [ERROR]
      - name: keep-slow
        type: latency
        latency:
          threshold_ms: 1000
      - name: probabilistic-rest
        type: probabilistic
        probabilistic:
          sampling_percentage: 10

  filter/drop-noise:
    error_mode: ignore
    traces:
      span:
        - 'attributes["http.target"] == "/healthz"'
        - 'attributes["http.target"] == "/readyz"'
        - 'attributes["http.target"] == "/metrics"'

exporters:
  otlp/jaeger:
    endpoint: ${JAEGER_OTLP_ENDPOINT}
    tls:
      insecure: false
      ca_file: /etc/otelcol/tls/ca.crt
    sending_queue:
      enabled: true
      num_consumers: 4
      queue_size: 10000
    retry_on_failure:
      enabled: true
      initial_interval: 5s
      max_interval: 30s
      max_elapsed_time: 300s

  prometheusremotewrite:
    endpoint: ${PROM_REMOTE_WRITE_URL}
    auth:
      authenticator: basicauth/prom
    tls:
      insecure: false
    resource_to_telemetry_conversion:
      enabled: true
    remote_write_queue:
      enabled: true
      queue_size: 10000
      num_consumers: 4

  loki:
    endpoint: ${LOKI_ENDPOINT}
    headers:
      X-Scope-OrgID: ${LOKI_TENANT}
    sending_queue:
      enabled: true
      queue_size: 5000
      num_consumers: 4

  debug:
    verbosity: basic
    sampling_initial: 2
    sampling_thereafter: 500

extensions/basicauth:
  basicauth/prom:
    client_auth:
      username: ${PROM_REMOTE_WRITE_USER}
      password: ${PROM_REMOTE_WRITE_PASS}

service:
  extensions: [health_check, pprof, zpages, basicauth/prom]
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, filter/drop-noise, attributes/scrub, resource, tail_sampling, batch]
      exporters: [otlp/jaeger, debug]
    metrics:
      receivers: [otlp, prometheus/self]
      processors: [memory_limiter, resource, batch]
      exporters: [prometheusremotewrite]
    logs:
      receivers: [otlp]
      processors: [memory_limiter, attributes/scrub, resource, batch]
      exporters: [loki]
  telemetry:
    logs:
      level: info
      output_paths: [stdout]
    metrics:
      level: detailed
      address: 127.0.0.1:8888
EOF

chown otelcol:otelcol /etc/otelcol/config.yaml
chmod 640 /etc/otelcol/config.yaml

echo "==> systemd unit"
cat > /etc/systemd/system/otelcol.service <<'UNIT'
[Unit]
Description=OpenTelemetry Collector (gateway)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=otelcol
Group=otelcol
ExecStart=/usr/local/bin/otelcol-contrib --config=/etc/otelcol/config.yaml
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5s
LimitNOFILE=200000
TimeoutStopSec=30

# Hardening
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
ReadWritePaths=/var/lib/otelcol /var/log/otelcol

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload

echo "==> Validating config"
/usr/local/bin/otelcol-contrib validate --config=/etc/otelcol/config.yaml

echo "==> Starting otelcol"
systemctl enable --now otelcol

echo "==> Waiting for health check"
for i in {1..30}; do
  if curl -fs http://127.0.0.1:13133/ >/dev/null 2>&1; then break; fi
  sleep 2
done

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(4317|4318|13133|8888|55679)\b' || true
echo
echo "Health:"
curl -fs http://127.0.0.1:13133/ || echo "health check failed"
echo
echo "Push a test trace from an app or another collector:"
echo "  endpoint: ${PRIVATE_IP}:4317 (gRPC) or ${PRIVATE_IP}:4318 (HTTP)"
echo
echo "Tail logs:"
echo "  journalctl -u otelcol -f"
echo

Make it executable and run it:

chmod 700 /root/setup-otel-gateway.sh
/root/setup-otel-gateway.sh

After first start, point a single application SDK at the gateway (set OTEL_EXPORTER_OTLP_ENDPOINT=https://<gateway-ip>:4317 on the SDK), watch otelcol_receiver_accepted_spans climb, and confirm spans show up in Jaeger and metrics in Prometheus. Once a single service is green, roll the OTLP endpoint to a second service, then a third — do not flip the whole fleet at once. The tail-sampling decision window is 30 seconds: errors and slow spans are always kept, the rest get 10% probabilistic sampling. Tune sampling_percentage and the latency threshold based on what your backend can ingest, not based on what looks elegant in config.

Stack Harbor runs OTel gateways for customers as part of monitoring and support under Managed Cloud Ops — with sampling-policy review, vendor-cost guardrails, and Sev-1 escalation. Start a scoping call if you want this operated, not just installed.