basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Beszel: agent without an open port, rolling-average thresholds and heartbeat

    The Beszel agent connects to the hub over WebSocket and keeps its fallback on a Unix socket or off, so the server never opens a port even when the hub is down. Thresholds check the rolling average over the window: “80% for 10 minutes” fires around minute eight under full load, while a brief spike stays quiet. The heartbeat to Healthchecks.io tells you the hub is alive, not that every server is up.

    With default settings, the Beszel agent opens port 45876 on every server address the second the hub stops answering. The “CPU Usage 80% for 10 minutes” threshold doesn’t mean 10 consecutive minutes above 80%: it checks the rolling average, so full load triggers earlier and a short spike never fires at all. The heartbeat to Healthchecks.io keeps arriving even when half your servers are down. Installation is covered in stage “Beszel: the hub and the agent” of Metrics, uptime checks and alerts; here is how those pieces work.

    Two paths between the agent and the hub

    The hub is a web app with graphs and a database; the agent collects metrics on the host. Once a minute the hub asks the agent for a sample and writes one record to its database. They can talk over two paths:

    primary path — WebSocket: the agent connects to the hub
      web1 agent ── HUB_URL=http://localhost:8090 ─────────────────▶ hub
      web2 agent ── HUB_URL=https://beszel.example.org ─▶ Traefik ─▶ hub
    
    fallback path — SSH: the hub connects to the agent
      hub ── /beszel_socket/beszel.sock ──▶ web1 agent   socket exists only while WebSocket is down
      hub ── :45876 ──────────────────────▶ web2 agent   stays closed with DISABLE_SSH=true
    • WebSocket. The agent connects to HUB_URL and presents TOKEN, which tells the hub which system it is. On the first connection the hub records the machine’s fingerprint and rejects the same token from any other host. KEY is the hub’s public key; the agent checks it to verify it reached its own hub.
    • SSH. The agent listens on a TCP port or Unix socket and accepts only the hub holding KEY. It opens this listener only when WebSocket drops or fails to connect, and closes it the moment WebSocket returns.

    Restart the hub, and the agent opens its socket for a few seconds, then reconnects over WebSocket and closes the socket. The fallback helps when the hub is up but rejects the agent’s WebSocket — for example, after a token rotation. The agent keeps getting rejected, while the hub connects back over the socket after a restart and metrics keep flowing. If the socket fails too, the hub marks the system “Down”.

    Agent next to the hub: compose line by line

    This is the same file as in the recipe. Hub and agent live on one server and share the data/socket directory.

    /opt/beszel/docker-compose.yaml
    services:
      beszel:
        image: henrygd/beszel:latest
        container_name: beszel
        restart: unless-stopped
        environment:
          APP_URL: https://beszel.example.org
          USER_EMAIL: [email protected]
          USER_PASSWORD: ${BESZEL_PASSWORD}
          HEARTBEAT_URL: ${HEARTBEAT_URL:-}

    The hub. USER_EMAIL and USER_PASSWORD create the account on an empty database on first start. HEARTBEAT_URL sets the heartbeat endpoint; :- substitutes an empty string if .env omits it, turning the heartbeat off.

        ports:
          - "127.0.0.1:8090:8090"
        volumes:
          - ./data/hub:/beszel_data
          - ./data/socket:/beszel_socket

    127.0.0.1:8090 lets the local agent reach the hub without Traefik (A host-only port goes on 127.0.0.1): if Traefik goes down, metrics keep recording. data/socket is mounted into the hub too so it can reach the agent’s socket.

        labels:
          - "traefik.enable=true"
          - "traefik.http.routers.beszel.rule=Host(`beszel.example.org`)"
          - "traefik.http.routers.beszel.entrypoints=https"
          - "traefik.http.services.beszel.loadbalancer.server.port=8090"
        networks:
          - proxy

    Browsers and agents on other servers come in through Traefik at https://beszel.example.org. Traefik proxies WebSocket without extra labels.

      beszel-agent:
        image: henrygd/beszel-agent:latest
        container_name: beszel-agent
        restart: unless-stopped
        network_mode: host

    network_mode: host lets the agent see the host’s network interfaces instead of the container’s, and makes localhost point to the host itself.

        environment:
          LISTEN: /beszel_socket/beszel.sock
          HUB_URL: http://localhost:8090
          KEY: ${BESZEL_KEY:-}
          TOKEN: ${BESZEL_TOKEN:-}
    Key part

    HUB_URL and TOKEN are the primary path. LISTEN tells the agent where to put its fallback: a Unix socket in the shared directory instead of a port. Without this line it would open :45876, which with network_mode: host binds every address on the server. The socket is owned by root, so only root can connect to it.

        volumes:
          - ./data/agent:/var/lib/beszel-agent
          - ./data/socket:/beszel_socket
          - /var/run/docker.sock:/var/run/docker.sock:ro

    The agent stores its fingerprint in data/agent. Delete the file and the agent derives the same fingerprint from the machine ID, so the hub still accepts it. Mounting the Docker socket gives container metrics, which equals root access (docker.sock).

    networks:
      proxy:
        external: true

    The Traefik network from level “Services”.

    Agent on a second server

    web2 has no hub, so it doesn’t need a socket: the agent connects out to https://beszel.example.org, and you turn the fallback off. Left on, the hub would connect to web2 over the internet on port 45876, exposing that port to scanners too. Run the agent as a standalone binary under systemd so web2 doesn’t need Docker.

    First add the system in the hub: click “Add System”, set the name to web2, and put 203.0.113.11 in “Host / IP”. WebSocket doesn’t use that address, though the field is required. The dialog shows “Public Key” and “Token”; each system gets its own token.

    1. Agent

      Download the release binary from GitHub and check its checksum:

      cd /tmp
      R=https://github.com/henrygd/beszel/releases/download/v0.21.2
      curl -sSLO $R/beszel-agent_linux_amd64.tar.gz
      curl -sSL $R/beszel_0.21.2_checksums.txt | grep ' beszel-agent_linux_amd64.tar.gz$' | sha256sum -c
      # beszel-agent_linux_amd64.tar.gz: OK
      tar xzf beszel-agent_linux_amd64.tar.gz beszel-agent
      sudo install -m 755 beszel-agent /usr/local/bin/beszel-agent
      sudo useradd --system --home-dir /nonexistent --shell /bin/false beszel
    2. Unit

      Use the same unit as Beszel’s installer script, with DISABLE_SSH=true added at the top. Replace <key> and <token> with the values from the dialog.

      # /etc/systemd/system/beszel-agent.service
      [Unit]
      Description=Beszel Agent Service
      Wants=network-online.target
      After=network-online.target
      
      [Service]
      Environment="DISABLE_SSH=true"
      Environment="KEY=<key>"
      Environment="TOKEN=<token>"
      Environment="HUB_URL=https://beszel.example.org"
      ExecStart=/usr/local/bin/beszel-agent
      User=beszel
      Restart=on-failure
      RestartSec=5
      StateDirectory=beszel-agent
      KeyringMode=private
      LockPersonality=yes
      ProtectClock=yes
      ProtectHome=read-only
      ProtectHostname=yes
      ProtectKernelLogs=yes
      ProtectSystem=strict
      PrivateTmp=yes
      RemoveIPC=yes
      RestrictSUIDSGID=true
      
      [Install]
      WantedBy=multi-user.target

      StateDirectory creates /var/lib/beszel-agent, where the agent stores its fingerprint. Beszel’s installer sets PORT=45876 instead of DISABLE_SSH, which leaves the port open whenever the hub is down.

    3. Start

      sudo systemctl daemon-reload && sudo systemctl enable --now beszel-agent
      sudo journalctl -u beszel-agent -n 1 -o cat
      # INFO WebSocket connected host=beszel.example.org

      In the hub, web2 shows “Up” and its systemd services appear on the system page. Behind Traefik, the agent was tested over http; over https with a real certificate1.

    Thresholds average over the window

    Click the bell in a system’s row: each threshold has a value and a window, such as “Average exceeds 80%” and “For 10 minutes”. After each poll the hub takes the per-minute records across that window and compares their average against the threshold. It alerts once when the average crosses above the limit, and again when it drops back at or below it: “above threshold”, then “below threshold”.

    Three consequences follow:

    • Full load fires before the full window elapses. A 10-minute average crosses 80% once eight of the ten minutes hit 100%, so the alert arrives around minute eight.
    • Short spikes stay silent. Six minutes at 100% inside a 10-minute window average around 60%, so nothing fires. To catch spikes too, shorten the window; at 1 minute the hub compares the latest sample directly without averaging.
    • “Below threshold” is delayed too. After load drops, the average falls under 80% a couple of minutes later once quiet samples enter the window.

    When you add a threshold to a system that already has history, the hub checks it on the next poll: if a disk is already over the limit, the alert fires within the first minute. On a new system it waits until enough samples exist to fill the window.

    “Status” behaves differently: its window is a delay. The moment contact with the agent drops, the hub marks the system “Down” and starts the timer. If the agent comes back before the window expires, the hub cancels the alert and sends nothing. If not, it sends Connection to web2 is down 🔴, and once the agent starts again, Connection to web2 is up ✅ right away.

    Thresholds are set per system. The “All Systems” tab in the same dialog applies a threshold across every system at once, and “Overwrite existing alerts” replaces any already configured.

    Which thresholds to turn on

    Threshold What it tracks What to keep in mind
    “Status” hub-to-agent connection 2 minutes: a drop during an agent restart won’t wake you
    “CPU Usage” processor load rolling average; 80% for 10 minutes catches sustained load, not spikes
    “Memory Usage” memory used excluding cache same rolling average
    “Disk Usage” the fullest mounted disk the alert names which one: Usage of root
    “CPU Steal” CPU time taken by the hypervisor for other VMs on a VPS, signals noisy neighbors taking your CPU
    “Failed Services” systemd units in the failed state no window, though the agent refreshes the unit list every 10 minutes, so alerts aren’t instant
    “Container Health” containers whose healthcheck reports unhealthy only applies to containers that define a healthcheck

    The agent reads “Failed Services” from systemd over D-Bus. The standalone binary sees units out of the box; the containerized agent sees none. A container needs the D-Bus socket and, on Ubuntu, no AppArmor confinement:

      beszel-agent:
        security_opt:
          - apparmor:unconfined
        volumes:
          - /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket:ro

    The trade-off: the container loses Docker’s docker-default AppArmor profile and talks to the host’s systemd over D-Bus. Without apparmor:unconfined the agent sees no units and logs the reason only with LOG_LEVEL: debug — see “If it doesn’t work”.

    Heartbeat: what the hub sends

    With HEARTBEAT_URL set, the hub sends a POST every minute (HEARTBEAT_INTERVAL, in seconds), starting immediately on launch. The body is a JSON summary with status, how many systems are up, which ones are down, and which alerts are active. status is ok when all systems are up, warn when alerts are firing, and error when at least one system is down.

    The URL stays the same either way: the ping still goes out with error. Healthchecks.io ignores the body by default (it checks body text only if you enable Filtering Rules), so a ping means one thing there: the hub is alive and can reach the internet. Beszel’s “Status” alert tells you an agent went down; Healthchecks.io tells you the hub’s server went down. Set HEARTBEAT_METHOD=GET or HEAD to send no body at all.

    If it doesn’t work

    sudo docker logs beszel-agent keeps repeating WebSocket connection failed err="unexpected status code: 401"

    Cause
    The hub doesn’t recognize the token in .env: the system was deleted and re-added, or the token was rotated. An agent next to the hub opens its socket instead, and after a hub restart metrics flow through that socket, so the break only shows up in the log.
    Fix
    Get the system’s token under Settings, Tokens & Fingerprints. Put it in BESZEL_TOKEN in /opt/beszel/.env and run cd /opt/beszel && sudo docker compose up -d: restart doesn’t pick up new variables.

    The agent connects and drops right away: reason=fingerprint mismatch

    Cause
    The token belongs to another system — for instance, .env was copied from web1 to web2. On the first connection the hub saved web1’s machine fingerprint and now rejects that token from any other host.
    Fix
    Create a separate system for web2 in the hub (“Add System”) and use its token.

    On the second server sudo ss -tlnp shows *:45876 on beszel-agent

    Cause
    The hub is unreachable and the agent opened its SSH fallback: the journal says Starting SSH server addr=:45876 network=tcp. The port stays open on all interfaces until WebSocket comes back.
    Fix
    Add Environment="DISABLE_SSH=true" to the agent unit, run daemon-reload and restart — step 2 under “Agent on a second server”.

    CPU sat at 100% for several minutes, yet no “CPU Usage” alert arrived

    Cause
    The threshold checks the average over the window, rather than each individual minute. Five minutes at 100% in a 10-minute window average around 50%, below 80%.
    Fix
    That’s intended: brief spikes don’t page you. If you want to catch them too, shorten the window; at 1 minute the hub compares the latest reading against the threshold.

    The agent stopped for a minute — no “down” alert, no “up” alert

    Cause
    With a 2-minute window, “Status” waits 2 minutes after losing contact. The agent returned sooner, so the hub canceled the alert and sent nothing.
    Fix
    Leave it as is: a brief drop during a restart or upgrade won’t wake you. To test it, stop the agent for 3 minutes (see “How to check”).

    web2 is down, yet the Healthchecks.io check is green

    Cause
    The hub sends the heartbeat as long as the hub itself is alive. A dead agent only appears inside the ping body as "status":"error", and Healthchecks.io ignores the body by default.
    Fix
    The “Status” threshold on that system reports a dead agent: click the bell in the web2 row. The heartbeat covers the case where the hub’s own server goes down.

    “Failed Services” is on, yet web1 has no service list and no alerts for failed units

    Cause
    The containerized agent can’t reach systemd: it needs the D-Bus socket and, on Ubuntu, an unconfined AppArmor profile. With LOG_LEVEL: debug, the agent logs An AppArmor policy prevents this sender from sending this message to this recipient.
    Fix
    Mount /var/run/dbus/system_bus_socket in the agent’s volumes and set security_opt: [apparmor:unconfined] — see “Which thresholds to turn on”. Or run the agent binary directly, which sees services without either setting.

    How to check

    Confirm the web1 agent is on WebSocket and the fallback socket is absent:

    sudo docker logs beszel-agent 2>&1 | grep -E 'WebSocket connected|SSH server' | tail -1
    # … INFO WebSocket connected host=localhost:8090
    ls /opt/beszel/data/socket
    # (empty)

    Confirm the web2 agent opens no port even while the hub is stopped. Stop the hub on web1 and check web2:

    cd /opt/beszel && sudo docker compose stop beszel     # web1
    sudo ss -tlnpH | grep beszel-agent                    # web2
    # (empty)
    sudo docker compose start beszel                      # web1

    Without DISABLE_SSH, the second command would list *:45876.

    Test “Status” by action (Test your server’s protection by action): run sudo systemctl stop beszel-agent on web2, then start 3 minutes later. Your phone receives Connection to web2 is down 🔴 2 minutes after stopping and up ✅ right after starting.

    Not verified yet

    1. the agent connects to https://beszel.example.org with a Let’s Encrypt certificate ↑