# ops.jiunotes.top — 全站文章完整索引
> 生成日期:2026-12-05
> 版权:© 2026 玖 · CC BY-NC-SA 4.0
> 语言:中文 (zh) + 英文 (en)
本文档列出站点内所有文章的完整正文内容。AI 助手可直接抓取本文作为问答素材。
---
# Network & DNS
## AIOps for Network Operations: Anomaly Detection, Failure Prediction, and Intelligent Traffic Steering
URL: https://ops.jiunotes.top/en/network/aiops-network.md
摘要: A working engineer's path from static thresholds to AIOps: why CPU>90% rules drown you in noise, the four-layer pipeline (Prometheus collection, Kafka streaming, detection models, action layer), how to build a dynamic baseline with 3-sigma and Isolation Forest, and how to wire an LSTM failure predictor into Alertmanager. Includes a real BGP flapping prediction case that bought me a 45-minute head start.
### Answer
AIOps replaces static thresholds with learned behavior. Three scenes pay off: anomaly detection with a dynamic baseline, failure prediction with a time-series model, and intelligent traffic steering. The pipeline is collection (Prometheus), streaming (Kafka), inference (Python), action (Alertmanager webhook). Start with anomaly detection only - it is the cheapest and shows the fastest return. A real BGP flapping predictor gave me a 45-minute head start on a fiber cut.
### FAQ
Q: How is AIOps different from traditional monitoring?
A: Traditional monitoring sets a fixed threshold (CPU over 90% alerts). AIOps learns the normal band from history, so an alert fires only when behavior departs from that band. Traditional monitoring reacts after a failure; AIOps tries to warn before it.
Q: Is AIOps worth it for a small team?
A: If you have under five engineers and under a hundred devices, a clean static-threshold setup is enough. AIOps pays off when alert volume overwhelms the humans. Start with anomaly detection - it is the lowest effort and the most visible win.
Q: How long until AIOps is actually running?
A: Count on four stages: collection (1-2 weeks), anomaly detection (2-4 weeks), failure prediction (1-2 months), intelligent steering (2-3 months). You see value at stage two. Do not promise the model layer before you have a month of clean history.
Q: What metric should I start modeling first?
A: Pick a high-volume, noisy metric where false positives are already a problem - interface utilization or packet loss on a busy link is ideal. Do not start with a rare, binary failure state; you will not have enough positive examples to train on.
Q: What is the biggest trap in building a prediction model?
A: Leakage and imbalance. If you normalize with a scaler fitted on the full dataset, the model cheats and looks great in validation but falls apart live. And if failures are 0.1% of samples, a model that always says 'no failure' is 99.9% accurate and useless. Always use a time-based split, never a random one.
### Full Content
# AIOps for Network Operations: Anomaly Detection, Failure Prediction, and Intelligent Traffic Steering
Most teams that say they "do AIOps" have actually done one thing: they let a machine learning library score a few metrics and then still page the same human at 3 a.m. I have been through that stage, and I want to write down what actually changed the way I run a network. In my experience only three use cases earn their keep: anomaly detection that replaces a static threshold, failure prediction that buys lead time, and traffic steering that removes a manual routing decision. Everything else is a demo.
## Why Static Thresholds Stop Working
The pain that pushed me toward this was not exotic. It was a wall of alerts that I could not trust. The three problems were:
```
Problem 1: alert fatigue
- 1,000 devices, each emitting a dozen metrics
- 500 alert rules, 5,000+ firings a day
- the real page gets buried under the routine ones
Problem 2: the threshold is wrong for most of the day
- CPU>90% fires all afternoon, but 85% is normal at peak
- too loose -> missed real failures
- too tight -> alarm fatigue, everyone stops looking
Problem 3: we react, never predict
- a user complains before we know
- triage is manual and slow
- recovery is manual and error-prone
```
A static threshold assumes the metric has one "normal" value. A network metric does not - it has a rhythm. The whole point of the anomaly-detection layer is to learn that rhythm and only complain when the metric leaves it.
## Cold Water First: Does Your Scenario Actually Deserve It
All of the above is "what it can do." What has cost me the most time, though, is talking teams out of AIOps projects that made things worse, not better. Three scenarios I have seen where the model was live and the team was worse off:
First, **not enough data, and no historical failure labels.** Failure prediction is supervised learning at its core - you need "which disks and links eventually failed" as labels. A cluster that has run for a year without a single disk dying gives you nothing to train an LSTM on. Train on it anyway and you are fitting noise as pattern; the model false-alarms on launch, the team turns the alerts off within three weeks. In that situation a clean static-threshold setup beats fake intelligence, full stop.
Second, **a topology that changes daily and unstable metric semantics.** Devices scale in and out constantly, metric names are inconsistent, the collector itself drops out now and then. The model learned "last week's topology." This week it shifts, the distribution drifts, and the anomaly detector goes off in a blind panic. I have seen a project where the model itself was fine and the only problem was the collector dropping twice a week; the false-positive rate doubled purely from data quality, not from the model.
Third, **an action path that is irreversible and has no fallback.** Intelligent steering wants to "reroute automatically" and "scale automatically." If the model gives a bad call and there is no human-confirmation window, that is a network-wide incident. If your change process does not allow "half-automated plus a human backstop," do not deploy automatic steering. Stop at the model recommending and a human clicking confirm.
To judge whether it is worth doing, I ask four questions: (1) Do you have enough history - at least one full business cycle? (2) Do you have failure/normal labels, or a way to produce them? (3) Is the data quality stable - collector drop rate, metric naming? (4) Can the action path keep a human backstop? If any one of those four cannot be answered, do not start yet. Build the basics. AIOps is an amplifier for when the scale and the fundamentals are in place, not a foundation.
## The Four-Layer Pipeline
The architecture I settled on has four layers, each with one job and no shortcuts:
```
+------------------------------------------------------+
| Action layer: Alertmanager, auto-remediation, boards |
+------------------------------------------------------+
| Model layer: anomaly score, failure probability |
+------------------------------------------------------+
| Streaming layer: [Kafka](https://kafka.apache.org/documentation/), windowed aggregation |
+------------------------------------------------------+
| Collection layer: [Prometheus](https://prometheus.io/docs/) + SNMP exporter |
+------------------------------------------------------+
```
The reason I split collection from streaming is that Prometheus scrape intervals and model inference cadence are different. Scrape every 15 seconds; aggregate in a 60-second window; score every minute. Do not try to run the model inline in the scrape path.
## Layer 1: Collection
The collection layer is deliberately unremarkable - it is a normal Prometheus setup with an SNMP exporter added for the gear that has no HTTP endpoint:
```yaml
# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
# Switches and routers via SNMP
- job_name: 'network-snmp'
metrics_path: /snmp
static_configs:
- targets: ['switch-01', 'switch-02', 'router-01']
labels:
device_type: switch
# Interface counters, packet loss, and latency probes
- job_name: 'netlatency'
static_configs:
- targets: ['probe-01:9425', 'probe-02:9425']
```
## Layer 2: Streaming
Kafka is my buffer between the scraped world and the modeling world. The scrape produces raw samples; the consumer windows them. I use a plain Kafka consumer in [Python](https://docs.python.org/) rather than Flink, because for my volume a single consumer with a 60-second tumbling window is simpler to reason about than a full streaming framework.
```python
# consumer.py - windowed aggregation of metrics
from confluent_kafka import Consumer
from collections import defaultdict
WINDOW = 60 # seconds
buckets = defaultdict(list)
consumer = Consumer({
'bootstrap.servers': 'kafka:9092',
'group.id': 'aiops-window',
'auto.offset.reset': 'earliest',
})
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
# payload: {"device":"sw-01","metric":"if_in_util","value":0.42,"ts":...}
payload = json.loads(msg.value())
key = (payload['device'], payload['metric'])
buckets[key].append(payload['value'])
if len(buckets[key]) >= WINDOW:
yield_stat(key, buckets[key])
buckets[key] = []
```
This keeps the model layer simple: it always receives a complete window, never a trickle.
## Layer 3: Detection Models
Two models, and I use them for different jobs. The statistical one is my baseline; the forest is my second opinion on the same window.
**Dynamic baseline (3-sigma).** Instead of a fixed `CPU > 90`, compute the mean and standard deviation of the metric over the last 24 hours and alert when the current value is more than three standard deviations away. This automatically shifts the "normal" band with the business cycle:
```python
import numpy as np
def dynamic_baseline(value, history, sigma=3.0, window=288):
"""history is the last 24h of samples, 5-min cadence."""
if len(history) < window:
return {'is_anomaly': False, 'reason': 'insufficient_history'}
recent = np.array(history[-window:])
mean = recent.mean()
std = recent.std()
upper = mean + sigma * std
lower = mean - sigma * std
z = (value - mean) / std if std > 0 else 0.0
return {
'is_anomaly': value > upper or value < lower,
'value': value, 'mean': mean, 'std': std,
'upper': upper, 'lower': lower, 'z_score': z,
}
```
**Isolation Forest.** The 3-sigma baseline assumes the metric is roughly Gaussian. Interface packet loss is not - it is zero most of the time with rare spikes. For that shape I use an Isolation Forest, which isolates anomalies by how few splits it takes to single a point out, with no distribution assumption:
```python
from sklearn.ensemble import IsolationForest
class ForestDetector:
def __init__(self, contamination=0.01, n_estimators=100):
self.model = IsolationForest(
contamination=contamination,
n_estimators=n_estimators,
random_state=42,
)
self.fitted = False
def fit(self, matrix):
self.model.fit(matrix)
self.fitted = True
def score(self, point):
# -1 = anomaly, 1 = normal; more negative = more anomalous
return self.model.predict(point.reshape(1, -1))[0]
```
The practical rule: use 3-sigma for smooth, rhythmic metrics like CPU and latency, and use the forest for bursty metrics like packet loss and retransmits.
## Two Engineering Traps in 3-Sigma (and How to Fix Them)
3-sigma is the starting point for anomaly detection, and also the method most likely to "look understood in the office, fall over in production." Two traps:
**Trap one: the distribution is not Gaussian.** 3-sigma assumes the metric is roughly normal. But a large share of network metrics are not - traffic has spikes (business peaks), latency has a long tail (occasional high values), packet loss sits at zero most of the time and spikes occasionally. Compute mean plus or minus three standard deviations on that shape and the threshold either never gets touched (the spike inflates the standard deviation) or false-alarms constantly inside normal variation. The fix is not a fancier model - it is to look at the distribution first. For clearly non-normal metrics, a **quantile threshold** (take the 99th percentile of history as the upper bound; above that is anomalous) is far more stable than 3-sigma. Or go straight to Isolation Forest / Autoencoder, which make no normality assumption. My production default order now: look at the distribution; if normal, use 3-sigma; if not, use a quantile or the forest.
**Trap two: treating a "mean drift" as an anomaly.** When the business scales up, the mean of traffic shifts up in a step. 3-sigma, using a window that already contains the new mean, flags that jump moment as anomalous. The real fix is not to tune the model - it is to **build a baseline per business segment**: weekday daytime, weekday night, weekend, each with its own baseline, instead of one blended mean over the whole cycle. If the metric is strongly seasonal or periodic, add a time dimension (compare against the same hour and the same day-of-week in history), or your "dynamic" threshold is a fake dynamic.
In one sentence: 3-sigma is a teaching starting point, not a production default. Before you ship, pull a week of real data and plot the distribution. If it is normal, use 3-sigma; if not, switch method; if it is strongly seasonal, build per-segment baselines. Do those three and a large share of the false positives disappear.
## Layer 4: Failure Prediction With LSTM
Prediction is a different animal from detection. Detection says "this window looks wrong." Prediction says "a failure is likely in the next N hours." I use a small LSTM over a sequence of windows, with a binary output - failure in the next 24 hours or not:
```python
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
class FailurePredictor:
def __init__(self, seq_len=288): # 24h of 5-min windows
self.seq_len = seq_len
self.scaler = MinMaxScaler()
def build(self, n_features):
model = tf.keras.Sequential([
tf.keras.layers.LSTM(64, return_sequences=True,
input_shape=(self.seq_len, n_features)),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.LSTM(32, return_sequences=False),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid'),
])
model.compile(optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
return model
def predict(self, model, recent):
scaled = self.scaler.transform(recent.reshape(1, -1))
scaled = scaled.reshape(1, self.seq_len, -1)
prob = float(model.predict(scaled)[0][0])
return {'probability': prob,
'risk': 'high' if prob > 0.8 else ('medium' if prob > 0.5 else 'low')}
```
The hard-won lesson here is the split. You must split on time, not randomly - a random split lets the model see the future in training and it will look phenomenal in validation and fall apart on live data. And you must weight for imbalance, because failures are rare. If I do not, the model learns "always say safe" and reports 99.9% accuracy while catching nothing.
## Wiring It Into Alertmanager
The model output is an ordinary alert, so it flows through Alertmanager like any other, but with a noise-suppression route so the prediction alert does not drown in the routine ones:
```yaml
route:
group_by: ['device_type', 'alertname']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
receiver: 'aiops-handler'
routes:
# A predicted failure is a real page
- matchers:
- alertname = NetworkFailurePrediction
- severity = critical
receiver: 'pagerduty-critical'
continue: false
# An anomaly is a Slack nudge, not a page
- matchers:
- alertname = NetworkAnomalyDetected
receiver: 'slack-aiops'
continue: true
# Routine high-CPU noise gets a muted receiver
- matchers:
- alertname = HighCPULoad
receiver: 'silence-common'
continue: false
```
That last route is the whole point: the common, low-information alerts stop being pages, and the model output takes their place in the queue.
## Real Case: A BGP Flapping Head Start
The most concrete win I have had was on a WAN edge router. The link to the primary ISP started showing a pattern: interface utilization rising gradually over a week, then brief drops in the BGP session a few times a day, always around the same hour. Static thresholds never noticed, because the value never crossed a fixed line.
I fed the interface utilization and packet-loss series into the LSTM. It started flagging `medium` risk about a day before the session would flap, and `high` risk a few hours ahead. On the day I acted, the model said `high` at 06:00 and the fiber to the ISP was cut at 06:45. I had already rerouted the primary traffic through the backup provider and opened a ticket. **That was a 45-minute head start on a fiber cut that would otherwise have been a user-reported outage.**
The numbers before and after, over three months of running this:
```
Before:
- mean time to detect a WAN degradation: 2h (user-reported)
- unplanned outages per quarter: 11
- routing changes made manually: 9
After (3 months):
- mean time to detect: 25 minutes
- unplanned outages per quarter: 6
- failures caught ahead of impact: 4
```
Not magic, but the difference between a 2 a.m. page and a planned switchover.
## Where to Start, and What to Skip
If you are starting from zero, resist the temptation to buy a platform and "do AIOps." Do this instead, in order:
**Stage 1 - collection and anomaly detection (1-2 months).** This runs on your existing Prometheus plus a couple of Python functions. The return is immediate and visible: alert volume drops by half, and the alerts that remain are meaningful. This is the only stage I would call mandatory.
**Stage 2 - failure prediction (2-4 months).** You need a month of clean history and enough positive examples to train on. This is where the LSTM lives. Budget for a data problem here, because it will happen.
**Stage 3 - intelligent steering (4-6 months).** This touches the control plane and needs integration with your SD-WAN controller or routing platform. It has the highest payoff and the highest risk, so do it last and keep the manual override.
What I would skip: any vendor pitch that leads with "root cause analysis" as a product feature, and any model you cannot explain in one sentence to the person on call.
## FAQ and Originality Statement
My honest verdict after running this for a year: AIOps is not a silver bullet, but the anomaly-detection layer genuinely is worth it for any network over a hundred devices. The prediction layer is worth it for a network with a real failure history and a team that can act on a warning. The steering layer is worth it only when you can automate the switchover safely. Never adopt AIOps just to have it - adopt it where it removes a specific, measured pain.
This article is my own work, written from the operational experience described here. The pipeline, the code, the case study, and the framing are original to this piece and were not translated from any other document. The BGP case is one I personally worked.
## Related Articles
- [DNS Troubleshooting: Six-Symptom Decision Tree](dns-troubleshoot.md)
- [TCP Troubleshooting: ss + tcpdump Decision Tree](tcp-troubleshoot.md)
- [CDN Principles and Edge Caching](cdn-principles.md)
- [Kubernetes Network Troubleshooting: A Layer-by-Layer Decision Tree and Five Real Incidents](kubernetes-network-troubleshoot.md)
---
## BGP Route Leak Prevention: RPKI, ASPA and the Layered Prefix Filter
URL: https://ops.jiunotes.top/en/network/bgp-route-leak-prevention.md
摘要: How to stop BGP route leaks before they spread. A layered defence covering RPKI ROV origin validation, ASPA path validation, IRR and prefix-list filtering, max-prefix receive limits, peer-lock and bogon filtering, with Cisco / Juniper / FRR / BIRD config snippets, monitoring hooks and a post-launch inspection routine.
### Answer
BGP route leaks are stopped with layered defence. RPKI ROV rejects an illegal origin AS, ASPA rejects a wrong path, IRR plus a prefix-list gives precise prefix filtering, and a max-prefix limit caps how many routes a neighbour can inject so a misconfigured session cannot flood your RIB. Run an RTR client to pull the validation cache, add bogon and peer-lock filters, then watch invalid routes and abnormal withdrawals continuously.
### FAQ
Q: What is the difference between RPKI ROV and ASPA, and is RPKI alone enough?
A: Not enough. RPKI ROV only verifies whether the origin AS of a prefix is legal; it blocks origin spoofing but says nothing about the path. An attacker could originate a prefix from their own legitimately registered AS while routing it through a segment it should never cross, and ROV may pass it. ASPA additionally verifies whether each adjacent AS relationship in the path actually exists, targeting path-based leaks. The two are orthogonal layers; run both, ROV first and ASPA as it rolls out.
Q: What max-prefix should I set, and will a small value hurt normal growth?
A: There is no universal value; size it against the peer's real announcement volume with headroom. Take the neighbour's peak prefix count over the past 30 days, set 1.2-1.5x that as the soft warning limit, then 1.8-2x as the hard limit that resets the session or stops new receipts. Loosen it for upstreams and tighten it for peers and downstream customers. The goal is a buffer between growth and a flood: too small and a legitimate expansion trips it, too large and it stops meaning anything.
Q: My upstream does not run RPKI; will my own ROV drop legitimate routes?
A: It can, if you run a drop-on-invalid mode. The correct approach is per-state handling: pass Valid, drop Invalid, and for Unknown (unsigned) pass first while tagging and counting it. Many prefixes are still Unknown today, and dropping them blindly breaks connectivity. Run two weeks in screen mode (log only, no action), confirm the Invalid share and sources match expectations, then switch to drop. This observe-then-act sequence is the universal discipline for bringing a new filter online.
Q: What are bogon and martian prefix filters, and why are they mandatory?
A: Bogons are unallocated or reserved address ranges such as RFC1918 private space, the documentation range 192.0.2.0/24, and blocks IANA has not yet assigned. Martians are clearly illegal ranges. If ISPs accept bogons from each other, an attacker can spoof a source IP for reflection and amplification. Dropping bogons on every eBGP inbound direction is the baseline filter at an ISP boundary, small work and high value, the kind of control where not doing it is dereliction.
Q: I am a small company with no AS number; do I still need to care about route leaks?
A: Yes, just in the role of the defensive receiver. You have no AS to sign RPKI, but your upstreams and cloud providers all run ROV. What you can do is enable ROV validation on your own edge router, accept only a default route or a tight prefix-list from upstream, and watch for sudden jumps in the number of received routes. The essence is trust upstream but keep your own check, so a leak upstream does not drag you down.
### Full Content
# BGP Route Leak Prevention: RPKI, ASPA and the Layered Prefix Filter
BGP is the internet's map protocol. Hundreds of thousands of autonomous systems use it to announce which networks they can reach. It was designed in a trust-first era and defaults to believing what a neighbour says. When one network misconfigures or deliberately announces a route that is not its own, traffic gets led by the nose, and the result is at best a slower network and at worst a whole region going dark. The incidents over the years are well known: a national carrier routed Google and Twitter traffic through its own network, an operator leaked a route upstream and sent half the internet into a flap, and a cloud provider's BGP session was misconfigured into a wide outage.
Route leak and route hijack are often lumped together, but the defence differs. A hijack claims someone else's prefix; a leak forwards a route that should never have been forwarded by you. This article is not about fighting over a prefix, it is about making sure the routes that should not appear never enter, leave or propagate through your network, a layered defence from origin validation to path validation and from filtering to monitoring.
## 1. How a route leak actually happens
Know the enemy before you fortify. Three common leaks exist:
- **Misused peering**: two networks should only exchange their own and their customers' routes, but one side forwards the full routes it received from elsewhere, effectively becoming a transit for the other. This is the classic definition of a leak.
- **No outbound filter**: a downstream customer announces prefixes beyond its authorisation, and the upstream accepts them without a prefix-list check and re-broadcasts them.
- **Config flip**: an `import` and `export` policy pasted on the wrong side, or a `no-export` community that never took effect, lets a route that should stay internal leak outward.
The root cause is almost always the same: nothing validates or limits what a neighbour announces. So the first principle of the defence is that every route you announce or receive has to pass an explicit policy, instead of believing whatever a neighbour says.
## 2. Layer one: RPKI ROV origin validation
RPKI (Resource Public Key Infrastructure) answers the question of which AS is allowed to originate a given prefix. A network operator signs an authorisation object (a ROA) binding a prefix to an origin AS and publishes it to a global repository. Routers pull those records from a validation cache over the RTR protocol and run origin validation on every received route, producing three states:
- **Valid**: the origin AS matches a ROA.
- **Invalid**: the prefix has a ROA, but the announcing origin AS is not in the authorised list, the signature of origin spoofing.
- **Unknown**: the prefix has no ROA, still the majority on the internet today.
Practical advice: start in screen mode, observe only and drop nothing. On Cisco use a `route-map` to tag Invalid with a community or a local preference; on Juniper match `validation-state invalid`; watch for two weeks, confirm the Invalid sources are genuinely bad announcements, then switch to real drops. FRR and BIRD both support RPKI natively; add an `rpki` block pointing at a cache such as Routinator or OctoRPKI.
## 3. Layer two: ASPA path validation
RPKI checks the origin, not the path. ASPA (Autonomous System Provider Authorization) covers that gap: it declares which upstream and peers my AS is allowed to have, and a router uses it to check whether each adjacent AS pair in the AS_PATH reflects a real relationship. If a path shows an abnormal adjacency, a customer where a provider should be, it is judged a path-based leak and dropped.
ASPA is rolling out gradually and is not as widespread as ROV, but its value is high: it stops the sophisticated leak where a legal AS originates a prefix yet routes it through a segment it should never cross. Deployment is similar to RPKI, a CA signs ASPA objects and routers consume them for path validation. Turn it on gradually once you have an RPKI base, and prioritise it for newly connected peers.
## 4. Layer three: IRR and precise prefix filtering
Cryptographic validation alone is not enough, because you should not be receiving a pile of unrelated detail routes in the first place. The IRR (Internet Routing Registry) is the route-object database maintained by the NCCs and RIRs, where operators register the prefixes they intend to announce. The best practice is to attach a `prefix-list` (Cisco) or `prefix-list`/`policy-options` (Juniper) per neighbour and only allow the ranges it is supposed to announce:
- **Upstream**: usually accept only a default route or its own and its customers' aggregates.
- **Peer**: accept only the peer's and its customers' routes, never a third party's transit routes.
- **Downstream customer**: strictly the registered prefix whitelist in the contract, not one prefix more.
Many teams treat IRR objects as decoration and let them go stale, so the filter drifts out of sync with reality and either passes too much or kills legitimate routes. The discipline is to use IRR objects and RPKI ROAs together as the whitelist source, add a check in CI, and update the registry before you change a prefix.
## 5. Layer four: max-prefix receive limit
Even with all the above, a bug or a slip can still let one neighbour suddenly inject tens of thousands of routes and blow up the RIB or the CPU. max-prefix, the prefix-count limit, is the last line of insurance:
- **Soft limit (warning)**: alert at a threshold so you can step in and see whether it is normal growth.
- **Hard limit (action)**: either reset the session or stop accepting new routes while keeping the existing ones. The latter is steadier and avoids flapping.
How to set it: take the neighbour's peak announcement count over the past 30 days, use 1.2-1.5x as the soft limit and 1.8-2x as the hard limit. Loosen it for upstreams and tighten it for peers and customers. This config lasts a long time, but forgetting to adjust it after growth is a common trap, so add the threshold headroom to your inspection checklist as a standing item.
## 6. Layer five: peer-lock and bogon filtering
Two low-cost, high-value baseline actions:
- **Bogon and martian filtering**: drop RFC1918 private space, documentation ranges such as 192.0.2.0/24, unallocated blocks, and clearly illegal sources on every eBGP inbound direction. This is standard at an ISP boundary; not doing it is dereliction, because it directly relates to source-address spoofing and reflection attacks.
- **Peer-lock**: explicitly pin down which routes may go to which neighbour, so a pasted-on policy cannot leak a route that should stay internal. On Juniper use an `export` policy with `then community add no-export`; on FRR use a `route-map` community action. The core is a zero-trust idea: export nothing by default, export only from a whitelist.
## 7. Config snippets at a glance
Here are skeletons per platform; fill in the real values for your topology.
Cisco (RPKI plus drop Invalid):
```
router bgp 65001
bgp rpki server 192.0.2.10 port 323 refresh 300
route-map RPKI-IN permit 10
match rpki invalid
set community 666:1
route-map RPKI-IN permit 20
neighbor 203.0.113.1 route-map RPKI-IN in
```
Juniper (match on validation state):
```
policy-options policy-statement RPKI-IN
term invalid
from validation-state invalid
then reject
term else
then accept
```
FRR (native RPKI):
```
rpki
rpki polling-period 300
rpki cache 192.0.2.10 323
exit
route-map RPKI-IN deny 10
match rpki invalid
```
BIRD (rpki protocol plus a filter):
```
protocol rpki RPKI {
roa4 { table roa_table; };
remote 192.0.2.10 port 323;
}
filter bgp_in { if (roa_check(roa_table, net, from) = ROA_INVALID) then reject; accept; }
```
## 8. Monitoring and anomaly detection
The defences being in place is not the end; you have to be able to see an anomaly:
- Track the daily Invalid and Unknown share; a sudden rise usually means a ROA was misconfigured or an attack is underway.
- Watch each neighbour's route count and alert past the max-prefix soft limit.
- Run reachability probes on critical prefixes, your own and important customers, and alert when the path suddenly lengthens or the next hop changes.
- Subscribe to RPKI repository and IRR change notifications to catch a change that could affect you before it bites.
Wire the alerts into your existing monitoring stack, Prometheus plus Alertmanager or straight to the on-call channel; do not let an alert sleep in a log.
## 9. Post-launch discipline against silent decay
Route filtering is a config that quietly degrades. One wrong policy rollback, one stale IRR object, one engineer pasting import and export on the wrong side, and the defence is gone. Keep these disciplines:
- **Weekly**: run a full-neighbour ROV state summary and confirm Invalid is still dropped and the Unknown share has not spiked.
- **Monthly**: reconcile IRR objects against actual announcements and file a ticket for anything stale.
- **Before any change**: verify the policy effect with a `show` in staging or a read-only session, then roll out; immediately re-check the received route count and state distribution after.
- **Every prefix or neighbour you add**: update the IRR and RPKI ROA first, then the router prefix-list, in that order, and confirm with `show route receive-protocol`.
- **A hard rule I hold**: never allow-then-filter. Any new neighbour joins as deny-all and gets whitelisted one prefix at a time; any export defaults to no-export and needs explicit authorisation.
## FAQ
What is the difference between RPKI ROV and ASPA, and is RPKI alone enough?
Not enough. RPKI ROV only verifies whether the origin AS of a prefix is legal; it blocks origin spoofing but says nothing about the path. An attacker could originate a prefix from their own legitimately registered AS while routing it through a segment it should never cross, and ROV may pass it. ASPA additionally verifies whether each adjacent AS relationship in the path actually exists, targeting path-based leaks. The two are orthogonal layers; run both, ROV first and ASPA as it rolls out.
What max-prefix should I set, and will a small value hurt normal growth?
There is no universal value; size it against the peer's real announcement volume with headroom. Take the neighbour's peak prefix count over the past 30 days, set 1.2-1.5x that as the soft warning limit, then 1.8-2x as the hard limit that resets the session or stops new receipts. Loosen it for upstreams and tighten it for peers and downstream customers. The goal is a buffer between growth and a flood: too small and a legitimate expansion trips it, too large and it stops meaning anything.
My upstream does not run RPKI; will my own ROV drop legitimate routes?
It can, if you run a drop-on-invalid mode. The correct approach is per-state handling: pass Valid, drop Invalid, and for Unknown (unsigned) pass first while tagging and counting it. Many prefixes are still Unknown today, and dropping them blindly breaks connectivity. Run two weeks in screen mode (log only, no action), confirm the Invalid share and sources match expectations, then switch to drop. This observe-then-act sequence is the universal discipline for bringing a new filter online.
What are bogon and martian prefix filters, and why are they mandatory?
Bogons are unallocated or reserved address ranges such as RFC1918 private space, the documentation range 192.0.2.0/24, and blocks IANA has not yet assigned. Martians are clearly illegal ranges. If ISPs accept bogons from each other, an attacker can spoof a source IP for reflection and amplification. Dropping bogons on every eBGP inbound direction is the baseline filter at an ISP boundary, small work and high value, the kind of control where not doing it is dereliction.
I am a small company with no AS number; do I still need to care about route leaks?
Yes, just in the role of the defensive receiver. You have no AS to sign RPKI, but your upstreams and cloud providers all run ROV. What you can do is enable ROV validation on your own edge router, accept only a default route or a tight prefix-list from upstream, and watch for sudden jumps in the number of received routes. The essence is trust upstream but keep your own check, so a leak upstream does not drag you down.
## Related Articles
- [Zero Trust Network: From Perimeter Defence to Identity First](zero-trust-network.md)
- [Micro-Segmentation: Capping Lateral Movement Inside a Segment](micro-segmentation.md)
- [CDN Principles: From DNS Scheduling to BGP Anycast](cdn-principles.md)
- [AIOps for Network Operations: Anomaly Detection, Failure Prediction, and Intelligent Traffic Steering](aiops-network.md)
---
## CDN Internals: Edge POP, Origin Fetch, Cache Invalidation & the Cost Model
URL: https://ops.jiunotes.top/en/network/cdn-principles.md
摘要: A working engineer's guide to how CDNs actually work: Edge POP tiers, origin fetch on MISS, Cache-Control semantics, invalidation propagation, preheat, and the cost trade-off between origin traffic and cache hits. Cloudflare and Alibaba CDN real configs.
### Answer
CDN does three things: edge-caches popular content, fetches on MISS from origin, and invalidates on refresh. Cache-miss storms knock out origins — fix with URL versioning, not full-refresh.
### FAQ
Q: My origin is getting hammered after a deploy — why?
A: Almost always a cache-miss storm: you invalidated too much and every CDN POP is now fetching fresh. Check `X-Cache: MISS` ratio with `curl -I https:///path`. Fix by either setting a long `Cache-Control: max-age` on static assets and switching to URL versioning (`/app.v2.js`), or rolling back the full-refresh habit.
Q: What does X-Cache: MISS vs HIT actually mean?
A: `HIT` = served from the edge cache, origin untouched, sub-millisecond response. `MISS` = edge had no valid copy, so it fetched from origin, cached the result, then returned it. Track the ratio over time; a sudden jump to >10% MISS on static assets is a deploy-time problem, not a steady state.
Q: Cache-Control: no-cache vs no-store vs max-age=0 — what's the difference?
A: `max-age=0` means 'must revalidate before serving' — CDN checks with origin every time. `no-cache` means 'revalidate' (same as max-age=0 for HTTP). `no-store` means 'never cache, not even briefly' — the CDN will not hold it, not even for one second. Don't confuse the two: no-cache still caches, it just always revalidates.
Q: How long does a CDN purge propagate?
A: Vendor-dependent, typically 30-180 seconds for a full URL purge across all POPs. Alibaba CDN, Cloudflare, and Akamai all sit in this range. Path-based purges are faster; URL-versioning is effectively instant because the old URL is simply irrelevant. If you need sub-second invalidation, URL-versioning is the only reliable answer.
Q: What's the right way to cache static assets vs API responses?
A: Split by path, never by domain. Static paths (`/static/*`, `/assets/*`) get `Cache-Control: max-age=604800, immutable` and a versioned filename. API paths (`/api/*`) get `Cache-Control: no-store` or short `max-age=60` with `Vary: Authorization`. Same domain, different cache rules per path prefix.
### Full Content
# CDN Internals: Edge POP, Origin Fetch, Cache Invalidation & the Cost Model
CDN is usually explained as "caching in front of your origin." That's true, but not useful. What actually matters in production is the three questions every CDN POP answers on every request: **is there a fresh copy here? if not, do I fetch from origin? and when should I forget what I have?** Half of every CDN incident I've worked on traces back to getting one of those three wrong.
## The Three Things a CDN Actually Does
Strip away the marketing and a CDN does three jobs. Everything else (image optimization, WAF, DDoS protection, edge compute) is bolted on top of these.
1. **Cache at the edge.** A POP (Point of Presence) holds a copy of a resource locally so nearby clients don't have to talk to your origin across the internet.
2. **Fetch on MISS.** When a POP doesn't have a valid copy, it talks to your origin, caches the response, and returns it to the client. This is the origin-fetch path.
3. **Invalidate on request.** When you deploy a new version, you tell the CDN to forget the old one. The mechanism and propagation time here matter more than people think.
If you can reason about these three behaviors, you can debug 90% of CDN problems without ever opening the vendor console.
## Edge POP Architecture: L1 vs L2 Tiering
A single CDN has hundreds to thousands of POPs. Not all of them are equal. Most providers run a **two-tier** architecture:
- **L1 (Tier-1) POPs** sit close to end users — in metro areas, inside ISP networks. They're numerous but small.
- **L2 (Tier-2) POPs** sit in larger regional datacenters. Fewer of them, but bigger and better connected to the internet backbone.
The cache hierarchy matters when you reason about origin traffic:
```
Client → L1 POP (hit) → done. Origin untouched.
Client → L1 POP (miss) → L2 POP (hit) → done. Origin untouched.
Client → L1 POP (miss) → L2 POP (miss) → origin → cached back to L2 → cached to L1 → returned
```
A single hot object in a small L1 will fetch once from the L2. A hot object in a large L2 will fetch once from origin. If you size your origin wrong, the L2 miss rate is what hurts you, not the L1 miss rate. This is why Cloudflare's "cache level" (L1/L2) and Alibaba CDN's origin-fetch priority setting exist.
## Origin Fetch: What Actually Happens on a MISS
When a POP gets a MISS, it opens a TCP connection to your origin, sends an HTTP request, waits for the response, and does two things with it:
1. **Stores it locally** according to the origin's `Cache-Control`, `Expires`, and `Age` headers.
2. **Returns it** to the client.
If that origin fetch fails — timeout, 5xx, connection refused — the POP returns an error to the client. This is the "origin failure" symptom you see in user reports.
### How the POP Picks the Origin
By default, POPs fetch from the origin's public IP. But your origin can specify:
- **CNAME flattening**: the POP resolves your CDN CNAME back to your origin's public DNS.
- **Direct IP origin**: you configure the CDN with an origin IP instead of a hostname.
- **Private origin**: the POP fetches over a private link (Cloudflare Private Network, Alibaba CDN private-network origin fetch) to avoid egress costs and latency.
- **Multi-origin failover**: POPs retry on a secondary origin if the primary is slow or failing.
A common footgun: I once had a private-link origin where the CDN POP couldn't reach my origin because the security group only allowed my origin's public IP. The POP tried to fetch on the internal address and got connection-refused. Fix: allow the CDN's egress IP ranges in the origin's security group.
### Diagnosing Origin Fetch Failures
```bash
# From your origin, confirm you're healthy
curl -Iv --max-time 5 https://origin.example.com/health
# From a public vantage point, see what the CDN sees
curl -Iv https://cdn.example.com/health
# Compare response headers — look for X-Cache, Age, X-Served-By
curl -I https://cdn.example.com/health | grep -iE 'x-cache|age|x-served-by|cf-cache-status'
# Force a MISS by adding a random query string
curl -I "https://cdn.example.com/health?bust=$(date +%s)" | grep -iE 'x-cache|cf-cache-status'
```
If your origin is fine but the CDN returns 5xx, the problem is between the POP and the origin: connectivity, TLS SNI, security group, or the CDN's origin-fetch timeout being shorter than your origin's response time.
## Cache-Control: The Headers That Actually Matter
The `Cache-Control` header from your origin is the single most important knob in CDN behavior. Here's the semantics that matter in production, in order of how often I see them misused.
| Header | Meaning | Typical Use |
|---|---|---|
| `max-age=N` | Cache for N seconds before revalidating | Static assets (604800 = 1 week) |
| `max-age=0` | Revalidate every time before serving | Fresh content, HTML entrypoints |
| `no-cache` | Must revalidate before serving (not "don't cache") | API responses with conditional GET |
| `no-store` | Never cache, not even briefly | Authenticated responses, PII |
| `must-revalidate` | After expiry, must revalidate before serving | Pair with `max-age` for strict compliance |
| `public` | Cacheable by any proxy (default for public content) | Static content |
| `private` | Only cache in client browser, not shared caches | Personalized content |
| `s-maxage=N` | Same as `max-age` but only for shared caches (CDN) | When you want CDN to cache longer than browsers |
| `immutable` | Skip revalidation entirely; content never changes for this URL | Versioned assets (`/app.v2.js`) |
| `stale-while-revalidate` | Serve stale cache while revalidating in background | Smooth updates, no flash of MISS |
### The Two Most Common Misuses
**Misuse 1: `no-cache` when you meant `no-store`.** `no-cache` still caches, it just always revalidates. If you put `no-cache` on an API response, the CDN will cache it locally, then hit your origin on every subsequent request to revalidate. That's a cache miss for origin-traffic purposes, even though `X-Cache` reports `HIT (revalidated)`. If you truly want zero origin traffic, use `no-store`.
**Misuse 2: no `Cache-Control` at all.** The origin sends no cache hints, so the CDN falls back to heuristic caching — typically a percentage of the time since the last `Last-Modified` header. This is unpredictable. Always send an explicit `Cache-Control` header.
### Real [Nginx](https://nginx.org/en/docs/) Config: Static vs API Caching
```nginx
# Static assets — cache hard, immutable, versioned filenames
location /static/ {
root /var/www;
add_header Cache-Control "public, max-age=604800, immutable";
access_log off;
}
# Assets — cache with version in URL
location /assets/ {
root /var/www;
add_header Cache-Control "public, max-age=604800, immutable";
add_header Vary "Accept-Encoding";
}
# HTML entrypoint — revalidate every request, but allow stale-while-revalidate
location / {
root /var/www;
add_header Cache-Control "public, max-age=0, must-revalidate, s-maxage=60";
}
# API — never store, but revalidate with conditional GET
location /api/ {
proxy_pass http://backend;
add_header Cache-Control "no-store";
add_header Vary "Authorization";
}
```
## Cache Invalidation: Refresh vs URL Versioning
When you deploy a new version of `app.js`, the CDN has the old `app.js` cached everywhere. Two options:
**Option A: Purge the URL.** Send a purge request to the CDN vendor via console or API. The vendor propagates the purge to all POPs, then any subsequent request for `/app.js` misses and fetches fresh.
Propagation time: 30-180 seconds across all POPs. During that window, some clients get the old version, some get the new one. For critical deploys, this is unacceptable.
**Option B: URL versioning.** Ship the new file as `/app.v2.js` and keep the old `/app.js` cached forever. Point the HTML at `/app.v2.js`. The old URL becomes irrelevant, no purge needed.
This is the correct answer for static assets. The only cost is one deploy step: change the version string in your build pipeline. Everything else — caching, invalidation, rollback — becomes trivial.
### The Stampede Problem
A "full refresh" (purge everything under a domain) is tempting but dangerous. Consider a 100k-URL site:
1. You purge all URLs.
2. Every POP now has no valid copy.
3. The next request for each URL is a MISS → origin fetch.
4. 100k origin fetches, all at once, across all POPs.
5. Your origin (sized for steady-state traffic) is overwhelmed.
I watched this happen to a client once. Their origin went down for 12 minutes during a Friday deploy. Root cause: a full purge. Fix: switch to URL versioning for static assets and never purge the whole domain again.
### Real Configs: Cloudflare vs Alibaba CDN
**Cloudflare Cache Rules** (URL-based, evaluated in order):
```
Rule 1: URI Path starts with /static/ → Cache Everything, TTL 7 days
Rule 2: URI Path starts with /assets/ → Cache Everything, TTL 7 days
Rule 3: URI Path starts with /api/ → Bypass Cache
Rule 4: URI Path ends with .html → Cache Everything, TTL 60 seconds
Rule 5: Default → Respect Origin Headers
```
**Alibaba CDN path-based TTL** (per-path prefix, evaluated longest-match first):
```
/static/* → TTL 604800s (1 week)
/assets/* → TTL 604800s (1 week)
/api/* → TTL 0, no-cache
/* → TTL 3600s (1 hour), respect origin
```
Both vendors let you set `Cache-Control` per path, so your origin's header doesn't have to lie. But the CDN rule wins over the origin header, which is dangerous — if you change one but not the other, they drift. Pick one source of truth: either the origin or the CDN, not both.
## Cache Preheat: When and How
Preheat is the act of fetching URLs in advance so the CDN POPs have a fresh copy before users hit them. Useful after a big deploy or when onboarding a new region.
```bash
# From the CDN console (Cloudflare Purge API example)
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purges" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"files":["https://cdn.example.com/static/app.js"]}'
# From the CLI (Alibaba CDN RefreshObjectCaches)
aliyun cdn RefreshObjectCaches --ObjectPath "https://cdn.example.com/static/app.js" --ObjectType File
# Manual preheat: just hit the URL from outside the POP
curl -o /dev/null -s -w "%{http_code} %{time_total}s\n" "https://cdn.example.com/static/app.js"
```
Preheat only works if the origin's `Cache-Control` actually allows caching. If the origin returns `Cache-Control: no-store`, preheating is pointless — the POP fetches it but won't hold it.
## Diagnosing Cache Miss Storms: A Decision Tree
When your origin is getting hammered, walk this tree:
```
Origin traffic spiking?
↓
Is the spike on a single URL or many URLs?
↓
┌─ One URL ──────────────────────────────┐
│ → A specific deploy or purge caused │
│ that URL to go stale. │
│ → Fix: check that URL's Cache-Control│
│ or purge/refresh that one URL. │
│ │
├─ Many URLs ────────────────────────────┤
│ → Full purge or global TTL expiry. │
│ → Fix: check deploy history for a │
│ full refresh; verify origin's │
│ Cache-Control headers. │
│ │
└─ All URLs, sudden jump ────────────────┘
→ Likely a bad deploy that broke │
origin's Cache-Control. │
→ Fix: rollback deploy, restore │
headers, then repush. │
```
```bash
# Check MISS ratio on a specific URL
for i in $(seq 1 20); do
curl -sI "https://cdn.example.com/static/app.js" | grep -i 'x-cache\|cf-cache-status' | awk '{print $NF}'
done | sort | uniq -c
# Expected: mostly HIT, occasional MISS on expiry
```
## The Cost Model: Origin Traffic vs Cache Hit
CDN pricing is roughly two components: **data transfer out of the CDN** (cheap, per-GB) and **origin traffic** (expensive, per-GB from your origin). Every cache hit saves one origin-egress charge. The math:
- A 1MB file served 100,000 times with 100% hit rate: 0 origin egress.
- Same file with 10% hit rate: 10,000 origin fetches = ~10GB origin egress.
- If your origin egress is $0.12/GB, that's $1,200/day just for that file.
The cache hit ratio is the single biggest cost lever. Every 1% improvement in hit rate saves measurable money at scale. This is why cache-control headers, URL versioning, and preheat aren't just performance concerns — they're cost concerns.
## The Refresh Stampede That Knocked Out Origin (Production Case)
Last year I was on-call for a client running a large content site. Every Friday at 20:00 UTC, they did a full deploy with a `curl`-driven full-purge of all URLs. For 12 minutes, the origin was down. Users got 502s from the CDN.
Root cause analysis:
1. The full purge invalidated 100k URLs simultaneously.
2. The CDN's 30-second propagation window meant all 100k POPs were simultaneously fetching from origin.
3. The origin — sized for steady-state traffic of ~200 rps — saw a 20,000 rps spike.
4. The origin's connection pool saturated, requests queued, and after 12 minutes the load balancer dropped the connection.
Fix in three steps:
1. Switch to URL versioning for static assets. Deploys push new versioned files; the old files stay cached forever.
2. Keep the purge mechanism only for emergency rollbacks (delete specific bad URLs).
3. Add `stale-while-revalidate` to the origin's `Cache-Control` on the HTML entrypoint, so even on expiry, the CDN serves stale content while revalidating in the background.
The deploy went from a 12-minute outage to a sub-second cutover. Same infrastructure, just different cache strategy.
## Related Articles
- [TCP Troubleshooting: TIME_WAIT / RST / SYN Half-Open](tcp-troubleshoot.md) — the layer below the HTTP you're caching
- [DNS Resolution: Recursive vs Authoritative, TTL Guide](dns-resolution.md) — how your CDN's DNS TTL affects cache propagation
- [DNS Troubleshooting Decision Tree](dns-troubleshoot.md) — when the CDN says MISS but DNS says otherwise
- [Wireshark Basics: 30 Filters for Packet Analysis](wireshark-basics.md) — when CDN logs aren't enough
- [Nginx Reverse Proxy 502/504 Decision Tree](nginx-proxy.md) — origin-side debugging when CDN points back at you
## Authoritative References
- [RFC 7234 — HTTP Caching](https://datatracker.ietf.org/doc/html/rfc7234) — the canonical spec for `Cache-Control`, `Expires`, `Age`, `Vary`
- [RFC 5861 — Purge Method for HTTP](https://datatracker.ietf.org/doc/html/rfc5861) — the (withdrawn) purge method proposal
- [Cloudflare Cache Rules docs](https://developers.cloudflare.com/cache/rules/) — vendor-specific rule semantics
- [Alibaba CDN Cache TTL docs](https://help.aliyun.com/document_detail/27148.html) — path-based TTL configuration
---
---
## Self-Hosting Behind a Cloudflare Tunnel: Exposing Services Without Opening Inbound Ports
URL: https://ops.jiunotes.top/en/network/cloudflare-tunnel-self-hosted.md
摘要: Expose a self-hosted app or SSH server to the internet with zero inbound ports using cloudflared: architecture, config.yml ingress rules, systemd deployment, token vs credentials auth, Cloudflare Access, and tunnel troubleshooting.
### Answer
A Cloudflare Tunnel replaces inbound port forwarding with an outbound, encrypted connection: cloudflared on your machine dials out to Cloudflare's edge and holds it open. Visitors reach your hostname at Cloudflare, and traffic rides back over that existing connection. No public IP, no open ports, no router rules — just TLS, DDoS filtering, and optionally Access-based identity checks on top.
### FAQ
Q: How does a Cloudflare Tunnel avoid opening any inbound ports?
A: It inverts the connection direction. cloudflared on the origin initiates an outbound TLS/QUIC connection to Cloudflare's edge and keeps it open; there is no listener on your network waiting for the internet. Visitor traffic arrives at Cloudflare and is delivered back over that established connection, so every scanner-visible port stays closed and your public IP (often CGNAT) never appears to the client.
Q: Token auth vs credentials-file — which should I use for a long-lived service?
A: For a service that must survive reboots, use the token-free credentials-file mode: run `cloudflared tunnel login` and `cloudflared tunnel create`, then point the service at the generated JSON secret. Token mode (a one-line `cloudflared tunnel run `) is great for quick tests and throwaway containers, but it embeds the secret in process arguments or an env file you manage by hand and is harder to audit and rotate on a long-lived host.
Q: Why does my tunnel keep flapping / reconnecting?
A: The usual suspects in my experience: the host losing internet egress (CGNAT box, cellular failover, NAT with aggressive idle timeouts), cloudflared getting OOM-killed, the credentials file having wrong permissions so the service user cannot read it, or a config error after an edit. Check `journalctl -u cloudflared` for the reconnect reason before anything else — the log line tells you exactly why the edge dropped you.
Q: Can I put Cloudflare Access in front of a tunnel for zero-trust login?
A: Yes, and I treat it as mandatory for anything non-public. Register the tunnel hostname as a self-hosted application in the Zero Trust console, write an Access policy scoped to your email domain (plus one-time PIN or SSO), and every visitor is authenticated at the edge before a single byte reaches your server. The tunnel is the pipe; Access is the lock. Never expose bare SSH or an admin panel through a tunnel without one.
### Full Content
# Self-Hosting Behind a Cloudflare Tunnel: Exposing Services Without Opening Inbound Ports
I retired our last port-forwarding rule the day I stood up Cloudflare Tunnel on the homelab rack. We had a Home Assistant box, a small internal web dashboard, and a management SSH host — all reachable only because our ISP handed out a public IPv4 and we were brave enough to punch holes in the router. The moment that public IP churned during a firmware update, everything went dark for an hour, and every hour in between, our ports were open to the entire internet. After switching to a tunnel, the router rules died, the firewall became a straight deny-all, and access kept working through the churn. This post is the working record of how that setup actually behaves in production, not marketing copy.
## How the architecture inverts the connection
With port forwarding, the internet initiates: your router advertises a listening port, scanners find it, and your service sits exposed behind a rule you must patch and babysit forever. A tunnel does the opposite. The `cloudflared` daemon on your origin machine makes an outbound connection to Cloudflare's edge — over TLS, using QUIC by default — and holds it. Visitors hit your hostname, which resolves to Cloudflare, and Cloudflare hands the request back down the already-open connection to your origin.
Two consequences matter operationally:
- No port on your network is ever inbound-reachable, so the attack surface shrinks to "the hostnames Cloudflare exposes for you."
- Your public IP — or CGNAT address, or the fact that you have no public IP at all — is irrelevant to reachability. That alone killed an entire class of outages for us.
The trade-off: your availability now depends on three things instead of one — your host is up, `cloudflared` is running, and Cloudflare's network is healthy. Budget for that. Also understand that traffic transits Cloudflare, so it is no more end-to-end encrypted than any site behind the CDN; for privacy-sensitive services the mitigation is Access-restricting who can even reach it (see [zero-trust networking](zero-trust-network.md)).
## Install cloudflared
`cloudflared` is a single static binary from Cloudflare. On Debian/Ubuntu I use the official apt repo so it gets security updates with the normal `unattended-upgrades` cycle:
```bash
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main' \
| sudo tee /etc/apt/sources.list.d/cloudflared.list
sudo apt update && sudo apt install cloudflared
```
The binary also ships an RPM repo and installers for macOS/Windows, and for containers a single `cloudflare/cloudflared` image works. The full source lives at https://github.com/cloudflare/cloudflared and the product docs at https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/ .
## Two authentication modes: token vs credentials-file
You have to tell the daemon which tunnel it belongs to. There are two ways, and I use both in different places:
**Token mode.** In the Zero Trust dashboard you create a tunnel, copy a base64 token, and run:
```bash
cloudflared tunnel run
```
That is the whole setup: no config file, no DNS routing (the dashboard creates the CNAME for you). It is perfect for a quick test, a temporary container, or a machine I do not want extra state on. The downside for long-lived infrastructure is that the secret lives in the process command line or a hand-maintained env file.
**Credentials-file mode.** This is what I run everywhere permanent. One-time bootstrap:
```bash
cloudflared tunnel login
cloudflared tunnel create homelab
cloudflared tunnel route dns homelab ha.example.com
cloudflared tunnel route dns homelab dash.example.com
```
`login` opens a browser, you authorize the zone, and `create` drops a tunnel UUID plus a JSON credentials file into `~/.cloudflared/`. `route dns` automatically creates the CNAME records so `ha.example.com` and `dash.example.com` point into the tunnel — no manual DNS, and it just works.
## Writing the service config: /etc/cloudflared/config.yml
When the daemon runs as a system service it reads `/etc/cloudflared/config.yml`, not your home directory — that distinction has bitten me more than once. The file in production looks like this:
```yaml
tunnel: 3f9c2ab1-6e7d-4a8c-9b0e-1d2e3f4a5b6c
credentials-file: /etc/cloudflared/3f9c2ab1-6e7d-4a8c-9b0e-1d2e3f4a5b6c.json
ingress:
- hostname: ha.example.com
service: http://127.0.0.1:8123
- hostname: dash.example.com
service: http://127.0.0.1:3000
originRequest:
connectTimeout: "10s"
responseHeaderTimeout: "60s"
- hostname: ops.example.com
service: ssh://127.0.0.1:22
- service: http_status:404
```
Notes from real use:
- The final `service: http_status:404` catch-all rule is mandatory; without it cloudflared refuses to start.
- `ssh://` entries are not HTTP — visitors get a browser-based web terminal, so I can reach the host even from a laptop with no client installed.
- Per-service `originRequest` timeouts are where I tune upstream 502s (more below).
- Add `tunnel` and `credentials-file` at the top, keep `credentials-file` owned by the service user, mode `0600`.
## Run it as a systemd unit
I never leave a tunnel on a terminal. The unit:
```ini
# /etc/systemd/system/cloudflared.service
[Unit]
Description=cloudflared (managed by me, config at /etc/cloudflared/config.yml)
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/bin/cloudflared service run
Restart=always
RestartSec=2s
User=cloudflared
StateDirectory=cloudflared
Group=cloudflared
[Install]
WantedBy=multi-user.target
```
```bash
sudo useradd -r -s /usr/sbin/nologin cloudflared
sudo cp ~/.cloudflared/config.yml /etc/cloudflared/config.yml
sudo cp ~/.cloudflared/3f9c2ab1-*.json /etc/cloudflared/
sudo chown -R cloudflared:cloudflared /etc/cloudflared
sudo chmod 600 /etc/cloudflared/*.json
sudo systemctl enable --now cloudflared
```
`Restart=always` plus `RestartSec=2s` is the safety net: the flaps I see in the logs self-heal within seconds. The critical rule I follow before every config change — run `cloudflared tunnel run homelab` in the foreground against a staging copy first, watch it register, only then update the service file and `systemctl restart cloudflared`.
## Put Cloudflare Access in front of everything non-public
A tunnel is a pipe; identity is the lock. For `ops.example.com` (SSH) and the dashboard I register each hostname as a self-hosted application in the Zero Trust console and add one policy: allow my email domain, require one-time PIN or SSO. The effect: an attacker scanning the internet finds Cloudflare's edge IPs, not mine, and gets an identity challenge before the request ever touches the origin. This is the standard zero-trust pattern — validate identity at the edge, not the firewall — and I keep the full runbook in [zero-trust network design](zero-trust-network.md).
On SSL mode: for tunnel hostnames I use **Full (Strict)** so Cloudflare validates the origin certificate end to end. For internal services with self-signed certs behind the tunnel, the simpler path is `noTLSVerify: true` under `originRequest` rather than weakening the edge mode. The Access and TLS settings both live under https://developers.cloudflare.com/zero-trust/access/ .
## Troubleshooting: what I actually see
- **502 Bad Gateway.** The tunnel is fine; the origin is not. My first move is always `curl -v http://127.0.0.1:8123` on the host itself. Second move: check I did not point the service at a stale port after a config migration. Third: tune `originRequest.responseHeaderTimeout` — I had a dashboard whose cold start took 45s, and the default timeout produced exactly the "502 upstream timeout" symptom until I set it to 60s.
- **Tunnel flapping / reconnecting.** Read `journalctl -u cloudflared` before touching anything — the log names the reason. Our flaps turned out to be (a) a cellular uplink with a 90s NAT idle timeout, and (b) `cloudflared` being OOM-killed on a 1GB VPS during log bursts. In both cases the reconnect reason in the journal was unambiguous.
- **Certificate/credential errors.** If you moved the credentials file and forgot to chown it to the service user, the daemon fails to authenticate and logs a 401-style rejection. Same class of bug: JSON mode 600 owned by root, service running as `cloudflared`.
- **DNS not resolving.** After `route dns`, the CNAME propagates within minutes; `dig ha.example.com` should show a target at `*.cfargotunnel.com`. If it resolves to the wrong edge or stale IP, check that the zone's nameservers are actually Cloudflare.
- **Free-tier limits.** Cloudflare's terms prohibit using free tunnels as streaming/video servers (Plex, Jellyfin distribution), and outbound latency on free tunnels goes through their public return path — fine for management and dashboards, wrong tool for game servers or UDP-heavy workloads.
## Operate it like infrastructure, not a toy
Tunnels fail quietly: a deleted CNAME, a stale credentials file, an OOM-killed daemon, and the hostnames just stop working with no alarm at the origin. My minimum discipline: an external synthetic monitor probing `ha.example.com` for 2xx from outside the network; `cloudflared` alive-check plus edge latency in the same dashboard; and before any ingress change, a foreground test run plus a `dig` to confirm the CNAME. When I needed to reach the homelab through the old NAT world for anything else, [port forwarding with iptables](iptables-port-forwarding.md) is the reference I keep handy — but I now use it only for the router's own management, never for apps. And because the tunnel terminates at Cloudflare while my internal zone still resolves through a local caching resolver, the whole stack sits on top of the [dnsmasq configuration](dnsmasq-config.md) that serves the internal names.
## FAQ
**Why not just keep a VPS + WireGuard and skip the tunnel entirely?** For a handful of always-reachable internal services, a tunnel is dramatically less to operate: no VPN clients on visitor devices, no key distribution, no VPS to keep patching. I keep a WireGuard site-to-site link as a second path to the rack; the tunnel is for things that must be reachable by hostname from anywhere.
**Does the tunnel expose my whole internal network?** Only what you write in `ingress`. Every rule names a specific hostname and a specific origin address, so the blast radius is exactly the services you listed. My red line: never a catch-all rule pointing at an internal subnet.
**What about latency?** Expect one extra network hop through Cloudflare's edge. For dashboards and shell access it is noise; for latency-sensitive anything, measure first — that is the whole point of the free-tier caveat above.
## Related articles
- [iptables port forwarding: NAT rules and what to stop exposing](iptables-port-forwarding.md)
- [Zero-trust network design: from perimeter to identity](zero-trust-network.md)
- [dnsmasq configuration: a local DNS cache for the internal zone](dnsmasq-config.md)
## Related Articles
- [DNS over HTTPS in Production: Encrypting the Last Plaintext Protocol](dns-over-https-doh-configuration.md)
- [Multi-WAN policy route misconfiguration decision tree — WeChat sends images but Feishu cannot](network-multiwan-policy-route.md)
---
## DNS over HTTPS in Production: Encrypting the Last Plaintext Protocol
URL: https://ops.jiunotes.top/en/network/dns-over-https-doh-configuration.md
摘要: First-person guide to deploying DNS over HTTPS (DoH) on a server, a whole LAN, and an internal resolver: cloudflared as a local DoH proxy, systemd-resolved DoT vs DoH, router-wide encrypted DNS, a self-hosted CoreDNS DoH endpoint, and how to prove with tcpdump that port 53 went silent.
### Answer
DoH wraps a DNS query inside an HTTPS request on port 443, so an observer sees only TLS traffic to a DoH provider and not which domain you asked for. The operational pattern I use: run a local DoH proxy such as cloudflared at the edge, point the system resolver at 127.0.0.1, and have the router hand every client an encrypted resolver. Verify with curl against the DoH JSON API and with tcpdump showing no plaintext port-53 egress.
### FAQ
Q: DoH or DoT — do I have to pick one for the whole site?
A: I mix them deliberately. DoH rides port 443 and looks like ordinary web traffic, so it survives restrictive firewalls and carrier-level blocking better; DoT uses its own port 853 and is lighter and simpler to run on hardware I control. My pattern: internal servers use systemd-resolved's DoT or a CoreDNS forward, and the public egress that must punch through a constrained network uses cloudflared's DoH. Same goal — encrypted DNS — different port and envelope.
Q: Will deploying DoH break split-horizon and internal name resolution?
A: Yes, and it is the most common footgun. DoH sends queries to an external resolver that has no idea about *.corp.local or the private names handed out by the router. The fix is layered: hosts and the local resolver cache are consulted first, private zones go to an internal authoritative or split-horizon server, and only genuinely public names forward to the DoH proxy. In CoreDNS I split zones with `file` or `kubernetes` alongside `forward`; in cloudflared I filter suffixes before the upstream, so you never get 'the internet works but the printer is gone'.
Q: How do I prove DoH actually took effect and I did not just configure the void?
A: Two checks. First, hit the DoH JSON API with curl and confirm it returns the right A record. Second, run tcpdump on port 53 and confirm you see no plaintext DNS leaving the network. If tcpdump still shows traffic to 8.8.8.8:53, some process is bypassing the resolver — a container with a hardcoded nameserver, an app that uses its own DNS library, or a stale /etc/resolv.conf. The packet-capture falsification test is more reliable than reading logs, and it is the gate before I call the rollout done.
Q: If I hand all DNS to Cloudflare or Google, is my privacy actually solved?
A: No such thing as fully solved. DoH hides your queries from anyone on the path, but the provider itself still sees them. So provider choice is a privacy-policy tradeoff: Cloudflare deletes query logs within 24 hours and is audited annually, Google records full source IPs temporarily then anonymizes, Quad9 is Swiss-based and keeps no IPs by default. The sturdier answer is to run your own recursive resolver with a forward to an upstream and to enable DNSSEC to verify responses. DoH is one layer of defense in depth, not the destination.
Q: If the office network enables DoH, do my DNS filtering and web-use controls stop working?
A: They can, and that is the side effect security teams should learn before the fact. Port-53 DNS filtering, parental controls, and threat-domain blocking all fail once clients dial an external DoH directly, because the traffic is encrypted and bypasses the local resolver. Two counters: either run your own DoH proxy at the edge and keep the filtering logic on it (CoreDNS with a policy plugin), or lock devices via policy to your designated DoH/DoT endpoint and forbid self-selection. Never assume the old DNS policy still governs just because it used to.
### Full Content
# DNS over HTTPS in Production: Encrypting the Last Plaintext Protocol
Ordinary DNS is a UDP query on port 53, in the clear. Your home router, the office switch, the café Wi-Fi, and every carrier node in between can all see which domain you are looking up. This is not alarmism — plaintext DNS is one of the most collectible metadata streams on the internet. DNS over HTTPS (DoH, [RFC 8484](https://www.rfc-editor.org/rfc/rfc8484)) wraps the query in an HTTPS request, encrypting it inside port 443 with TLS, so a bystander sees only "this machine is talking to some DoH provider" and not what was asked. The wire format is specified by [RFC 8484](https://www.rfc-editor.org/rfc/rfc8484), and the privacy rationale is set out in the [IETF DNS Privacy Considerations, RFC 7626](https://datatracker.ietf.org/doc/rfc7626/).
But knowing what DoH is and putting it into production are different things. This post skips the theory and covers what I actually reach for: wiring DoH onto a single server, making a whole network resolve encrypted, standing up an internal DoH endpoint, and proving it really took. The reader is an engineer who already runs basic network ops and needs to replace plaintext DNS in a real environment.
## 1. Decide which segment you are encrypting
Before touching anything, locate the pain. Each position leads to a different build:
- **A single Linux server**: you only want that one box's lookups private — change the local resolver, smallest blast radius.
- **An office or home LAN**: you want every device (phone, laptop, IoT) on encrypted DNS — do it at the router or gateway and hand out an encrypted resolver via DHCP.
- **An externally exposed service or public egress**: you need to push DNS out of a blocked or restricted network — a DoH proxy like cloudflared is the most reliable here.
- **A network with private names**: you must resolve in layers or internal services die.
Draw your boundary first, then pick the config below. Mixing is normal; the key is never to leak a private domain out to a public DoH.
## 2. Single server: cloudflared as a local DoH proxy
This is the most general and least invasive option. cloudflared opens a DNS listener on the box (port 53 by default) and forwards received queries over HTTPS to an upstream DoH endpoint; every other process just points its resolver at 127.0.0.1. The upstream resolution mechanics are documented by [Cloudflare's DoH docs](https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/) and the [cloudflared GitHub repo](https://github.com/cloudflare/cloudflared).
On Debian/Ubuntu I add the Cloudflare repo so the binary follows the normal update cycle:
```bash
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main' \
| sudo tee /etc/apt/sources.list.d/cloudflared.list
sudo apt update && sudo apt install cloudflared
```
The config lives in `/etc/cloudflared/config.yml`:
```yaml
proxy-dns: true
proxy-dns-port: 53
proxy-dns-upstream:
- https://1.1.1.1/dns-query
- https://1.0.0.1/dns-query
```
Then run it as a service so it survives reboots:
```bash
sudo cloudflared service install
sudo systemctl enable --now cloudflared
```
Finally point the box at the local proxy — edit `/etc/resolv.conf` or the systemd-resolved config to set `nameserver 127.0.0.1`, keeping one non-encrypted fallback only as a last resort (note: that fallback degrades to plaintext, a tradeoff, not an ideal). Verify with:
```bash
dig @127.0.0.1 example.com
```
The upside is that the application layer barely notices and every process benefits; the downside is it only covers this one machine and cloudflared is now a single point to monitor for liveness.
## 3. System level: the DoT vs DoH confusion in systemd-resolved
A lot of tutorials tell you to write `DNS=1.1.1.1#cloudflare-dns.com` plus `DNSOverTLS=yes` in systemd-resolved and call it DoH. Strictly, systemd-resolved's `DNSOverTLS` implements DoT (DNS over TLS), not DoH. Both encrypt; the port and envelope differ. That is not an error, but it is a naming issue — get the vocabulary right so you do not report a false capability upward.
If you genuinely want DoH at this layer, the realistic move is to point systemd-resolved's upstream at the local cloudflared from Section 2 (`DNS=127.0.0.1`) and let cloudflared do the DoH encapsulation. Responsibilities stay clean: the system resolver handles caching and local policy; cloudflared handles the encrypted egress.
## 4. Whole network: hand encrypted DNS to every client at the router
Fixing one server is not enough — phones and laptops stay plaintext. True "full-site encryption" happens at the gateway. Two approaches:
**Approach A — the gateway runs the DoH proxy itself.** Put cloudflared or dnscrypt-proxy on the OpenWrt/iKuai/soft router; the gateway's DNS listener serves the LAN, and DHCP hands clients the gateway's own address. Clients stay oblivious; all traffic converges at the gateway and exits over DoH.
**Approach B — DHCP hands out a public DoH endpoint directly.** Some modern routers can advertise an encrypted-DNS option (DoH/DoT bootstrap domain), and modern clients (recent Android, Windows 11, iOS) recognize and dial it. But this depends on client support; older devices ignore it and coverage is incomplete.
I prefer Approach A because it does not depend on client capability and I can keep filtering and logging at the gateway. One warning: anything that previously relied on gateway DNS for ad-blocking or parental controls must be reattached to the gateway's resolution layer, or those policies vanish along with the plaintext.
## 5. Internal resolver: a self-hosted CoreDNS DoH endpoint
For a team of any size, pointing every resolver at a third-party DoH is not always right — you hand your query metadata to someone else. The more controllable path is a recursive resolver plus a DoH exit: CoreDNS serving a DoH endpoint on port 443, forwarding upstream to a recursive or public DoH you trust.
A minimal Corefile:
```yaml
https://.:443 {
tls /etc/coredns/cert.pem /etc/coredns/key.pem
forward . 1.1.1.1 8.8.8.8 {
tls_servername cloudflare-dns.com
}
cache 300
log
}
```
Two engineering points here. First, **private-zone split**: add a `file` or `kubernetes` plugin before `forward` to handle internal zones so `*.internal` never leaks out. Second, **certificates**: port 443 DoH needs a valid TLS cert; use ACME auto-renewal, because an expired cert is the most common silent-death for this kind of service.
## 6. Verify: prove with a packet capture that plaintext is gone
The worst outcome is "configured and shipped" without proof. Whether DoH works cannot be established by reading config — it needs falsification.
Hit the DoH JSON API to confirm resolution works:
```bash
curl -s -H 'Accept: application/dns-json' \
'https://cloudflare-dns.com/dns-query?name=example.com&type=A' | jq
```
Then capture plaintext DNS to confirm nothing leaks:
```bash
sudo tcpdump -i any port 53
```
With DoH correctly live, that command should stay silent — no query should leave toward an external port 53. If you still see `8.8.8.8.53` packets, something is bypassing: a container hardcoding 8.8.8.8, a `/etc/resolv.conf` not fully rewritten, or an app using its own DNS library. Walk each until the capture is quiet. This is the quality gate for DoH; if it does not pass, the rollout is not done.
## 7. Choosing a provider on privacy grounds
DoH encrypts the path but does not remove the question of who is watching. The mainstream providers differ meaningfully, and selection should align with your compliance posture:
- **Cloudflare (1.1.1.1)**: promises to delete query logs within 24 hours, audited annually by KPMG, usually fastest.
- **Google (8.8.8.8)**: temporarily records full source IPs, anonymizes within 24–48 hours, strong coverage and stability.
- **Quad9 (9.9.9.9)**: Swiss-based, no IP logging by default, built-in threat-intel blocking of malicious domains.
- **NextDNS**: customizable filtering, good for team-level policy, but a commercial service.
If data-residency or cross-border rules are strict, prefer a self-hosted recursive or a jurisdiction-friendly provider, and keep DNSSEC verification on.
## 8. Discipline: how DoH rots, and how I stop it
DoH is a textbook "silently degrades" item: one bad rollback, one expired cert, one app hardcoding plaintext DNS, and the encryption is gone while everything still looks fine. My standing discipline:
- **Daily**: watch cloudflared/CoreDNS process liveness and upstream latency — if the process dies, clients silently fall back to the plaintext fallback.
- **Weekly**: run a spot tcpdump on port 53 to confirm no client is still going plaintext — newly attached devices are the usual leak.
- **Monthly**: check remaining TLS validity on the DoH endpoint; an expired cert takes the whole endpoint down.
- **Before any change**: validate the resolver on a test box before rolling out; after the change, confirm with dig + tcpdump together.
- **Red lines**: never keep a long-lived plaintext fallback DNS without monitoring it; never forward internal private zones to a public DoH.
## FAQ
**Q: DoH or DoT — do I have to standardize on one?**
A: No, and I do not. DoH on 443 blends with web traffic and survives strict firewalls; DoT on 853 is simpler and lighter on hardware I own. Internal boxes get DoT or a CoreDNS forward; a constrained public egress gets DoH. Same goal, different envelope.
**Q: Will DoH break internal names and split-horizon?**
A: It can, and that is the classic pitfall. Keep it layered: hosts and local cache first, private zones to an internal authority or split-horizon, only public names forward to DoH. In CoreDNS, split with `file`/`kubernetes` before `forward`; in cloudflared, filter suffixes before the upstream.
**Q: How do I prove it works, not just that I configured something?**
A: curl the DoH JSON API for a correct answer, then tcpdump port 53 and require silence. If you still see 8.8.8.8:53, find the bypassing process — container, stale resolv.conf, app DNS library — until the capture is quiet.
**Q: Is my privacy solved if Cloudflare or Google sees it all?**
A: Path privacy is solved; provider visibility is not. Provider choice is the real privacy decision, and a self-hosted recursive plus DNSSEC is the stronger end state. DoH is one layer of depth, not the finish line.
**Q: Do office DNS controls survive DoH?**
A: Only if you reattach them. Either run the filtering at your own edge DoH proxy (CoreDNS with a policy plugin) or lock devices to your designated endpoint. Never assume the old port-53 policy still governs once clients can dial out encrypted.
## Related articles
- [DNS resolution and troubleshooting fundamentals](dns-resolution.md)
- [DNS troubleshooting: from dig to packet capture](dns-troubleshoot.md)
- [dnsmasq configuration: a local DNS cache for the internal zone](dnsmasq-config.md)
- [Zero-trust network design: from perimeter to identity](zero-trust-network.md)
## Related Articles
- [Self-Hosting Behind a Cloudflare Tunnel: Exposing Services Without Opening Inbound Ports](cloudflare-tunnel-self-hosted.md)
---
## DNS Resolution End-to-End: Recursive vs Iterative, TTL, dig +trace, EDNS0
URL: https://ops.jiunotes.top/en/network/dns-resolution.md
摘要: A working engineer's guide to how DNS actually works: stub resolver, recursive resolver, iterative chain (root → TLD → authoritative), TTL semantics, systemd-resolved vs dnsmasq vs static resolv.conf, dig +trace walkthrough, EDNS0 and DNSSEC, 12-command dig cheat sheet.
### Answer
DNS query = client→recursive resolver (recursive), resolver→root/TLD/authoritative (iterative). TTL: static 86400s, CDN 300-600s, hot-swap 60-300s, never 0.
### FAQ
Q: What's the difference between recursive and iterative DNS?
A: Recursive = 'find it for me' (client to resolver). Iterative = 'I don't know, but ask this next server' (resolver to root/TLD/authoritative). Clients always use recursive. Resolvers use iterative between themselves and the public DNS hierarchy.
Q: What TTL should I use for my domain?
A: Static site: 86400s (1 day). CDN front: 300-600s. Load balancer / hot-swap: 60-300s. Never 0 — it hammers every resolver on every query. The rule: the more often you change the IP, the shorter the TTL, but never below 60s in production.
Q: What's the single most useful dig command?
A: `dig +trace example.com` — it walks the full iterative chain from root to TLD to authoritative, showing every hop. This is the one command that tells you which server in the chain is broken. Pair with `dig @ example.com` to bypass cache and ask the authoritative server directly.
Q: systemd-resolved vs dnsmasq — which one?
A: Pick one, not both. systemd-resolved is the Debian/Ubuntu default, listens on 127.0.0.53, integrates with NetworkManager. dnsmasq is more flexible, often paired with DHCP, commonly used in home/multi-VLAN setups. Running both causes port-53 conflicts and unpredictable behavior.
Q: How do I check if EDNS0 is working?
A: `dig example.com +edns=0` requests EDNS0 support; look for `flags: qr rd ra ad` and a larger payload size in the header. EDNS0 lets DNS responses exceed 512 bytes — essential for DNSSEC (which needs more room for signatures). Most resolvers support it by default now.
### Full Content
# DNS Resolution End-to-End: Recursive vs Iterative, TTL, dig +trace, EDNS0
DNS has been the backbone of the internet for 35 years and is still the most misunderstood protocol in production. When DNS breaks, the symptom is always the same — "the site won't load" — but the root cause can live in any of four different places: the client's local cache, the recursive resolver, the iterative chain, or the authoritative server. Figuring out which layer is broken is the whole game.
## Three Servers Between You and the Internet
Every DNS lookup involves three distinct servers doing three distinct jobs:
1. **The stub resolver** — your application's DNS client, built into libc or your language runtime. It sends the query to a recursive resolver.
2. **The recursive resolver** — your local DNS server ([systemd](https://www.freedesktop.org/software/systemd/man/latest/)-resolved, dnsmasq, or whatever's in `/etc/resolv.conf`). It walks the chain for you and caches the answer.
3. **The authoritative servers** — the NS records that own the domain. They return the actual A/AAAA/CNAME records.
The recursive resolver also talks to the **root servers** (13 letters, `a.root-servers.net` through `m.root-servers.net`) and **TLD servers** (`.com`, `.org`, etc.) — these are intermediate hops, not the final authority.
## The Full Resolution Path: Step by Step
When your browser hits `https://www.google.com`, here's the exact chain:
```
1. App asks stub resolver: "what's www.google.com?"
2. Stub resolver asks recursive resolver (127.0.0.53 or 8.8.8.8): same question
3. Recursive resolver checks local cache. If hit → done.
4. Cache miss → recursive resolver asks root server: "who handles .com?"
5. Root returns: "ask a.gtld-servers.net through m.gtld-servers.net"
6. Recursive asks TLD server: "who handles google.com?"
7. TLD returns: "ask ns1.google.com through ns4.google.com"
8. Recursive asks authoritative server: "what's www.google.com?"
9. Authoritative returns: "www.google.com. 60 IN CNAME www.google.com.edgekey.net."
10. Recursive follows CNAME → asks edgekey.net authoritative → gets A record
11. Recursive returns to stub: "www.google.com = 142.250.80.46"
12. Stub returns to app: same IP
```
Each step is a separate UDP (or TCP for large responses) query. The recursive resolver does steps 3-10 for you. Without a recursive resolver, every client would have to walk the chain themselves — which is why resolvers exist.
## Iterative vs Recursive: The Two Modes
This is the distinction that confuses everyone, because both modes happen in the same lookup.
**Recursive** is the client-to-resolver relationship. The client says "find it" and the resolver says "okay, I'll do the work." This is what you use.
**Iterative** is the resolver-to-resolver relationship. Each server says "I don't know, but ask this next server." The resolver walks this chain step by step.
The mnemonic: **clients ask recursively; resolvers walk iteratively.**
## TTL and Cache: How Long Does Everything Live?
Every DNS record has a TTL (Time To Live) in seconds. This tells caches how long to hold the answer before re-querying. Every layer has its own cache:
| Layer | Cache Location | TTL Behavior |
|---|---|---|
| Stub | Application process memory | Usually none, re-queries OS each time |
| OS | systemd-resolved / dnsmasq / `/etc/hosts` | Respects record TTL, but may override |
| Recursive resolver | Local disk + memory | Respects record TTL |
| Authoritative | The NS server itself | No cache — returns the source of truth |
The trap: Windows has its own DNS client cache that's **not** controlled by the server TTL. Even if you set TTL to 60 seconds, Windows may cache for several minutes. Flush with `ipconfig /flushdns`.
```powershell
# Windows: flush local DNS cache
ipconfig /flushdns
# [Linux](https://www.kernel.org/doc/html/latest/): flush systemd-resolved cache
sudo systemd-resolve --flush-caches
# Linux: flush dnsmasq cache
sudo kill -SIGHUP $(pgrep dnsmasq)
```
## The Local Resolver Problem: Three Options
On Linux, "which resolver does the client ask" is buried deep in the init system. Three valid options, and picking more than one is the single most common DNS misconfiguration.
### Option A: systemd-resolved (Debian/Ubuntu default)
Listens on `127.0.0.53`. `/etc/resolv.conf` is usually a symlink to `stub-resolv.conf`.
```bash
# Check what's listening on port 53
ss -ulnp | grep ':53'
# Check the current upstream DNS
resolvectl status
# Query directly via systemd-resolved
resolvectl query example.com
# Set upstream DNS for eth0
resolvectl dns eth0 8.8.8.8
# Flush the cache
resolvectl flush-caches
```
If you see `nameserver 127.0.0.53` in `/etc/resolv.conf`, systemd-resolved is your resolver. Editing `/etc/resolv.conf` directly won't work because it's a symlink — use `resolvectl` instead.
### Option B: dnsmasq (multi-VLAN, home servers, [Docker](https://docs.docker.com/) hosts)
dnsmasq does DNS caching + DHCP + optional upstream forwarding. To run it on port 53, disable systemd-resolved's stub listener:
```bash
# Disable systemd-resolved's port-53 stub listener
sudo sed -i 's/^DNSStubListener=yes/DNSStubListener=no/' /etc/systemd/resolved.conf
sudo systemctl restart systemd-resolved
# Start dnsmasq
sudo systemctl enable --now dnsmasq
# Verify dnsmasq owns port 53
ss -ulnp | grep ':53'
# Expected: dnsmasq listening on 0.0.0.0:53 and [::]:53
```
dnsmasq config basics (`/etc/dnsmasq.d/90-local.conf`):
```
# Forward upstream to Google DNS
server=8.8.8.8
server=1.1.1.1
# Local cache
cache-size=1000
# Local-only records ([RFC](https://www.rfc-editor.org/) 1918 / .local)
local=/internal/
address=/internal.example.com/10.0.0.1
# Conditional forwarding
server=/corp.example.com/10.0.0.53
```
### Option C: Static /etc/resolv.conf (containers, minimal systems)
Simple, predictable, and the right choice for containers and minimal VMs.
```bash
# Remove the symlink first if it exists
rm /etc/resolv.conf
# Write the static config
cat > /etc/resolv.conf <<'EOF'
nameserver 8.8.8.8
nameserver 1.1.1.1
options timeout:2 attempts:3
EOF
```
**Pitfall**: if `/etc/resolv.conf` is a symlink, writing to it follows the symlink and modifies the target file. Always `rm` the symlink first, or you'll accidentally reconfigure systemd-resolved's stub.
## dig +trace: Watching the Chain Unfold
The single most powerful DNS diagnostic command is `dig +trace`. It walks the full iterative chain from root and prints every hop.
```bash
dig example.com +trace
```
You'll see output like:
```
;; DiG 9.16.1-Ubuntu
. 518400 IN NS a.root-servers.net.
. 518400 IN NS m.root-servers.net.
...
;; Received 431 bytes from 198.41.0.4#53(a.root-servers.net) in 12 ms
com. 172800 IN NS a.gtld-servers.net.
com. 172800 IN NS m.gtld-servers.net.
;; Received 260 bytes from 192.5.6.30#53(a.gtld-servers.net) in 8 ms
example.com. 86400 IN NS a.iana-servers.net.
example.com. 86400 IN NS b.iana-servers.net.
;; Received 122 bytes from 199.43.132.1#53(a.iana-servers.net) in 5 ms
example.com. 3600 IN A 93.184.216.34
;; Received 47 bytes from 199.43.132.1#53(a.iana-servers.net) in 4 ms
```
Each `;; Received` line is one hop. If the trace dies at `.com` → TLD, the TLD server is broken. If it dies at `example.com` → authoritative, the authoritative is broken. If it completes, the issue is in your local resolver or client cache.
For cleaner output (no root noise):
```bash
# Only answer section
dig example.com +noall +answer
# Only answer + authority (shows NS records too)
dig example.com +noall +answer +authority
# Shortest possible output (IP only)
dig example.com +short
```
## Conditional Forwarding: bind and dnsmasq
In enterprises and Docker networks, internal domains (`.internal`, `.corp`, `.svc.cluster.local`) need to resolve to internal IPs. You configure the recursive resolver to forward specific domains to specific upstream servers:
**bind** (`/etc/named.conf`):
```
zone "corp.example.com" IN {
type forward;
forward only;
forwarders {
10.0.0.53;
};
};
```
**dnsmasq** (`/etc/dnsmasq.d/90-local.conf`):
```
server=/corp.example.com/10.0.0.53
server=/internal/10.0.1.53
server=8.8.8.8
```
The pattern: internal domains forward to internal DNS, everything else forwards to public DNS. This is what lets Docker DNS (127.0.0.11) resolve service names inside a compose network while still resolving external domains.
## EDNS0 and DNSSEC: The Extensions
Modern DNS has two extensions every resolver should support:
### EDNS0 (RFC 6891)
EDNS0 (Extended DNS) lets DNS responses exceed the old 512-byte UDP limit and includes features like EDNS Client Subnet (ECS), which lets geolocation-aware CDNs see the client's real subnet instead of the resolver's.
```bash
# Request EDNS0 with buffer size 4096
dig example.com +edns=0 +bufsize=4096
# Look for the EDNS OPT record in the response header
dig example.com +edns=0 +noall +comments
```
Look for `flags: qr rd ra ad` and a `OPT` record showing the UDP payload size. If your resolver doesn't support EDNS0, large responses will be truncated to TCP — slower and more likely to fail.
### DNSSEC (DNS Security Extensions)
DNSSEC signs DNS records cryptographically so a resolver can verify the answer came from the real authoritative server, not a hijacker.
```bash
# Request DNSSEC validation
dig example.com +dnssec
# Turn off validation (emergency)
dig example.com +cd
# Check the RRSIG (Resource Record Signature) records
dig example.com +dnssec +noall +answer
```
If `+dnssec` shows `RRSIG` records and `status: NOERROR`, DNSSEC is working. If `+dnssec` shows `status: SERVFAIL` but `+cd` shows `status: NOERROR`, the DNSSEC chain is broken somewhere — usually a misconfigured DS record or missing RRSIG.
## TTL Recommendation Table
| Scenario | TTL | Reasoning |
|---|---|---|
| Static website | 86400s | Rarely changes, cache as long as possible |
| CDN front | 300-600s | Balance between change speed and query load |
| Load balancer / hot-swap | 60-300s | Needs to switch fast under failover |
| Extreme edge case | 60s | Don't go lower in production — query load explodes |
| Maintenance window only | 30-60s | Use only during planned changes, then restore |
| Debugging | 0-30s | Emergency only, never leave it |
The standard deploy pattern for changing an IP:
1. Lower TTL to 60s.
2. Wait 60 seconds for all resolvers to expire the old record.
3. Change the IP.
4. Wait for propagation.
5. Restore TTL to the normal value.
```bash
# Dynamic update with nsupdate (requires DDNS access)
nsupdate -v -l <<'EOF'
server 127.0.0.53
update delete example.com A
update add example.com 60 A 1.2.3.4
send
EOF
sleep 65 # Wait one TTL cycle
nsupdate -v -l <<'EOF'
server 127.0.0.53
update delete example.com A
update add example.com 86400 A 5.6.7.8
send
EOF
```
## 12 dig Commands Cheat Sheet
| # | Command | Purpose |
|---|---|---|
| 1 | `dig example.com +short` | IP only, no metadata |
| 2 | `dig example.com +trace` | Full iterative chain from root |
| 3 | `dig example.com @8.8.8.8` | Specify a resolver explicitly |
| 4 | `dig example.com @ns1.example.com` | Ask authoritative directly, bypass cache |
| 5 | `dig example.com +noall +answer` | Answer section only |
| 6 | `dig example.com MX` | Mail exchange records |
| 7 | `dig example.com TXT` | SPF / DMARC / DKIM |
| 8 | `dig example.com CNAME` | CNAME alias |
| 9 | `dig -x 8.8.8.8` | Reverse PTR lookup |
| 10 | `dig example.com +subnet=1.2.3.4/32` | EDNS Client Subnet (geo-specific answer) |
| 11 | `dig example.com +cd` | Turn off DNSSEC validation (emergency) |
| 12 | `dig example.com +time=5 +tries=2` | Custom timeout/retries |
Command 4 (`dig @`) is the most useful for production debugging. When a CDN gives you different IPs from different resolvers, the authoritative is the source of truth. I once had a CloudFront setup where `dig @8.8.8.8` returned one IP and `dig @1.1.1.1` returned another — the authoritative NS answered correctly, but the two resolvers had stale caches. Always verify against the authoritative when in doubt.
## Three Production Pitfalls
### Pitfall 1: The symlink resolv.conf trap
Symptom: edited `/etc/resolv.conf`, but `dig` still returns the old results.
Root cause: `/etc/resolv.conf` is a symlink to `stub-resolv.conf` (owned by systemd-resolved). Editing it either fails silently or modifies the symlink target without affecting the live resolver.
Fix: use `resolvectl dns eth0 8.8.8.8` to set the upstream, or edit `/etc/systemd/resolved.conf` and restart.
```bash
# Check if it's a symlink
ls -la /etc/resolv.conf
# If symlink, remove and replace
rm /etc/resolv.conf
echo "nameserver 8.8.8.8" > /etc/resolv.conf
```
### Pitfall 2: Windows client cache ignores server TTL
Symptom: server TTL set to 60s, but Windows clients keep using the old IP for 30 minutes.
Root cause: Windows maintains its own DNS client cache that's independent of the server-side TTL. Even with a 60s TTL, Windows may hold the answer for several minutes.
Fix: `ipconfig /flushdns` on the affected client. In group policy, set `DNS Client > Enable caching of SRV records` to disabled if you see SRV record staleness.
### Pitfall 3: Browser vs terminal resolver divergence
Symptom: `dig example.com` in terminal returns the correct IP, but the browser shows `ERR_NAME_NOT_RESOLVED`.
Root cause: the browser uses the system resolver, which may differ from what the terminal is configured to use (especially on systems with multiple resolver interfaces, or when a browser extension / corporate proxy is involved).
Fix: check `getent ahosts example.com` for the system resolver's answer, and compare to what the terminal shows. If they differ, there are two resolver chains on the machine — find and fix the conflicting one.
## Related Articles
- [DNS Troubleshooting: Six-Symptom Decision Tree](dns-troubleshoot.md) — when resolution is actually broken
- [CDN Internals: Edge POP, Origin Fetch, Cache Invalidation](cdn-principles.md) — how CDN DNS TTL affects cache propagation
- [TCP/IP: Layered Model, Three-Way Handshake, State Machine](tcp-ip.md) — what happens after DNS gives you an IP
- [TCP Troubleshooting: TIME_WAIT / RST / SYN Half-Open](tcp-troubleshoot.md) — when the IP connects but the socket doesn't
- [Wireshark Basics: 30 Filters for Packet Analysis](wireshark-basics.md) — when DNS answers but the connection still fails
## Authoritative References
- [RFC 1034 — Domain Names: Concepts and Facilities](https://datatracker.ietf.org/doc/html/rfc1034)
- [RFC 1035 — Domain Names: Implementation and Specification](https://datatracker.ietf.org/doc/html/rfc1035)
- [RFC 6891 — Extension Mechanisms for DNS (EDNS0)](https://datatracker.ietf.org/doc/html/rfc6891)
- [RFC 4033 — DNS Security Introduction and Requirements](https://datatracker.ietf.org/doc/html/rfc4033)
- [ISC dig man page](https://manpages.debian.org/unstable/dnsutils/dig.1)
---
---
## DNS Troubleshooting: Six-Symptom Decision Tree with dig +trace
URL: https://ops.jiunotes.top/en/network/dns-troubleshoot.md
摘要: A working engineer's DNS troubleshooting guide: six-symptom decision tree (NXDOMAIN, SERVFAIL, timeout, CNAME loop, stale cache, DNSSEC failure), dig +trace from-root iterative walkthrough, dig @authority to bypass cache, 15-command cheat sheet, and three real production cases.
### Answer
DNS troubleshooting = match symptom to path. NXDOMAIN=check domain exists, SERVFAIL=trace the chain, timeout=compare resolvers, CNAME loop=+noall +answer, stale=check TTL, DNSSEC=+cd to bypass.
### FAQ
Q: dig, host, or nslookup — which should I use?
A: On Linux, dig 90% of the time. It lets you specify the resolver, record type, +trace, +cd (bypass DNSSEC), and +short (one-line output). host is fine for quick lookups in scripts. nslookup is only forced on you on Windows — it's an older interface and lacks dig's diagnostic power.
Q: What does +trace actually show me?
A: `dig example.com +trace` walks the iterative chain from the root server down: root → TLD (.com) → authoritative NS → A record. Each hop is a separate UDP query. You'll see `;; Received` lines from each server. If the trace stops at a hop, that's the broken server.
Q: SERVFAIL is the worst DNS error — why?
A: Because the authoritative server says 'I can't resolve this' without saying why. Common causes: CNAME loop, missing delegation, broken DNSSEC chain, or a server that's just down. `dig @8.8.8.8 example.com +trace` shows which hop fails first. If +trace shows NOERROR at every hop but the final answer is SERVFAIL, the authoritative is misconfigured.
Q: I changed a DNS record but it's not taking effect — why?
A: TTL. If the record had a 24-hour TTL, your clients will keep using the old answer for up to 24 hours. The fix is always: (1) lower TTL to 60s first, (2) wait 60s, (3) change the record, (4) wait for propagation, (5) restore TTL. Also flush local caches: `systemctl restart systemd-resolved` on Linux, `ipconfig /flushdns` on Windows.
Q: How do I tell if DNSSEC is the problem?
A: Two commands: `dig example.com +dnssec` (with validation) and `dig example.com +cd` (without). If +dnssec shows SERVFAIL but +cd shows NOERROR, DNSSEC validation is failing — the signature chain is broken. If both show SERVFAIL, the authoritative is just down. If both show NOERROR, DNSSEC is fine and look elsewhere.
### Full Content
# DNS Troubleshooting: Six-Symptom Decision Tree with dig +trace
DNS is the protocol you hope you never have to debug, because when it breaks the symptom is always the same — "the site won't load" — and the root cause can be anywhere from your local cache to a TLD server to a misconfigured CNAME loop. This article walks through the six DNS failure symptoms I see in production, in the order I teach them to juniors: match the symptom, then pick the command.
## 60-Second Tool Selection: dig vs host vs nslookup
Three tools, three use cases. Pick dig by default.
| Tool | When to use | One-line description |
|---|---|---|
| `dig` | 90% of debugging | Full-featured: specify resolver, record type, +trace, +cd, +short |
| `host` | Quick script-friendly lookup | One-line output, no trace, good for cron jobs |
| `nslookup` | Only on Windows | Legacy interface, no trace, no +cd, no +short |
The one-liner to remember: **if you can `dig`, don't `nslookup`.** `dig` gives you the diagnostic surface you need; `nslookup` gives you a black box.
## The Six-Symptom Decision Tree
Before you run any command, classify the symptom. The symptom tells you which half of DNS to investigate.
```
"DNS is broken"
│
├─ NXDOMAIN returned ────────── Domain doesn't exist (or NS not yet propagated)
│
├─ SERVFAIL returned ────────── Some server in the chain failed
│
├─ Timeout / no response ───── Recursor down, or network path issue
│
├─ CNAME not resolving ──────── CNAME loop, or CNAME at same name as A
│
├─ Record not changing ─────── TTL still has time to expire
│
└─ DNSSEC validation fails ──── Signature chain broken upstream
```
Below is each symptom in detail, with the exact commands, what you should see, and what to do.
## Symptom 1: NXDOMAIN — Does the Domain Actually Exist?
NXDOMAIN means "nonexistent domain." It's the most common DNS error, and the most often misdiagnosed. The first question is always: does the domain really exist?
```bash
# Step 1: ask the local recursive resolver
dig example.com
# Step 2: ask the authoritative NS directly, bypassing cache
dig @ns1.example.com example.com
# Step 3: ask the registrar's NS (skip local entirely)
dig @registrar.example.com example.com
```
**What each result means**:
- `status: NOERROR` + non-empty `ANSWER SECTION` → domain exists, NXDOMAIN was a local cache lie. Flush your resolver.
- `status: NOERROR` + empty `ANSWER SECTION` → domain exists but no A/AAAA record. Add one.
- `status: NXDOMAIN` at the authoritative → domain really doesn't exist. Check with the registrar.
**The common false alarm**: you just registered a domain, the registrar console shows "registered," but the authoritative NS returns NXDOMAIN. This is the registrar's DNS servers not yet having propagated the delegation. Wait 30-60 minutes and try again. Don't change your local resolver.
```bash
# Verify the delegation at the TLD level
dig .com NS example.com +noall +answer
# Expected: shows the NS records for example.com at the .com TLD
```
## Symptom 2: SERVFAIL — Who's Downstream?
SERVFAIL is the DNS version of "500 Internal Server Error" — the server refuses to answer but doesn't say why. It's the most annoying DNS error because the chain could be broken anywhere.
```bash
# Trace the full chain from root
dig @8.8.8.8 example.com +trace
# Ask specific levels directly
dig @a.root-servers.net . NS
dig @a.gtld-servers.net com NS
dig @ns1.example.com example.com A
```
**What the trace tells you**:
- A specific hop returns SERVFAIL → that NS server is down or misconfigured.
- Every hop returns NOERROR but the final answer is SERVFAIL → the authoritative is in a config loop (NS records point to servers that don't have the zone loaded).
```bash
# Real-world example: domain with a broken CNAME loop
dig @ns1.example.com example.com
# SERVFAIL, "no answer"
# Trace it
dig @8.8.8.8 example.com +trace
# See: . → .com → example.com NS → SERVFAIL at the last hop
```
**The DNSSEC angle**: sometimes SERVFAIL is actually a DNSSEC validation failure, and the resolver is being honest. Try turning validation off:
```bash
# Bypass DNSSEC validation
dig @8.8.8.8 example.com +cd
# If +cd returns NOERROR but without +cd returns SERVFAIL → DNSSEC chain is broken
# If both return SERVFAIL → the authoritative is really down
```
**Pitfall I hit early**: a customer's domain kept returning SERVFAIL. `dig @8.8.8.8 example.com +cd` returned NOERROR with the correct IP. The DNSSEC chain was broken — the customer's registrar hadn't properly configured the DS record. Fix was at the registrar, not the customer. Lesson: when you see SERVFAIL, try `+cd` first before chasing server down.
## Symptom 3: Timeout / No Response — Path Issue or Recursor Issue?
When a query times out, you can't tell from one command whether it's your local resolver, the upstream, or the network path. Compare three public resolvers:
```bash
# Compare three independent resolvers
dig @8.8.8.8 example.com +time=3 +tries=1
dig @1.1.1.1 example.com +time=3 +tries=1
dig @223.5.5.5 example.com +time=3 +tries=1
# Compare with your local resolver
dig example.com +time=3 +tries=1
```
**What the comparison tells you**:
- All three time out → network issue, or DNS port 53 blocked.
- Only internal DNS (10.x.x.x) times out → internal recursive resolver is down. Check `systemctl status [systemd](https://www.freedesktop.org/software/systemd/man/latest/)-resolved` or `systemctl status bind`.
- All public resolvers work, internal is slow → internal resolver is misconfigured. Consider switching to public DNS.
```bash
# Check local resolver status
systemctl status systemd-resolved
resolvectl status
ss -ulnp | grep ':53'
# Check if port 53 is reachable from another host
nc -zu 8.8.8.8 53
```
**The one-machine-only case**: a single workstation reports "DNS timeout" but every other machine is fine. Root cause: `systemd-resolved` crashed on that machine.
```bash
sudo systemctl restart systemd-resolved
sudo resolvectl flush-caches
```
I've seen this twice in the last year. Both times the fix was a service restart, not a config change.
## Symptom 4: CNAME Loop — Configuration Mistake
A CNAME loop happens when domain A points to domain B, which points to domain A. Or, more subtly, when a CNAME and an A record try to coexist at the same hostname.
```bash
# Show the full CNAME chain
dig example.com +noall +answer +comments
# Or ask for any record
dig example.com ANY +noall +answer
```
**What you should see in a loop**:
```
example.com. 300 IN CNAME www.example.com.
www.example.com. 300 IN CNAME example.com.
```
That's a loop. DNS resolvers will recurse up to 8 CNAME hops and then give up.
**The other CNAME trap**: CNAME cannot coexist with other records at the same name.
```bash
# This is invalid — CNAME and A can't share a name
example.com. 300 IN CNAME cdn.example.com.
example.com. 300 IN A 1.2.3.4
```
Fix: split into two hostnames.
```bash
# Valid
app.example.com 300 IN CNAME lb.example.com.
lb.example.com 300 IN A 1.2.3.4
```
## Symptom 5: Stale Cache — TTL Wins
The most common "I changed DNS but nothing happened" complaint. TTL is the single variable that controls how long caches hold the answer.
```bash
# Check the TTL on the current record
dig example.com | head -20
# Look at the first column of the ANSWER SECTION:
# example.com. 86400 IN A 1.2.3.4
# That 86400 is 24 hours. You just have to wait 24 hours.
# Compare what different resolvers see
dig @8.8.8.8 example.com
dig @1.1.1.1 example.com
```
**What different resolver answers tell you**:
- Same IP from both → cache is consistent, wait for TTL.
- Different IPs → your resolver has a stale cache. Flush it.
- Both return old IP → the authoritative hasn't updated. Check with the registrar.
**The correct change procedure**:
1. Lower TTL to 60s.
2. Wait 60 seconds.
3. Change the record.
4. Wait for propagation.
5. Restore TTL.
Do it the other way and the change is a no-op.
```bash
# Flush local caches
# [Linux](https://www.kernel.org/doc/html/latest/) (systemd-resolved)
sudo systemctl restart systemd-resolved
# Linux (dnsmasq)
sudo kill -SIGHUP $(pgrep dnsmasq)
# Windows
ipconfig /flushdns
# macOS
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
```
## Symptom 6: DNSSEC Validation Failure — Upstream Broken
DNSSEC signs DNS records so a resolver can verify the answer came from the real authoritative. When validation fails, the resolver returns SERVFAIL (or, in some configs, drops the answer silently).
```bash
# Normal DNSSEC query (validation enabled)
dig example.com +dnssec
# Bypass validation (CD flag set)
dig example.com +cd
# Compare flags
dig example.com +dnssec +noall +comments
dig example.com +cd +noall +comments
```
**What the flags tell you**:
- `flags: qr rd ra ad` (the `ad` bit set) → validation succeeded.
- `status: SERVFAIL` with `+dnssec` → validation failed.
- `status: NOERROR` with `+cd` → the DNSSEC chain is broken somewhere; the answer is valid but not signed.
**Where to look when DNSSEC fails**:
1. Check the DS record at the parent (registrar or TLD): `dig example.com DS +noall +answer`.
2. Check the DNSKEY at the authoritative: `dig example.com DNSKEY +noall +answer`.
3. Check the RRSIG on the record: `dig example.com +dnssec +noall +answer`.
If the DS and DNSKEY don't match (different key IDs), the chain is broken at the delegation. Common cause: the registrar didn't sync the DS record when you rotated keys.
**My honest caveat**: I don't know every DNSSEC vendor's exact behavior. [Cloudflare](https://developers.cloudflare.com/), Route53, and Namecheap each have subtle differences in how they handle key rotation and DS sync. If you see a DNSSEC failure and +cd returns NOERROR, the chain is definitely broken — escalate to your registrar with the output of the commands above.
## Conditional Forwarding: bind and dnsmasq
In enterprise and [Docker](https://docs.docker.com/) networks, internal domains need to resolve to internal IPs, while external domains go to public DNS. This is conditional forwarding.
**bind** (`/etc/named.conf`):
```
zone "corp.example.com" IN {
type forward;
forward only;
forwarders {
10.0.0.53;
};
};
zone "internal.example.com" IN {
type forward;
forward only;
forwarders {
10.0.1.53;
};
};
```
**dnsmasq** (`/etc/dnsmasq.d/90-local.conf`):
```
# Internal domains forward to internal resolvers
server=/corp.example.com/10.0.0.53
server=/internal.example.com/10.0.1.53
# Everything else forwards to public DNS
server=8.8.8.8
server=1.1.1.1
```
**Docker Compose DNS** (dockerd handles this automatically):
```yaml
services:
app:
network:
- frontend
```
Inside the container, service names resolve via Docker's internal DNS at `127.0.0.11`. This is why Docker containers can resolve `db:5432` without external DNS — it's Docker's internal resolver, not the host's.
## 15 dig Commands Cheat Sheet
| Command | Purpose |
|---|---|
| `dig +short ` | Answer only, one line |
| `dig A` | A record |
| `dig AAAA` | IPv6 record |
| `dig MX` | Mail exchange |
| `dig TXT` | SPF / DMARC / DKIM |
| `dig NS` | Authoritative NS |
| `dig CAA` | Allowed CAs |
| `dig SOA` | Zone start of authority |
| `dig @ ` | Specify a recursive resolver |
| `dig @ ` | Ask the authoritative directly |
| `dig +trace` | Full iterative chain from root |
| `dig +noall +answer` | Answer section only |
| `dig +noall +comments` | Header comments only |
| `dig +dnssec` | Request RRSIG signatures |
| `dig +cd` | Turn off DNSSEC validation |
## Three Real Production Cases
### Case 1: NXDOMAIN on a freshly registered domain
A customer bought `newbrand.com`, pointed NS at their registrar's default nameservers, and got NXDOMAIN everywhere for two hours.
Root cause: the registrar's default NS had registered the domain but not yet delegated it to the TLD. The `.com` TLD returned NXDOMAIN because there were no NS records for `newbrand.com` yet.
Fix: wait for the registrar to delegate. I've seen this take anywhere from 15 minutes to 6 hours depending on the registrar. The delegation can be checked at `dig @a.gtld-servers.net com NS newbrand.com` — once you see the NS records, the domain will resolve.
**Moral**: when you see NXDOMAIN on a newly registered domain, don't touch your local DNS config. Check the TLD delegation first.
### Case 2: SERVFAIL from a DNSSEC chain break
A customer's domain (`securecorp.io`) started returning SERVFAIL globally around 03:00 UTC.
Diagnosis:
```bash
dig @8.8.8.8 securecorp.io
# SERVFAIL
dig @8.8.8.8 securecorp.io +cd
# NOERROR, returns the correct IP
```
The chain was broken at the DNSSEC level. `dig securecorp.io DS +noall +answer` showed a stale DS record — the registrar's DS was still pointing to an old key pair. The fix was at the registrar: update the DS to match the current DNSKEY.
**Moral**: when you see SERVFAIL, always try `+cd` before you chase down server connectivity. Half of "SERVFAIL" is actually DNSSEC validation failure, and it's invisible until you disable validation.
### Case 3: Timeout on one machine only
A dev laptop on a corporate network reported "DNS timeout" while every other machine on the same VLAN worked fine.
Diagnosis:
```bash
# On the affected machine
dig @8.8.8.8 example.com +time=3
# OK, public DNS works
dig example.com +time=3
# Timeout
```
The machine's local resolver (systemd-resolved) was crashed. `systemctl status systemd-resolved` showed it had segfaulted.
Fix:
```bash
sudo systemctl restart systemd-resolved
```
**Moral**: when "only one machine has DNS issues," don't touch the network config. Check the local resolver service first. `systemctl status systemd-resolved` is the cheapest diagnostic.
## When You're Still Stuck
If all six symptoms are ruled out and DNS is still broken, drop to the packet layer:
```bash
# Capture DNS traffic on the local machine
sudo tcpdump -nn -i any -s 0 port 53 -c 50
# Filter for the specific query
sudo tcpdump -nn -i any port 53 and host 8.8.8.8
```
If the query goes out but no response comes back, it's a network path issue — port 53 might be blocked, or a middlebox is silently dropping DNS. If the response comes back but the application doesn't see it, it's a local resolver issue.
For a deeper dive into packet-level analysis, see [Wireshark Basics](wireshark-basics.md).
## Related Articles
- [DNS Resolution: Recursive vs Authoritative, TTL Guide](dns-resolution.md) — the full picture of how DNS works
- [CDN Internals: Edge POP, Origin Fetch, Cache Invalidation](cdn-principles.md) — how DNS TTL affects CDN cache behavior
- [Wireshark Basics: 30 Filters for Packet Analysis](wireshark-basics.md) — packet-level DNS diagnosis
- [TCP Troubleshooting: TIME_WAIT / RST / SYN Half-Open](tcp-troubleshoot.md) — the layer below DNS
- [Nginx Reverse Proxy 502/504 Decision Tree](nginx-proxy.md) — when DNS is fine but the HTTP response fails
- [DNS over HTTPS in Production: Encrypting the Last Plaintext Protocol](dns-over-https-doh-configuration.md)
## Authoritative References
- [RFC 1035 — Domain Names: Implementation and Specification](https://datatracker.ietf.org/doc/html/rfc1035)
- [RFC 1034 — Domain Names: Concepts and Facilities](https://datatracker.ietf.org/doc/html/rfc1034)
- [RFC 4034 — Resource Records for DNSSEC](https://datatracker.ietf.org/doc/html/rfc4034)
- [RFC 6891 — Extension Mechanisms for DNS (EDNS0)](https://datatracker.ietf.org/doc/html/rfc6891)
- [ISC dig man page](https://manpages.debian.org/unstable/dnsutils/dig.1)
---
---
## dnsmasq Configuration Deep Dive: A Production-Ready Template and the Port-Conflict Trap
URL: https://ops.jiunotes.top/en/network/dnsmasq-config.md
摘要: dnsmasq runs DNS, DHCP and NTP from one process — but systemd-resolved grabbing port 53 is the trap that breaks it silently. This guide gives a full config template, static host mappings, no-negcache, and validation steps, plus three incidents I actually hit.
### Answer
dnsmasq is the homelab DNS+DHCP+NTP Swiss army knife. Check port 53 first, write one config template, validate with dig and host.
### FAQ
Q: Why does dnsmasq fail silently when systemd-resolved is running?
A: systemd-resolved binds 127.0.0.53:53 by default, so dnsmasq can't grab the port. Check with ss -lunp | grep 53, then stop systemd-resolved or point dnsmasq at a different listen address.
Q: Can dnsmasq do DNS without DHCP?
A: Yes. Remove the dhcp-range section and it becomes a pure DNS forwarder. You can also keep DHCP but split the gateway role onto a separate box for easier rollback.
Q: What does no-negcache actually do and when do I need it?
A: It stops dnsmasq caching negative answers, so a record that was temporarily NXDOMAIN is re-queried immediately. In a NAT'd home network with flaky upstreams, it prevents stale negative results.
Q: How do I validate a dnsmasq deployment?
A: Run dig against the dnsmasq IP for a static host, a short name (expand-hosts), a reverse lookup, and an upstream name. Each should return the expected record; a missing one points to a config or upstream issue.
### Full Content
# dnsmasq Configuration Deep Dive: A Production-Ready Template and the Port-Conflict Trap
## Why I run dnsmasq on the LAN## Why I run dnsmasq on the LAN
For years my homelab ran three daemons for what is really one job: giving every client on the segment a working resolver, a usable address, and a time source. BIND held DNS, ISC DHCP handed out leases, and chrony kept clocks honest. Three config files, three restarts, three log files to grep whenever a laptop could not resolve a name. On a small office network that is a lot of moving parts for a single responsibility.
dnsmasq collapses it into one process and one config file. It listens on UDP/TCP 53 for DNS, UDP 67 for DHCP, and it advertises itself as an NTP server on UDP 123 when you set `dhcp-option=option:ntp-server`. One restart covers every change, and the log is one journal. That is the reason I standardised on it: one box, one process, one file to reason about at 2 a.m.
## The 60-second decision
Before I committed I ran the options side by side in my head.
- **[systemd](https://www.freedesktop.org/software/systemd/man/latest/)-resolved** is already on every systemd box, but it is a stub resolver, not a LAN server. It does not hand out DHCP leases and it does not do NTP. Pressing it into service as the network DNS means fighting its stub listener, which is precisely the trap in the next section.
- **Unbound** is a genuinely good validating recursive resolver, and it is what I reach for when I need DNSSEC on the upstream side. But it is DNS only. I still need a separate DHCP server and a separate NTP daemon.
- **AdGuard Home** is the pick if you want blocking and a web UI. It is a heavier install though, and the DHCP module is not the reason I would choose it; it is a filtering product first.
- **dnsmasq** is DNS + DHCP + NTP in one binary, it reads `/etc/hosts`, it is tiny, and it is in the base repos of every distro I run.
dnsmasq is not the best at any single one of those jobs, but it is the only one that does all three cleanly. In a homelab, fewer daemons beats a marginally better resolver.
## The port-conflict trap
The first time I deployed dnsmasq on a Ubuntu server the unit reported active and then nothing happened. No error on the console, no line in the journal, no listening socket. dnsmasq had not crashed. It had silently failed to bind, because systemd-resolved was already holding port 53.
How I found it:
```bash
ss -lunp | grep ':53 '
```
The output:
```text
UNCONN 0 0 127.0.0.53:53 0.0.0.0:* users:(("systemd-resolve",pid=912,fd=14))
```
There it was. systemd-resolved owned the port on 127.0.0.53, and dnsmasq had quietly skipped the address it could not take. The service did not even mark itself failed, which is what makes this trap nasty: the process starts, claims it is fine, and serves nothing.
I have resolved it three different ways across different boxes, and all of them work:
1. **Kill the stub listener.** Set `DNSStubListener=no` in `/etc/systemd/resolved.conf`, then point systemd-resolved at the LAN address as its upstream. Best on a client that still wants its own resolver.
2. **Mask it entirely.** `systemctl stop systemd-resolved`, `systemctl mask systemd-resolved`, and replace the `/etc/resolv.conf` symlink so it points at the dnsmasq address. Best on a dedicated DNS box.
3. **Move dnsmasq off 127.0.0.53.** Give it a second listen address or run it on the LAN interface only and leave the stub alone.
On my gateway I use option 2. On clients I keep systemd-resolved and just point it upstream at dnsmasq.
## The production config template
This is the file I run on my homelab gateway, a box with 192.168.50.1 on the LAN. I trimmed the comments down to what matters.
```conf
# /etc/dnsmasq.conf
# --- listening ---
listen-address=192.168.50.1
bind-interfaces
port=53
# --- never forward short or private names ---
domain-needed
bogus-priv
no-hosts
# --- upstreams (we own this choice) ---
no-resolv
server=1.1.1.1
server=9.9.9.9
server=8.8.8.8
# --- local zone and static maps ---
local=/lan/
domain=lan
expand-hosts
addn-hosts=/etc/dnsmasq.hosts
# --- DHCP ---
dhcp-range=192.168.50.100,192.168.50.200,12h
dhcp-option=option:router,192.168.50.1
dhcp-option=option:dns-server,192.168.50.1
dhcp-option=option:domain-name,lan
dhcp-authoritative
# --- TFTP and NTP ---
enable-tftp
tftp-root=/srv/tftp
dhcp-option=option:ntp-server,192.168.50.1
# --- cache, logging ---
cache-size=2000
no-negcache
log-queries
log-dhcp
```
Lines worth calling out:
- `bind-interfaces` is not optional on a gateway. Without it dnsmasq binds every interface, and on a box with a VPN or a second NIC it starts answering queries you never intended to answer.
- `no-resolv` removes `/etc/resolv.conf` from the picture entirely, which matters because on a systemd box that file is a symlink into the systemd-resolved stub. Without `no-resolv` I would be forwarding to my own stub — a loop.
- `addn-hosts` keeps my static entries out of `/etc/hosts` and in one file I can manage with Ansible.
- `dhcp-authoritative` declares this the only DHCP server on the segment, so it can reclaim addresses and answer clients already leased elsewhere.
The static host file:
```text
# /etc/dnsmasq.hosts
192.168.50.10 nas.lan nas
192.168.50.11 printer.lan printer
192.168.50.12 pi.lan pi
192.168.50.20 media.lan media
```
With `expand-hosts` and `domain=lan`, a short query for `nas` expands to `nas.lan` automatically. That is the behaviour I want for the few hosts I always reach by first name.
## Upstream strategy and why no-negcache
For a NAT'd homelab the upstream question is simple: I want speed and no surprises. I run three public resolvers and let dnsmasq try them in order, failing over when one is slow. I do not front this with Unbound — another recursive resolver would be another daemon, and I already decided dnsmasq is enough for this network. When I need DNSSEC I swap in a single `server=` line and accept the extra latency.
Now `no-negcache`, which is easy to overlook and easy to regret. In a NAT'd network the upstream is flaky, and a bad upstream can return a SERVFAIL or a spurious NXDOMAIN for a record that actually exists. By default dnsmasq caches negative answers for the negative TTL. `no-negcache` disables that, so a record that was temporarily NXDOMAIN is re-queried immediately instead of being served stale from cache. I hit a concrete version of this in Incident 2. For a homelab where a host can be down for a minute and come back, negative caching is the wrong default.
## Validating the deployment
After every change I run the same four queries. I point dig straight at dnsmasq so I am testing my server, not the system resolver.
```bash
# static host, short name
dig @192.168.50.1 nas +short
# -> 192.168.50.10
# static host, fully qualified
dig @192.168.50.1 nas.lan +short
# -> 192.168.50.10
# reverse zone
dig @192.168.50.1 -x 192.168.50.10 +short
# -> nas.lan.
# upstream passthrough
dig @192.168.50.1 example.com +short
# -> 93.184.216.34
```
`host` is lighter when I am on a client without dig:
```bash
host nas 192.168.50.1
# nas.lan has address 192.168.50.10
```
From a client I confirm the running resolver two ways, depending on distro:
```bash
nmcli dev show | grep DNS
resolvectl status | grep 'DNS Servers'
```
Both should list 192.168.50.1, and on a systemd-resolved client `resolvectl status` should show the LAN address as the upstream rather than 127.0.0.53.
## DHCP and static leases
The DHCP half is where I nail infrastructure down so DNS and DHCP agree. `dhcp-host` takes the MAC, the name, and the address, and dnsmasq injects that name into DNS when `expand-hosts` is on.
```conf
dhcp-host=aa:bb:cc:dd:ee:01,nas,192.168.50.10
dhcp-host=aa:bb:cc:dd:ee:02,printer,192.168.50.11
```
The router option is critical: `dhcp-option=option:router,192.168.50.1` tells every client where its gateway is. I also push the DNS server so clients do not silently fall back to a public resolver behind my back.
Leases live in `/var/lib/misc/dnsmasq.leases` on Debian and `/var/lib/dnsmasq/dnsmasq.leases` on Arch. Each line is:
```text
```
Checking the lease file is the fastest way to see who is on the network and whether an address is still held. If a lease is in the file but the host is gone, the address stays reserved until the expiry passes, which is why the `12h` lease time on `dhcp-range` matters.
## Three incidents I actually hit
### Incident 1: silent failure on port 53
This is the trap from earlier. dnsmasq reported success, clients got no DNS, and the only clue was `ss -lunp | grep ':53 '` showing systemd-resolved on 127.0.0.53. Fix: stop and mask systemd-resolved on the dedicated box, repoint the resolv.conf, restart dnsmasq, then watch the journal for the bind line. It took me longer than it should have because nothing screamed.
### Incident 2: stale negative cache after an upstream change
I moved from one upstream to a new pair, and a host that had been briefly NXDOMAIN kept failing even after it came back. The old negative answer was being served from cache for the full negative TTL. Adding `no-negcache` and restarting made the record resolve on the very first query. Lesson: in a NAT'd network, never let a negative answer outlive the outage that caused it.
### Incident 3: overlapping DHCP ranges and a rogue server
A second config on another box had a `dhcp-range` that overlapped my primary, and the router's built-in DHCP was still enabled. Clients pulled two different addresses and occasionally an APIPA 169.254.169.254 when a lease expired at the wrong time. The fix was non-overlapping ranges, `dhcp-authoritative`, and disabling the router DHCP. From then on the log lease output matched reality.
## 15-command cheat sheet
```bash
systemctl status dnsmasq # is the daemon up
systemctl restart dnsmasq # apply config changes
systemctl reload dnsmasq # reload without dropping leases
dnsmasq --test # syntax-check the config
dnsmasq --test -C /path/to/conf # check a specific config file
ss -lunp | grep ':53 ' # who holds DNS
ss -lunp | grep ':67 ' # who holds DHCP
cat /var/lib/misc/dnsmasq.leases # current leases
dig @192.168.50.1 nas +short # static host
dig @192.168.50.1 -x 192.168.50.10 # reverse lookup
dig @192.168.50.1 example.com # upstream passthrough
host printer 192.168.50.1 # lightweight check
resolvectl status # client-side resolver state
journalctl -u dnsmasq -f # live logs
pkill -HUP dnsmasq # manual reload if needed
```
## FAQ
**Why does dnsmasq fail silently when systemd-resolved is running?**
systemd-resolved binds 127.0.0.53:53 by default, so dnsmasq cannot grab the port. Check with `ss -lunp | grep ':53 '`, then stop systemd-resolved or point dnsmasq at a different listen address.
**Can dnsmasq do DNS without DHCP?**
Yes. Remove the `dhcp-range` section and it becomes a pure DNS forwarder. You can also keep DHCP but split the gateway role onto a separate box for easier rollback.
**What does no-negcache actually do and when do I need it?**
It stops dnsmasq caching negative answers, so a record that was temporarily NXDOMAIN is re-queried immediately. In a NAT'd home network with flaky upstreams, it prevents stale negative results.
**How do I validate a dnsmasq deployment?**
Run dig against the dnsmasq IP for a static host, a short name (expand-hosts), a reverse lookup, and an upstream name. Each should return the expected record; a missing one points to a config or upstream issue.
**Where do leases live and how do I check expiry?**
On Debian they are in `/var/lib/misc/dnsmasq.leases`, on Arch in `/var/lib/dnsmasq/dnsmasq.leases`. Each line starts with the expiry epoch, so I can compare it to `date +%s` to see how much time a lease has left.
## Related Articles
- [DNS Resolution End-to-End: Recursive vs Iterative, TTL, dig +trace, EDNS0](dns-resolution.md)
- [DNS Troubleshooting: Six-Symptom Decision Tree with dig +trace](dns-troubleshoot.md)
- [CDN Internals: Edge POP, Origin Fetch, Cache Invalidation & the Cost Model](cdn-principles.md)
---
## Debugging nginx 502 in Docker: The 127.0.0.1 Trap, DNS Cache, and Healthcheck Gaps
URL: https://ops.jiunotes.top/en/network/docker-nginx-502.md
摘要: A working engineer's field guide to nginx 502 inside Docker Compose. Five root causes in order of frequency: proxy_pass pointing at 127.0.0.1 inside the container, nginx caching a stale backend IP after a container restart, no healthcheck so traffic arrives before the app is ready, an undersized upstream zone, and a host-mode network that bypasses Docker DNS. Includes a one-shot diagnostic script and a production compose template.
### Answer
nginx 502 in Docker is one of five things: proxy_pass to 127.0.0.1 (which is the nginx container itself, not the host), a stale cached backend IP after restart, no healthcheck so traffic arrives before the app is ready, an upstream zone too small for resolve, or a host-mode network that bypasses Docker DNS. Fix most: proxy_pass the service name, add a resolver with a short valid period, gate nginx on service_healthy.
### FAQ
Q: In Docker, should proxy_pass use an IP or the service name?
A: Always the service name from docker-compose.yml, like proxy_pass http://backend:8000. Docker's embedded DNS (127.0.0.11) resolves it to the container IP. Using 127.0.0.1 points at the nginx container's own loopback, which has nothing on port 8000 - connection refused, 502.
Q: Why does nginx 502 after a container restart when the config never changed?
A: nginx resolves the upstream hostname once and caches the IP. When the backend container restarts it gets a new IP, but nginx keeps sending to the old one. Fix with a variable proxy_pass plus resolver 127.0.0.11 valid=10s (works on any nginx), or on OpenResty with the resolve keyword on the upstream server (native nginx has no per-upstream re-resolve switch).
Q: What does a healthcheck actually buy me?
A: depends_on only waits for the container to start, not for the app to be ready. Without a healthcheck, nginx starts and forwards traffic into a backend that is still opening its database pool, and the backend crashes. Gate nginx on depends_on: backend: condition: service_healthy.
Q: I added resolve on OpenResty but it will not start. What is the error about?
A: The OpenResty resolve keyword requires a resolver directive and a shared-memory zone. If the zone is too small it fails at startup with a 'no memory' or 'zone' error. Add resolver 127.0.0.11 valid=10s and bump the zone to at least 64k: zone backend_zone 64k. Search docker logs nginx for 'zone' to confirm.
Q: What is the fastest way to check the upstream from inside the container?
A: Three commands: docker exec nginx nginx -t to validate the config, docker exec nginx curl -v http://backend:8000/health to test reachability, and docker logs nginx to read the exact error. The error text tells you which of the five causes it is - refused, timed out, or host not found.
### Full Content
# Debugging nginx 502 in Docker: The 127.0.0.1 Trap, DNS Cache, and Healthcheck Gaps
I lost two days to a 502 once. The [nginx](https://nginx.org/en/docs/) config looked perfect, `curl` from the host worked, and the backend was healthy. Then I ran `docker exec nginx curl http://backend:8000/health` from inside the container and got connection refused, and finally understood: the `proxy_pass` said `127.0.0.1`, and inside the container `127.0.0.1` is the nginx container itself, not the host, not the backend. This article is the field guide I wish I had that day - the five root causes of [Docker](https://docs.docker.com/)-era 502s, in the order I actually see them.
## Why Docker Made 502 Easier to Hit
On a bare server, a 502 usually means the backend is down or the port is wrong. Docker adds three new dimensions, because each container has its own network namespace:
```
Bare metal: backend down -> 502
Docker: backend container not up yet -> 502
Docker: backend container restarted, new IP -> 502
Docker: proxy_pass written as 127.0.0.1 -> 502
Docker: nginx starts faster than the app -> 502
```
The common thread is that the meaning of "the backend" changes. In a container, `127.0.0.1` is only ever yourself. It is never the host, and never a sibling container.
## Trap 1: proxy_pass to 127.0.0.1
The most common and the most invisible. It looks right to anyone who has written nginx on a server:
```nginx
# WRONG - 127.0.0.1 is this container's own loopback
upstream backend {
server 127.0.0.1:8000;
}
# RIGHT - backend is the service name in docker-compose.yml
upstream backend {
server backend:8000;
}
```
Why it is wrong: nginx lives in a container, so `127.0.0.1:8000` is a port inside the nginx container itself. Nothing listens there, so every request is `connection refused`, and nginx returns 502. There is no error that tells you this - it just looks like a broken backend.
The verification is instant:
```bash
# Is anything listening on 8000 inside the nginx container?
docker exec nginx ss -tlnp | grep 8000
# empty output = nothing here, that is your trap
# Test the real service name directly
docker exec nginx curl -v http://backend:8000/health
# should return a healthy response
```
## Trap 2: Stale DNS After a Container Restart
Docker's embedded DNS at `127.0.0.11` resolves the service name to an IP. nginx resolves the upstream once and then holds that IP. Here is the failure sequence: nginx starts first and caches the backend IP; the backend container restarts during a deploy and gets a new IP; nginx keeps sending to the old IP. Every request hits a dead address, so you get 502 for a window that can last as long as the cache.
Two fixes. The first works on any nginx:
```nginx
server {
resolver 127.0.0.11 valid=10s ipv6=off;
location / {
set $upstream http://backend:8000;
proxy_pass $upstream;
}
}
```
The second is OpenResty only (not native nginx) — the `resolve` keyword on an upstream server is an OpenResty directive and it requires a `resolver`:
```nginx
upstream backend {
server backend:8000 resolve;
resolver 127.0.0.11 valid=10s;
zone backend_zone 64k;
}
```
I was bitten by this on a rolling deploy. The old container stopped, the new one came up on a different IP, and for about thirty seconds every request 502'd. Adding `resolver 127.0.0.11 valid=10s` made the window disappear.
## Trap 3: No Healthcheck, Traffic Arrives Too Early
`depends_on` only waits for the container to be *running*. It does not wait for the application to be *ready*. A backend container can be up and still initializing its database connection pool for thirty seconds. If nginx is already forwarding, those requests hit an app that is not ready and can knock it over.
```yaml
# WRONG - only waits for container start
services:
nginx:
depends_on:
- backend
# RIGHT - wait until the app answers a health probe
services:
backend:
image: my-backend:latest
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
nginx:
image: nginx:1.25
depends_on:
backend:
condition: service_healthy
```
`start_period` matters. If your app needs thirty seconds to build its connection pool, that time should not count against the retries. Without it, a slow-starting app is marked unhealthy before it was ever given a chance.
## Trap 4: Upstream Zone Too Small
The `resolve` parameter needs a shared-memory zone, and the zone must be big enough. Too small and nginx fails to start or throws a zone error at runtime.
```nginx
# WRONG - 4k is not enough for a resolve zone
upstream backend {
server backend:8000 resolve;
zone backend_zone 4k;
}
# RIGHT - 64k is the safe minimum
upstream backend {
server backend:8000 resolve;
zone backend_zone 64k;
}
```
Check the log: `docker logs nginx | grep -i zone`. If you see a memory or zone complaint, raise the size.
## Trap 5: Network Isolation or Host Mode
Docker Compose creates a bridge network by default, and service-name resolution only works for services on the *same* network. Two ways to break it: put nginx and the backend on different networks, or use `network_mode: host`.
```yaml
# RIGHT - nginx and backend share one bridge network
services:
nginx:
networks: [app-network]
backend:
networks: [app-network]
networks:
app-network:
driver: bridge
```
```yaml
# WRONG - host mode bypasses Docker DNS entirely
services:
nginx:
network_mode: host
# now `backend` does not resolve; you must use the host IP
```
With host mode there is no embedded DNS, so a bare service name fails with `host not found` in the error log. The error message is the tell: `host not found in upstream` points at trap 2 or trap 5; `connection refused` points at trap 1.
## The One-Shot Diagnostic Script
I bundled the five checks into a script I run before I read anything else:
```bash
#!/usr/bin/env bash
# diagnose-nginx-502.sh - quick triage for Docker-era 502
set -u
C="${1:-nginx}"
echo "=== 1. Did someone use 127.0.0.1? ==="
docker exec "$C" grep -r "127.0.0.1" /etc/nginx/ 2>/dev/null | head -5 || echo "clean"
echo "=== 2. Is a resolver configured? ==="
docker exec "$C" grep -r "resolver" /etc/nginx/ 2>/dev/null || echo "NO RESOLVER - stale cache risk"
echo "=== 3. Reach the backend by name ==="
SVC=$(docker exec "$C" grep -oP 'server\s+\K[^:;]+' /etc/nginx/conf.d/*.conf 2>/dev/null | head -1)
if [ -n "${SVC:-}" ]; then
docker exec "$C" curl -s -o /dev/null -w "HTTP %{http_code}\n" "http://${SVC}/health" || echo "unreachable"
fi
echo "=== 4. Backend container state ==="
docker ps --filter "name=backend" --format "table {{.Names}}\t{{.Status}}"
echo "=== 5. Recent nginx errors ==="
docker logs "$C" --tail 30 2>&1 | grep -Ei "502|error|refused|timeout|host not found" || echo "none"
echo "=== 6. Upstream zone size ==="
docker exec "$C" grep -r "zone.*k" /etc/nginx/ 2>/dev/null || echo "no zone configured"
```
Run it with `./diagnose-nginx-502.sh nginx`. The output usually names the trap in under a minute.
## Two Cases From My Own Racks
**Case A: healthy-looking backend, 100% 502.** Every deploy was 502 for the first five minutes, then recovered. The backend container was running, but its database pool was not built. `depends_on` started nginx immediately, traffic hit a half-initialized app, and it OOM'd. Fix: a healthcheck with `start_period: 60s` and `condition: service_healthy`.
**Case B: weekly deploy, two-minute 502 spike.** A rolling deploy stopped the old backend and started a new one on a different IP. nginx held the old IP. Fix: `resolver 127.0.0.11 valid=10s` plus a variable `proxy_pass` so every request re-resolves.
## Production Template
The compose file and the nginx config that together avoid all five traps:
```yaml
# docker-compose.yml
services:
backend:
image: my-backend:latest
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
networks: [app-network]
nginx:
image: nginx:1.25
restart: unless-stopped
ports: ["80:80", "443:443"]
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
backend:
condition: service_healthy
networks: [app-network]
networks:
app-network:
driver: bridge
```
```nginx
# nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events { worker_connections 4096; }
http {
resolver 127.0.0.11 valid=10s ipv6=off;
upstream backend {
server backend:8000 resolve;
zone backend_zone 64k;
}
server {
listen 80;
server_name _;
location / {
proxy_pass http://backend;
proxy_connect_timeout 10s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
}
}
```
## The Decision Path I Follow
```
502 in Docker
|
+-- curl backend:8000 from inside nginx
| +-- refused -> trap 1 (127.0.0.1)
| +-- timeout -> trap 2 or trap 5 (cache / network)
| +-- host not found -> trap 2 or trap 5
|
+-- docker logs nginx | grep "host not found"
| +-- present -> check resolver and network mode
|
+-- docker ps | grep backend
| +-- unhealthy -> check healthcheck / start_period
| +-- running -> continue
|
+-- docker logs nginx | grep -i zone
+-- zone error -> raise upstream zone to 64k
```
## 502 vs 504: Where Slow-Upstream Meets Refused-Upstream
A common field question is "why is it 502 sometimes and 504 other times." The boundary is clean: **502 means nginx could not connect, or the backend refused directly** (Connection refused / reset — that is most of traps 1, 3, and 5); **504 means the connection was established but the backend did not finish its response within `proxy_read_timeout`** (a slow, hung, or long-running backend). In practice, read error.log first: `connect() failed` is the 502 path, `upstream timed out` is the 504 path. Do not reach for DNS or healthcheck fixes on a 504 — those are 502 cures. On a 504, check whether a slow query or a long-lived connection has pinned the backend's workers, then align `proxy_read_timeout` with the backend's longest legitimate response and add a circuit breaker or graceful degradation for the timed-out slice. Treating 502 and 504 as the same problem is the fastest way to "fix" for an hour and fix nothing.
## FAQ and Originality Statement
The short version of everything above: **inside a container, `127.0.0.1` is never where you want to go.** Use the service name, re-resolve with a short `valid`, gate startup on `service_healthy`, give the `resolve` zone 64k, and keep nginx and the backend on the same bridge network. Those five habits remove the vast majority of Docker-era 502s.
This article is my own work, written from the incidents described. The diagnostic script, the production template, and the case framing are original and were not translated from any other source.
## Related Articles
- [Nginx Reverse Proxy: The 502 / 504 Root-Cause Decision Tree](nginx-proxy.md)
- [Nginx Upstream Configuration and Load Balancing](nginx-upstream-config.md)
- [Nginx Keepalived for High Availability](nginx-keepalived.md)
---
## Edge Computing Network Design: Getting Latency Down by Moving the Work Closer
URL: https://ops.jiunotes.top/en/network/edge-computing-network.md
摘要: A working engineer's approach to edge network latency. Where the milliseconds actually go (DNS, transit, node processing, return path), the three levers that matter - anycast + CDN for static traffic, a user-density edge node placement model, and a lightweight service mesh for east-west calls - and a real game server case that cut southern-region latency by 80%. Includes the Linkerd mesh config and the Prometheus latency alerts I run at the edge.
### Answer
Edge latency is mostly a network problem: the round trip dominates, not compute. Three levers lower it. Anycast DNS plus CDN edge caching takes static load off the origin. Placing nodes by user density cuts the transit hop for dynamic requests. A lightweight service mesh keeps east-west calls inside a region instead of crossing the backbone. A game case cut southern latency from 130ms to 25ms.
### FAQ
Q: How is edge computing different from cloud computing?
A: Cloud is centralized in a few large datacenters; edge is distributed close to users. Cloud suits batch and analytics work; edge suits real-time, latency-sensitive work. They are complements - edge handles the near field, cloud handles the heavy lifting.
Q: How many edge nodes do I need?
A: It depends on the traffic. Live video and games want dense coverage, roughly one node per 50-100km. Web and API can be coarser, one per major city. IoT can be sparse, one per region. If the budget is tight, cover the user-dense areas first - that is where the latency pain is.
Q: Is a service mesh mandatory at the edge?
A: Not mandatory, but strongly recommended once you have more than a handful of nodes. Without it, east-west calls take the slow path and failures spread cluster-wide. Linkerd is the lightest option and is enough for small and medium edge fleets; Istio is more capable but heavier.
Q: Why is my edge node healthy but users still see high latency?
A: Because you placed the node in the wrong place. A node in a datacenter far from the users adds transit time no amount of tuning removes. Check the user-to-node distance first - a node with a 300km coverage radius can never serve a 30ms goal.
Q: What should I measure before and after an edge rollout?
A: P95 latency per region, the round-trip from user to node, the cache hit ratio, and origin bandwidth. Run a per-node latency alert at 100ms for 5 minutes. The number that matters is not average latency - it is the P95 and the tail.
### Full Content
# Edge Computing Network Design: Getting Latency Down by Moving the Work Closer
The most common mistake I see in edge projects is thinking it is a compute problem. Teams deploy edge nodes, tune the server, and wonder why latency is still high. It is high because the network path - the round trip from user to node and back - is the dominant cost, and no amount of CPU tuning fixes a bad path. This article is about the three levers that actually move the number: anycast plus CDN for static traffic, a placement model for where nodes go, and a service mesh for the traffic that never leaves the region.
## Where the Latency Actually Lives
Before optimizing, break the request into its parts. Most teams skip this and end up tuning the wrong stage:
```
user request -> DNS -> transit (forward) -> node processing -> transit (return)
```
| Stage | Typical latency | What moves it |
|---|---|---|
| DNS resolution | 10-100ms | Anycast DNS, local cache |
| Transit, forward | 20-200ms | Nearby ingress, BGP anycast |
| Node processing | 5-50ms | Pre-warmed cache, pre-allocated resources |
| Transit, return | 20-200ms | Edge cache, nearby origin |
The two transit stages combined are usually 50-70% of the total. That is the lever. Cutting compute by ten milliseconds is worth less than cutting the path by fifty.
## Lever 1: Anycast DNS and CDN for Static Traffic
CDN is the most mature form of edge computing, and it is the cheapest win because it needs almost no work on your side. The static assets - images, JS, CSS, video - get cached at the edge, and anycast DNS sends the user to the nearest cache.
Anycast is the subtle half that people miss. With anycast, the same IP is announced from many sites, and BGP routes the user to the nearest one. That is what turns "resolve to a fixed origin" into "resolve to wherever you already are":
```bash
# Point the static domain at the CDN with a short TTL so you can
# switch back quickly if needed.
# In your DNS provider: set TTL to 300 (5 min) on the CNAME for
# static.example.com -> cdn-provider.example.net
```
On a real retail deployment I tracked, the CDN alone did most of the work:
| Metric | No CDN | With CDN edge cache |
|---|---|---|
| Homepage load | 3.2s | 0.8s |
| Image load | 1.5s | 0.2s |
| Global P95 latency | 800ms | 150ms |
| Origin bandwidth saved | - | 85% |
The rule I follow: **static traffic never touches the origin.** If it does, the CDN is misconfigured, and that is a configuration bug, not a capacity problem.
## Lever 2: Placing Nodes Where the Users Are
This is the lever that is almost always done wrong, because the convenient location is rarely the right one. Placement should follow user density. The model I use weighs three things: how many users are in a cluster, how far they are from the nearest node, and the cost of putting a node there.
```python
import math
def haversine(a, b):
lat1, lon1 = a
lat2, lon2 = b
r = 6371 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
x = math.sin(dlat/2)**2 + math.cos(math.radians(lat1)) \
* math.cos(math.radians(lat2)) * math.sin(dlon/2)**2
return 2 * r * math.asin(math.sqrt(x))
def plan_nodes(user_clusters, existing_nodes, budget):
"""user_clusters: [(lat, lon, count)]. Returns new node coords."""
candidates = []
for cl in user_clusters:
nearest = min((haversine(cl[:2], n) for n in existing_nodes),
default=float('inf'))
# Weight by users, penalize distance.
score = cl[2] / (nearest + 1.0)
candidates.append({'cluster': cl, 'score': score})
candidates.sort(key=lambda c: c['score'], reverse=True)
new_nodes = []
for cand in candidates:
if budget <= 0:
break
# Place the node at the cluster centroid.
lat, lon, count = cand['cluster']
new_nodes.append((lat, lon))
budget -= deploy_cost(count)
return new_nodes
```
The honest version: the model gives you a shortlist; the real decision is a map. Draw the user heatmap, overlay the shortlist, and check the coverage radius against the latency target. A node with a 300km radius can never meet a 30ms goal.
## Lever 3: A Lightweight Service Mesh for East-West Traffic
Once you have nodes, the traffic that hurts most is the traffic that never leaves the region but still crosses the backbone because nothing told it to stay local. A service mesh gives you two things: routing that prefers the in-region backend, and circuit breaking so a bad node does not take the whole fleet down.
I default to Linkerd at the edge because it is light - a small memory and CPU budget per proxy is worth it at the edge, where a single node may be a smaller machine than a central datacenter host:
```yaml
# Linkerd ProxyConfig - tuned for edge nodes
apiVersion: install.linkerd.io/v1alpha2
kind: ProxyConfig
metadata:
name: edge-proxy
spec:
proxy:
resources:
requests:
memory: 64Mi
cpu: 50m
limits:
memory: 128Mi
cpu: 100m
# Connection pool: keep a few warm so first-call latency stays low
connection_pool:
outbound:
min_idle_connections: 10
max_idle_connections: 100
max_life_time: 30s
# Fail fast; do not let a dead peer eat the request budget
connectivity_timeout: 100ms
request_timeout: 2s
```
The `connectivity_timeout: 100ms` line is the important one. At the edge you want a failed peer detected fast and routed around, not a slow timeout that stacks.
## The Edge Topology on [Kubernetes](https://kubernetes.io/docs/)
I run the edge services on Kubernetes so the placement and the mesh share one control plane. The route that keeps traffic in-region is an HTTPRoute that prefers the local backend:
```yaml
apiVersion: gateway.networking.k8s.io/v1beta1
kind: Gateway
metadata:
name: edge-gateway
spec:
gatewayClassName: edge-controller
listeners:
- name: http
port: 80
hostname: "*.example.com"
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: HTTPRoute
metadata:
name: edge-route
spec:
parentRefs:
- name: edge-gateway
hostnames: ["*.example.com"]
rules:
- matches:
- path:
type: PathPrefix
value: /live/
backendRefs:
- name: edge-media-chengdu
port: 8080
- name: edge-media-wuhan
port: 8080
```
This is where the mesh earns its keep. Without it, a request for `/live/` from Chengdu might get routed to Wuhan, cross the backbone, and add tens of milliseconds for no reason.
## Real Case: An Online Game's Southern Latency
The case that convinced me was an online game. The single datacenter was in the north, and southern players sat at 120-150ms, which is the difference between playable and frustrating.
The change was threefold: add nodes in the south and west, point DNS at the nearest node via anycast, and let the mesh route in-region. I did not touch the game server code at all.
| Player region | Before | After | Change |
|---|---|---|---|
| North (Beijing) | 15ms | 12ms | -20% |
| South (Guangzhou) | 130ms | 25ms | -81% |
| West (Chengdu) | 110ms | 20ms | -82% |
| Central (Wuhan) | 95ms | 18ms | -81% |
| Satisfaction | 65% | 92% | +42% |
The lesson: I did not make the game faster. I made the path shorter, which is the same thing and much cheaper.
## Observability at the Edge
You cannot manage latency you cannot see. The two metrics I alert on at the edge are node latency and node liveness:
```yaml
groups:
- name: edge-latency
rules:
- alert: EdgeNodeHighLatency
expr: edge_node_latency_seconds > 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "Edge node {{ $labels.node }} high latency"
description: "Latency is {{ $value }}s, threshold is 0.1s"
- alert: EdgeNodeDown
expr: up{job="edge-node"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Edge node {{ $labels.node }} is down"
```
The 100ms threshold is not arbitrary - it is roughly the point where a user stops noticing a delay in an interactive app. If your P95 is under 100ms, stop chasing latency and start chasing reliability.
## The Rollout Order I Recommend
For a latency-sensitive business, I would do this in sequence, not all at once:
1. **CDN first.** Cheapest, lowest risk, biggest visible win. Takes a week.
2. **Edge nodes second.** Place by user density, cover the painful regions first.
3. **Service mesh last.** Only after you have more than a handful of nodes and east-west traffic is actually crossing regions. This is the most complex and most valuable at scale.
The whole thing is three to six months. Do not try to land it in a week; a rushed edge rollout with bad placement is worse than no rollout, because it gives the impression of progress while the latency number does not move.
## FAQ and Originality Statement
My verdict, after doing this a few times: the phrase "edge computing" is really about one idea - put the work where the user is. If you keep that idea front and center, the CDN choice, the placement model, and the mesh all fall into place. If you lose it, you will end up with a distributed cluster that is no faster than the single datacenter you started with.
This article is my own work, written from the deployments described here. The placement model, the mesh config, the game case, and the framing are original to this piece and were not translated from any other source.
## Related Articles
- [CDN Principles and Edge Caching](cdn-principles.md)
- [DNS Troubleshooting: Six-Symptom Decision Tree](dns-troubleshoot.md)
- [TCP Troubleshooting: ss + tcpdump Decision Tree](tcp-troubleshoot.md)
---
## Network & DNS · All 42 Articles Hub
URL: https://ops.jiunotes.top/en/network.md
摘要: The Network & DNS hub gathers all 42 articles grouped by type. Same-topic notes live under one section — click any title to jump to the hands-on note. Built for internal cross-linking.
### Full Content
# Network & DNS · All 42 Articles
This page groups all **42** Network & DNS articles by type. Same-topic notes sit under one section so you can jump straight to the hands-on note you need, and hop between related pieces.
**Where to start:** new here? begin with [Nginx Reverse Proxy 502/504 Troubleshooting — Full Decision Tree](nginx-proxy.md), then pick a section below.
## Troubleshooting Decision Trees
- [Internal DNS resolution failure decision tree — internet works but the intranet OA won't open](network-internal-dns-failure.md) — A classic office-network failure — clients can reach the internet and chat apps, but the internal OA portal wo…
- [Multi-WAN policy route misconfiguration decision tree — WeChat sends images but Feishu cannot](network-multiwan-policy-route.md) — A classic office-network failure — WeChat images go through fine, but Feishu cannot send images or files while…
- [Endpoint time skew and root-certificate decision tree — "certificate error" on web login](network-endpoint-time-cert-error.md) — A classic office-network failure — the finance/business web portal greets login with \"certificate error\" or …
- [Return-to-office network anomaly decision tree — on company Wi-Fi but can't reach the share drive](network-return-to-office-network-reset.md) — A classic office-network failure — after a trip or working from home, staff connect to company Wi-Fi but canno…
- [Endpoint driver-baseline conflict decision tree — no sound / speaker stays on with headphone plugged in](network-driver-baseline-conflict.md) — A classic endpoint failure — staff report the PC suddenly has no sound, or the speaker keeps playing after a h…
## DNS Resolution & Troubleshooting
- [DNS Resolution End-to-End: Recursive vs Iterative, TTL, dig +trace, EDNS0](dns-resolution.md) — A working engineer's guide to how DNS actually works: stub resolver, recursive resolver, iterative chain (root…
- [DNS Troubleshooting: Six-Symptom Decision Tree with dig +trace](dns-troubleshoot.md) — A working engineer's DNS troubleshooting guide: six-symptom decision tree (NXDOMAIN, SERVFAIL, timeout, CNAME …
- [DNS over HTTPS in Production: Encrypting the Last Plaintext Protocol](dns-over-https-doh-configuration.md) — First-person guide to deploying DNS over HTTPS (DoH) on a server, a whole LAN, and an internal resolver: cloud…
- [dnsmasq Configuration Deep Dive: A Production-Ready Template and the Port-Conflict Trap](dnsmasq-config.md) — dnsmasq runs DNS, DHCP and NTP from one process — but systemd-resolved grabbing port 53 is the trap that break…
## Nginx Reverse Proxy & Errors
- [Nginx Reverse Proxy 502/504 Troubleshooting — Full Decision Tree](nginx-proxy.md) — A working engineer's guide to diagnosing 502 Bad Gateway and 504 Gateway Timeout behind Nginx reverse proxy. 5…
- [Debugging nginx 502 in Docker: The 127.0.0.1 Trap, DNS Cache, and Healthcheck Gaps](docker-nginx-502.md) — A working engineer's field guide to nginx 502 inside Docker Compose. Five root causes in order of frequency: p…
- [Nginx 504 Gateway Timeout: Six Root-Cause Branches in a Decision Tree](nginx-504-troubleshoot.md) — A working engineer's 504 troubleshooting guide: what 504 really means, the five protocol-level differences fro…
- [Nginx Upstream Keepalive: The Default of 8, the Backend Differences, and Five Real 502 Cases](nginx-keepalive-502.md) — A working engineer's guide to nginx upstream keepalive: the three parameters (keepalive, keepalive_timeout, ke…
- [nginx Upstream Load Balancing: Algorithm Selection, Server Directives, and the keepalive Trio](nginx-upstream-config.md) — Upstream block internals for SREs: 6 load balancing algorithms with a decision matrix, per-server parameter va…
- [nginx + keepalived VIP Failover: Parameter Matrix and 6 Production Incidents](nginx-keepalived.md) — Full keepalived parameter matrix with production-safe values, 6 real failure modes with root causes, 15-comman…
- [Rolling Out ModSecurity 3.0 WAF on Production nginx: Five Incidents, False Positives, and One Hard-Won Config](nginx-waf-modsecurity.md) — First-person notes on compiling ModSecurity 3.0 as a dynamic nginx module, wiring OWASP CRS, and taming false …
## Packet Capture & Protocol Analysis
- [TCP/IP Internals: Layered Model, Handshake, Teardown, RTO, CUBIC vs BBR](tcp-ip.md) — A working engineer's guide to TCP/IP internals: OSI vs TCP/IP layering, three-way handshake and four-way teard…
- [TCP Troubleshooting: TIME_WAIT / RST / SYN Half-Open / Retransmission](tcp-troubleshoot.md) — TCP troubleshooting decision tree: TIME_WAIT floods, RST storms, SYN half-open, retransmission spikes. 20-comm…
- [Wireshark Basics: 30 Filters, TCP RST/Retrans Analysis & tcpdump Cross-Reference](wireshark-basics.md) — A working engineer's Wireshark guide: 30+ display filters by layer (network, transport, TCP-analysis, HTTP/2, …
- [Wireshark Capture in Practice: Finding the Root Cause of nginx 502 / 504](wireshark-nginx-troubleshoot.md) — A first-person nginx 502/504 troubleshooting chain built on packet capture: identifying who sent the RST, veri…
- [Kubernetes Network Troubleshooting: A Layer-by-Layer Decision Tree and Five Real Incidents](kubernetes-network-troubleshoot.md) — A first-person walkthrough of Kubernetes networking failures: a decision tree from DNS to Service endpoints, k…
## Tunnels / VPN / Zero-Trust
- [WireGuard Site-to-Site VPN: Wiring Two Gateways and Routing Them Right](wireguard-site-to-site-vpn-setup.md) — How to build a WireGuard site-to-site VPN between two networks. A copyable two-gateway setup covering keypair …
- [Self-Hosting Behind a Cloudflare Tunnel: Exposing Services Without Opening Inbound Ports](cloudflare-tunnel-self-hosted.md) — Expose a self-hosted app or SSH server to the internet with zero inbound ports using cloudflared: architecture…
- [Zero Trust Network Architecture: From Concept to Enterprise Landing](zero-trust-network.md) — A first-person zero trust implementation guide: the three principles (identity as root, continuous verificatio…
- [SASE in Practice: Three Real Landing Paths When SD-WAN Meets Security Policy](sase-security.md) — SASE field guide for operators: three landing paths after merging SD-WAN with the security stack, a ZTNA vs VP…
- [Micro-segmentation: Cutting the Flat Network Before the Attacker Does](micro-segmentation.md) — A working engineer's micro-segmentation playbook: why lateral movement wins in flat networks, the three design…
## WAN / SD-WAN / Multi-Cloud
- [SD-WAN Deployment in Practice: Sizing, Config & Two Failures I Caused](sd-wan-deploy.md) — A first-person SD-WAN deployment guide: three-dimensional sizing (branch count, app mix, budget), VyOS branch …
- [SD-WAN vs MPLS in Production: A Cost, Latency, and Migration Decision Walkthrough](sd-wan-vs-mpls-comparison.md) — First-person comparison of SD-WAN and MPLS: when each wins, how to read the real cost math, what jitter budget…
- [Multi-Cloud Networking: Choosing the Right On-Ramp and Designing the Backbone](multicloud-network.md) — A working engineer's multi-cloud networking guide: Direct Connect vs ExpressRoute vs CEN, when VPN beats a lea…
## TLS / Certificates / Time
- [SSL/TLS Handshake Troubleshooting: A Decision Tree for Six Root Causes](ssl-tls-handshake-troubleshoot.md) — A working engineer's TLS handshake troubleshooting decision tree: openssl s_client parameter matrix (30+ flags…
## IPv6
- [IPv6 Deployment and Migration: Dual-Stack Transition Without the Fire Drill](ipv6-migration.md) — A working engineer's path to IPv6. Why dual-stack is the right first move, when tunneling is a stopgap and not…
- [IPv6 Transition in Practice: Dual Stack, 6in4, NAT64, and What to Actually Run](ipv6-transition-tunneling.md) — First-person guide to choosing and deploying IPv6 transition: why dual stack is always the first choice, the f…
## Routing & Firewall
- [BGP Route Leak Prevention: RPKI, ASPA and the Layered Prefix Filter](bgp-route-leak-prevention.md) — How to stop BGP route leaks before they spread. A layered defence covering RPKI ROV origin validation, ASPA pa…
- [iptables Port Forwarding in Production — SNAT/DNAT Chain Architecture, Failure Modes, and nftables Migration](iptables-port-forwarding.md) — Production iptables port forwarding: full SNAT/DNAT chain architecture, conntrack pitfalls, 5 real failure mod…
## Tuning / Time / AI Ops
- [Linux Network Kernel Tuning: A sysctl + TCP Congestion Control Playbook](linux-network-tuning.md) — A production playbook for Linux network kernel tuning: tiered tcp_* matrix with rollbacks, BBR vs CUBIC vs Ren…
- [CDN Internals: Edge POP, Origin Fetch, Cache Invalidation & the Cost Model](cdn-principles.md) — A working engineer's guide to how CDNs actually work: Edge POP tiers, origin fetch on MISS, Cache-Control sema…
- [Edge Computing Network Design: Getting Latency Down by Moving the Work Closer](edge-computing-network.md) — A working engineer's approach to edge network latency. Where the milliseconds actually go (DNS, transit, node …
- [Linux Time Sync in Production: A chrony Template and Five Real Clock-Drift Failures](ntp-time-sync.md) — A working engineer's time-sync guide: why clock drift silently breaks TLS, Kerberos, and monitoring, the chron…
- [AIOps for Network Operations: Anomaly Detection, Failure Prediction, and Intelligent Traffic Steering](aiops-network.md) — A working engineer's path from static thresholds to AIOps: why CPU>90% rules drown you in noise, the four-laye…
## Other / Unsorted
- [Synology DSM Services Not Starting After an Upgrade: A Five-Layer Triage Tree](synology-dsm-update-services-not-starting.md) — A triage tree for Synology DSM packages and services that fail to start after an upgrade: separate a dead NAS,…
- [Synology SSH Permission Denied: A Five-Layer Triage Tree](synology-ssh-permission-denied.md) — A triage tree for Synology SSH Permission denied, failed root logins, and sudo privilege failures: separate ac…
- [Synology Third-Party Package Install Failed: A Five-Layer Triage Tree](synology-third-party-package-install-failed.md) — A triage tree for failed Synology SPK installs and Package Center errors: separate signing and trust settings,…
---
**Other columns:** [Monitoring & Security](../monitor/index.md) · [Home Assistant](../homeassistant/index.md) · [AI for Ops](../ai/index.md) · [Postmortems](../postmortems/index.md) · [Ops Tools](../tools/index.md) · [Reference](../reference/index.md)
---
## iptables Port Forwarding in Production — SNAT/DNAT Chain Architecture, Failure Modes, and nftables Migration
URL: https://ops.jiunotes.top/en/network/iptables-port-forwarding.md
摘要: Production iptables port forwarding: full SNAT/DNAT chain architecture, conntrack pitfalls, 5 real failure modes with packet captures, and a migration path to nftables for Ubuntu 22.04+. First-person ops guide with 15 copy-paste commands.
### Answer
iptables port forwarding is DNAT on the FORWARD chain plus a return-path ESTABLISHED rule — that's the whole mechanic. The five failure modes I've hit in production: stateful firewall reset on kernel upgrade, conntrack table exhaustion under bursts, MASQUERADE vs SNAT confusion on non-local IPs, NAT bypass from a second gateway, and iptables vs nftables coexistence on Ubuntu 22.04+.
### FAQ
Q: What's the minimal iptables rule to forward traffic from an external port to an internal host?
A: Four rules minimum: (1) `iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80`, (2) `iptables -A FORWARD -d 192.168.1.10 -p tcp --dport 80 -j ACCEPT`, (3) `sysctl net.ipv4.ip_forward=1`, (4) `iptables -t nat -A POSTROUTING -s 192.168.1.10 -d -j SNAT --to-source `. Miss any one and traffic dies somewhere in the chain.
Q: Why does my port forward stop working after a reboot?
A: Because iptables rules are in-memory by default. Either install `iptables-persistent` (`apt install iptables-persistent; netfilter-persistent save`) or export your ruleset with `iptables-save > /etc/iptables/rules.v4` and add an ifup hook to reload them on boot.
Q: MASQUERADE vs SNAT — which should I use?
A: Use SNAT when your public IP is a static IP on a local interface. Use MASQUERADE when the public IP is dynamic (e.g., NAT gateway, cloud egress IP). MASQUERADE re-resolves the source IP at rule evaluation time, which adds ~0.1ms latency per packet and is measurably slower under high load.
Q: How do I migrate from iptables to nftables without breaking traffic?
A: On Ubuntu 22.04+ they already coexist (iptables commands actually proxy to nftables). To do a clean migration: (1) `apt remove iptables; apt install nftables`, (2) run `iptables-save | /usr/share/nftables/iptables-nft.sh` to convert rules, (3) verify with `nft list ruleset` that the NAT table exists, (4) test traffic with `tcpdump -i eth0 -n 'tcp dst port 80'` before rolling out.
### Full Content
# iptables Port Forwarding in Production — SNAT/DNAT Chain Architecture, Failure Modes, and nftables Migration
I've been on-call for a home-office NAT box and a small regional POP that each forward a handful of public ports into private VLANs. That sounds simple until 3 a.m. someone's Slack channel goes red because port 8443 stopped accepting handshakes.
This article is a distillation of those nights. I'm going to walk you through the actual chain of rules that makes port forwarding work, why each rule is non-optional, the five failure modes I've personally paged on, and a clean path from iptables to nftables on modern Ubuntu.
## 1. The Four-Rule Minimum
The whole mechanic of port forwarding is: rewrite the destination before the packet hits the router's local tables, let the FORWARD chain pass it, keep the state, then rewrite the source so the return trip comes back through you. The private ranges this box forwards into (192.168.1.0/24 below) are defined by [RFC 1918](https://www.rfc-editor.org/rfc/rfc1918), and the public port being rewritten (80) is the [IANA](https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml)-registered http/tcp port.
```bash
# (1) Rewrite the destination on the way in
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 \
-j DNAT --to-destination 192.168.1.10:80
# (2) Allow the forwarded packet through
iptables -A FORWARD -i eth0 -o eth1 -d 192.168.1.10 \
-p tcp --dport 80 -j ACCEPT
# (3) Allow the return path without re-inspecting it
iptables -A FORWARD -i eth1 -o eth0 -s 192.168.1.10 \
-p tcp --sport 80 -m state --state ESTABLISHED,RELATED -j ACCEPT
# (4) Rewrite the source so the originator sees your IP
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.10 \
-j SNAT --to-source 203.0.113.10
```
Remove any single rule and one leg of the trip silently dies. I have removed rule (3) a hundred times by accident while cleaning up a filter table. The symptom is always the same: SYN goes out, SYN-ACK comes back, gets dropped, client retries, times out. You never see an RST because you're the one killing it.
Rule (1) fires in PREROUTING before routing, so the destination you rewrite to doesn't need to be routable on the local interface — it just needs to be reachable from eth1. That's the whole point of DNAT.
## 2. conntrack State Is Not Optional
The `-m state --state ESTABLISHED,RELATED -j ACCEPT` rule on line 3 is what stops you from turning your NAT box into a stateless dumb repeater. Without it, you have to enumerate every return flow manually, which breaks the moment a client sends a mid-stream ICMP or does a bidirectional TCP push.
conntrack keeps one entry per connection (source IP, source port, dest IP, dest port, protocol, plus optional L4 marks). On my NAT box a busy afternoon pushes the table to around 40 000 entries:
```bash
$ cat /proc/sys/net/netfilter/nf_conntrack_count
38214
$ cat /proc/sys/net/netfilter/nf_conntrack_max
131072
```
Two knobs matter. `nf_conntrack_tcp_timeout_established` defaults to 432 000 seconds (5 days). If your upstream load balancer closes sessions in 15 minutes, you're holding onto slots you don't need. I set it to 900 on boxes doing a lot of short-lived TLS:
```bash
sysctl -w net.netfilter.nf_conntrack_tcp_timeout_established=900
sysctl -w net.netfilter.nf_conntrack_max=262144
```
Persist those in `/etc/sysctl.d/99-nat.conf` or they'll reset on reboot and you'll spend another Tuesday wondering why your conntrack grew.
## 3. Real Topology — One NAT Box, Two LAN Segments
My home lab NAT box is a mini-PC with two interfaces. External is on 10.0.0.1/24 behind a residential router (public IP assigned via CGNAT). Internal is a dedicated switch on 192.168.1.0/24 with three real machines and a [Docker](https://docs.docker.com/) host.
```
Internet NAT box Internal LAN
───────────┐ eth0 ┌──────────────┐ eth1 ┌─────────────────┐
203.0.113. | ───────▶ | 10.0.0.1 | │ 192.168.1.10 :80 │
.10 | | 192.168.1.1 | ────────▶│ 192.168.1.20 :443│
└──────────| | │ 192.168.1.30 :5432│
└──────────────┘ └─────────────────┘
```
Full rule set for this box:
```bash
# Enable forwarding
sysctl -w net.ipv4.ip_forward=1
sysctl -w net.ipv4.conf.all.rp_filter=2
# DNAT the three public ports
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.10:80
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.20:443
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 5432 -j DNAT --to-destination 192.168.1.30:5432
# Forward chain (both directions, stateful)
iptables -A FORWARD -i eth0 -o eth1 -m state --state NEW -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
# SNAT for outbound from internal
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.0/24 -j MASQUERADE
```
`rp_filter=2` is the loose mode. I learned about that one the hard way in section 7.
## 4. Failure Mode 1 — Stateful Firewall Reset on Kernel Upgrade
Last month I debugged a case where a Friday-night `apt full-upgrade` rolled my box from Ubuntu 22.04.4 to 22.04.5 and every forwarded port went dark. The NAT rules survived because I had `iptables-persistent` installed. But my FORWARD rules did not.
Turns out `iptables-persistent` on 22.04 saves to `/etc/iptables/rules.v4`, which is loaded at boot by `netfilter-persistent`. Kernel upgrades don't trigger a reboot automatically, but `unattended-upgrades` did, and something in the boot chain raced with `networkd` — the rules loaded before the interfaces were up, so the `-i eth0` matcher bound to nothing.
The fix isn't subtle:
```bash
# Reload rules AFTER interfaces are up
sudo systemctl edit netfilter-persistent.service
```
```ini
[Service]
ExecStart=
ExecStart=/sbin/iptables-restore < /etc/iptables/rules.v4
Requires=network-online.target
After=network-online.target
```
Before I did that, my forward rules silently existed in memory with zero bindings and `iptables -L` showed them as if they were fine. Packet captures told the truth.
## 5. Failure Mode 2 — conntrack Table Exhaustion
In June 2025 a marketing event spiked connections to a public TLS endpoint on my NAT box. New-connection rate hit about 4 000/s for 90 seconds. The conntrack table filled:
```bash
$ cat /proc/sys/net/netfilter/nf_conntrack_count
65536
$ cat /proc/sys/net/netfilter/nf_conntrack_max
65536
$ dmesg | tail -30
[ 4123.881] nf_conntrack: table full, dropping packet
```
Default `nf_conntrack_max` on stock Ubuntu 22.04 is 65 536. Any host doing NAT for more than a few dozen clients will hit this. My fix:
```bash
cat >> /etc/sysctl.d/90-conntrack.conf < 93.184.216.34.80: Flags [S], seq 1
10:23:41.124901 IP 203.0.113.10.51822 > 93.184.216.34.80: Flags [S], seq 1
10:23:41.125012 IP 192.168.1.20.39002 > 93.184.216.34.80: Flags [S], seq 1
10:23:41.126437 IP 203.0.113.10.51823 > 93.184.216.34.80: Flags [S], seq 1
```
Notice the 1.4 ms gap between each pair. With SNAT the gap is under 10 microseconds. The rule engine re-reads the source interface's current IP on every match because MASQUERADE is designed for DHCP-assigned egress. On a static IP there's nothing to re-resolve — I just wasn't telling the kernel that.
```bash
# Before (slow path)
iptables -t nat -D POSTROUTING -o eth0 -s 192.168.1.0/24 -j MASQUERADE
# After (fast path)
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.0/24 -j SNAT --to-source 203.0.113.10
```
Only reach for MASQUERADE when the egress IP actually changes.
## 7. Failure Mode 4 — NAT Bypass via a Second Gateway
This one bit me on a POP box that had two uplinks: a primary WAN on eth0 and a backup WAN on eth1 with a static default route. Both went to the same upstream provider. I wrote SNAT only for eth0. Traffic from the internal VLAN sometimes took eth1, skipped NAT entirely, and appeared on the internet with the source IP `192.168.1.10` — which is unreachable everywhere.
```bash
$ ip route show
default via 10.0.0.1 dev eth0 proto static
default via 172.16.0.1 dev eth1 proto static metric 20
192.168.1.0/24 dev eth1 scope link ← same interface as backup WAN, oops
```
Two problems, one box. First, two default routes means [Linux](https://www.kernel.org/doc/html/latest/) ECMPs them and half my internal traffic was never going through NAT. Second, `rp_filter=1` (the strict default) was silently dropping return packets on eth0 because they arrived from an interface that didn't match the FIB lookup for `192.168.1.10`.
Fix:
```bash
# Delete the duplicate default
ip route del default via 172.16.0.1 dev eth1
# Persist via netplan
ip netns exec ... ip route replace 172.16.0.0/24 via 172.16.0.1 dev eth1 scope link
# Relax rp_filter so DNAT return packets are accepted on either interface
sysctl -w net.ipv4.conf.all.rp_filter=2
sysctl -w net.ipv4.conf.eth0.rp_filter=2
sysctl -w net.ipv4.conf.eth1.rp_filter=2
```
If you do need two uplinks for redundancy, do it in policy routing with named tables, not with two `default` entries on the main table.
## 8. Failure Mode 5 — iptables-nft Coexistence Pitfalls
Ubuntu 22.04 ships `iptables-nft` as the default `/usr/sbin/iptables` symlink. All my muscle-memory iptables commands execute fine — they just get converted into nft rulesets under the hood. That's fine until you start mixing syntaxes.
Three things to remember:
**The `-w` lock timeout.** nft wraps a global lock. If a `[systemd](https://www.freedesktop.org/software/systemd/man/latest/)-networkd` restart is in flight when your script tries to install rules, you'll see:
```
iptables: Unable to open /run/xtables.lock. Another application holds it?
iptables: Waiting for existing lock ... 5.049 seconds passed
```
Always pass `-w 30` when scripting. It waits up to 30 seconds for the lock instead of failing fast.
**The legacy chain-name trap.** `iptables-legacy` understands `PREROUTING`, `OUTPUT`, `POSTROUTING`, `INPUT`, `FORWARD`, and `RAW` as-is. nft translates them into `nat prerouting`, `filter output`, etc. If your script writes `-A PREROUTING` without `-t nat`, iptables-nft silently puts it in the `filter` table and it does nothing. The iptables-legacy binary catches this; nft does not.
```bash
iptables -V # Confirm: iptables-nft v1.8.7 (nf_tables) or legacy?
ls -l /usr/sbin/iptables
```
**The symlink mess.** On a machine that had both packages installed the symlink could flip:
```bash
update-alternatives --display iptables
```
I switched back to `iptables-legacy` once because `iptables-nft` refused to load a ruleset that used the `raw` table with `PREROUTING` priorities that legacy accepted. Don't go there unless you have to — you're fighting the compat layer.
## 9. Migrating to nftables (Ubuntu 22.04+)
On Ubuntu 22.04 you probably don't need to migrate at all — you're already on nftables. But if you're on CentOS 7, Debian 10, or an older Ubuntu, here's the safe path:
```bash
# 1. Dump current rules
sudo iptables-save > /root/rules.v4.bak
sudo ip6tables-save > /root/rules.v6.bak
# 2. Install nftables
sudo apt update
sudo apt install -y nftables
# 3. Convert iptables ruleset to nft syntax
sudo iptables-save | sudo /usr/share/nftables/iptables-nft.sh | sudo nft -f -
sudo ip6tables-save | sudo /usr/share/nftables/iptables-nft.sh | sudo nft -f -
# 4. Verify
sudo nft list ruleset | less
sudo nft list table ip nat
sudo nft list ruleset | grep -E 'dnat|snat'
# 5. Remove the legacy shim AFTER verifying traffic
sudo apt remove -y iptables iptables-persistent
sudo apt install -y nftables
```
The `iptables-nft.sh` script is a translator, not a perfect conversion. Hand-fix things like owner matches, hashlimit, and complex `-m multiport` chains. Test each ruleset with `nft -c -f -` (check mode) before applying:
```bash
nft -c -f /tmp/ruleset.nft # syntax check only, no load
```
To watch live events during cutover:
```bash
sudo nft monitor trace
sudo nft monitor add # only rule additions
sudo nft monitor delete # only deletions
```
For my topology in section 3, the equivalent native nftables rule set is:
```bash
#!/usr/sbin/nft -f
table ip nat {
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
iifname eth0 ip daddr 203.0.113.10 tcp dport 80 dnat to 192.168.1.10:80
iifname eth0 ip daddr 203.0.113.10 tcp dport 443 dnat to 192.168.1.20:443
iifname eth0 ip daddr 203.0.113.10 tcp dport 5432 dnat to 192.168.1.30:5432
}
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
oifname eth0 ip saddr 192.168.1.0/24 snat to 203.0.113.10
}
}
table ip filter {
chain forward {
type filter hook forward priority 0; policy drop;
iifname eth0 oifname eth1 ct state new,untracked accept
iifname eth1 oifname eth0 ct state established,related accept
}
}
```
Notice `ct state` instead of `-m state` — nftables folded the state match into the `ct` meta key, and the `!` negation is a prefix, not a flag.
## 10. 15-Command Verification Checklist
Run these in order after any rule change. Stop as soon as one fails.
```bash
# 1. Kernel engine
iptables -V
ls -l /usr/sbin/iptables
# 2. Sysctls
sysctl net.ipv4.ip_forward
sysctl net.ipv4.conf.all.rp_filter
# 3. NAT rules
iptables -t nat -L -n -v --line-numbers
# 4. Filter rules
iptables -L -n -v --line-numbers
# 5. Match counts (look for zeros)
iptables -t nat -L PREROUTING -n -v
iptables -t nat -L POSTROUTING -n -v
# 6. Conntrack health
cat /proc/sys/net/netfilter/nf_conntrack_count
cat /proc/sys/net/netfilter/nf_conntrack_max
dmesg | grep -i conntrack | tail -5
# 7. Routing
ip route show table all
# 8. Listening sockets on internal host
ssh 192.168.1.10 'ss -lntp | grep :80 '
# 9. End-to-end from internet
curl -vI --resolve test.example:8080:203.0.113.10 http://test.example:8080/
# 10. Return path
tcpdump -i eth1 -n 'host 192.168.1.10 and port 80' -c 5
# 11. Forward direction
tcpdump -i eth0 -n 'host 203.0.113.10 and port 8080' -c 5
# 12. Trace
sudo nft monitor trace 2>&1 | head -40
# 13. Persistence
ls -l /etc/iptables/rules.v4
systemctl status netfilter-persistent --no-pager
# 14. Lock contention
ls -l /run/xtables.lock
# 15. Rule count sanity
iptables -S | wc -l
nft list ruleset 2>/dev/null | wc -l
```
If command 6 shows `table full` in dmesg, jump to section 5. If command 13 has an empty `rules.v4`, your rules will be gone at next reboot. If command 8 shows nothing listening, no amount of iptables is going to help.
Keep this file on the NAT box itself as `/usr/local/bin/portfwd-check.sh`. You'll wish you did the first time a ticket shows up at 3 a.m. saying "the site is down."
## Related Articles
- [Port, service and firewall allow-list lookup (iptables/firewalld/ufw/nft templates)](../tools/port-firewall-lookup/index.md)
- [CDN Internals: Edge POP, Origin Fetch, Cache Invalidation & the Cost Model](cdn-principles.md)
- [DNS Resolution End-to-End: Recursive vs Iterative, TTL, dig +trace, EDNS0](dns-resolution.md)
- [DNS Troubleshooting: Six-Symptom Decision Tree with dig +trace](dns-troubleshoot.md)
- [IPv6 Transition in Practice: Dual Stack, 6in4, NAT64, and What to Actually Run](ipv6-transition-tunneling.md) — tunneling vs NAT64, with RFC references and fact-warehouse entries
> The RFC ([RFC 1918](https://www.rfc-editor.org/rfc/rfc1918) private ranges) and port numbers (80) referenced in this article also exist as machine-readable entries in the [ops fact warehouse](https://github.com/fxlcj/ops-fact-warehouse), each with its official source URL and a check date.
- [Linux Network Kernel Tuning: A sysctl + …](linux-network-tuning.md)
---
## IPv6 Deployment and Migration: Dual-Stack Transition Without the Fire Drill
URL: https://ops.jiunotes.top/en/network/ipv6-migration.md
摘要: A working engineer's path to IPv6. Why dual-stack is the right first move, when tunneling is a stopgap and not a plan, how to get an address (SLAAC vs DHCPv6 vs static), the nginx and Apache dual-stack configs, AAAA records, and the four failures that actually bite: carrier IPv6 not routed, DNS returning A only, firewall rules that cover IPv4 only, and apps that listen on IPv4 only. Includes the shadow-IPv6 security check and the migration checklist I run before and after.
### Answer
IPv6 transition starts with dual-stack: run IPv4 and IPv6 side by side. Tunnels like 6to4 and ISATAP are stopgaps, not a plan. The three pieces people forget: AAAA records (without them clients never try IPv6), firewall rules for the IPv6 family (leaving them out is shadow IPv6), and applications listening on :: not 0.0.0.0. Diagnose with ping6, traceroute6, and dig -t AAAA. Verify with curl -6 and an iperf3 comparison.
### FAQ
Q: Is IPv6 actually more secure than IPv4?
A: In theory, IPSec is native. In practice, many organizations have no IPv6 firewall policy at all, which is worse. That gap is shadow IPv6 - an attacker can walk in over IPv6 while your IPv4 firewall looks solid. Policy must cover both families.
Q: Dual-stack or tunnel - which should I pick?
A: Dual-stack. It runs both protocols natively, is easy to troubleshoot, and has no encapsulation overhead. Tunnels (6to4, ISATAP) add overhead and complexity and are only a temporary bridge. If you can do dual-stack, do dual-stack.
Q: Are AAAA records really mandatory?
A: Yes. A client that only receives an A record will never attempt IPv6 - it will just use IPv4. If you deploy IPv6 on a server but do not publish the AAAA record, you have deployed IPv6 that nobody uses. The record is half of the migration.
Q: My server has an IPv6 address but IPv6 sites still fail. Where do I look?
A: In order: ip -6 addr show (is there a global unicast address?), ip -6 route show default (is there a default route?), ping6 to a public IPv6 (is the path up?), traceroute6 (where does it stop?). The default route is the one people forget.
Q: How do I check if an app is listening on IPv6?
A: ss -tlnp | grep :443. An IPv4-only listener shows 0.0.0.0:443; a dual-stack listener shows [::]:443. If it shows only 0.0.0.0, the app needs a :: listen or an ipv6only setting. Node and Python both accept a :: bind to cover both families.
### Full Content
# IPv6 Deployment and Migration: Dual-Stack Transition Without the Fire Drill
IPv6 was "the future" for so long that a lot of teams treated it as optional. It is not optional anymore - the address pool is effectively exhausted, carriers are pushing IPv6, and new cloud-native services default to it. This article skips the theory and covers what I actually do: pick a path, get an address, make the services listen, publish the records, open the firewall for both families, and then verify the thing actually works.
## The Three Paths, and Which One to Take
There are three ways to get from IPv4 to IPv6. They are not interchangeable, and choosing the wrong one is the first mistake.
**Path 1 - dual-stack (my default).** Run both protocols at once. The client picks whichever the DNS gives it. Smooth, compatible, easy to troubleshoot. The only cost is maintaining two sets of configuration.
```
client ──┬── IPv4 ──→ server (IPv4 address)
└── IPv6 ──→ server (IPv6 address)
```
**Path 2 - tunnel (stopgap only).** Wrap IPv6 inside IPv4 and carry it across an IPv4 network. 6to4 ([RFC 3056](https://www.rfc-editor.org/rfc/rfc3056)) and ISATAP are the classic examples. They need no IPv4 network change, but they add encapsulation overhead, are a nightmare to troubleshoot, and the 6to4 relay infrastructure is not dependable — the IETF's later assessment of transition mechanisms ([RFC 6180](https://www.rfc-editor.org/rfc/rfc6180)) recommends them only for temporary bridging. Treat tunnels as a stopgap, never as the end state.
```bash
# 6to4 - shown for understanding, not recommended as a plan
ip tunnel add sixto4 mode 6to4 remote local
ip link set sixto4 up
ip addr add 2002:::1/16 dev sixto4
```
**Path 3 - pure IPv6.** The end goal for a greenfield network, but risky as a migration target because the compatibility is unknown. I would only go pure IPv6 on a brand-new network with no IPv4 legacy to carry.
My rule, stated bluntly: **99% of situations want dual-stack.** Tunnels are for emergencies. Pure IPv6 is for new builds.
## Getting an Address: SLAAC vs DHCPv6 vs Static
Three ways to hand out an address, and the choice affects how much control you have.
- **SLAAC** (Stateless Address Autoconfiguration) - the host builds its address from the router advertisement plus its own interface identifier. Zero configuration on the host, no state on the server. Good for most end hosts.
- **DHCPv6** - stateful, gives you a lease and a record of who has what. Better for servers and for environments that need to audit address assignments.
- **Static** - manual. Right for infrastructure like routers, gateways, and DNS servers that should never change address.
```bash
# What do you actually have right now?
ip -6 addr show
# You should see fe80::/10 (link-local) and, on a dual-stack host,
# a 2001:... global unicast address.
# Does the carrier actually route IPv6 to you?
curl -6 ifconfig.me
# or
dig -6 TXT +short ip.opendns.com
```
That last check is where a lot of deployments silently fail. A carrier that advertises IPv6 on the handoff but does not route it is indistinguishable from "no IPv6" unless you test it.
## Dual-Stack on [nginx](https://nginx.org/en/docs/) and Apache
The service layer is where a clean dual-stack config lives. nginx listens on both families in one block, and there is a `ipv6only` nuance worth knowing:
```nginx
# nginx.conf - dual stack
http {
server {
listen 80;
listen [::]:80 ipv6only=on;
server_name example.com;
location / {
proxy_pass http://backend;
# Pass the real client address; works for both families
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
```
With `ipv6only=on` on the `[::]` listener, the socket serves IPv6 only, and the separate `listen 80` serves IPv4. That is the safe arrangement. If you skip the `ipv6only` flag on some platforms, the `[::]` socket may also grab IPv4-mapped connections and silently double-listen.
Apache uses the same idea with a `Listen` directive per family:
```apache
Listen 80
Listen [::]:80
```
## Publish the AAAA Record
This is the half everyone forgets. A server can have a perfect IPv6 address and still be IPv4-only in practice, because the client never learns about the IPv6 address. The AAAA record is how the client finds out. Skip it and you have deployed IPv6 nobody uses. The DNS protocol itself is defined by [RFC 1035](https://www.rfc-editor.org/rfc/rfc1035), with the naming concepts in [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034) — AAAA is simply the IPv6 counterpart of the A record, and both must exist for a dual-stack deployment.
```bash
# Add in your DNS provider:
# Type: AAAA, Host: @ or www, Value: 2001:db8::1, TTL: 300
# Verify both records exist:
dig -t AAAA example.com +short # expect 2001:db8::1
dig -t A example.com +short # expect the IPv4, still present
```
Keep the TTL short during the transition - 300 seconds lets you roll back fast if the IPv6 path turns out to be broken for some clients.
## Firewall: Do Not Forget the Second Family
The classic mistake. You open `80` and `443` in `iptables`, which is IPv4 only, and never touch the IPv6 table. The service works over IPv4 and appears fine. Then someone tests IPv6 and it times out, or worse - it is open without you realizing it.
```bash
# iptables manages IPv4 only
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# ip6tables is the IPv6 counterpart - do not skip this
ip6tables -A INPUT -p tcp --dport 80 -j ACCEPT
ip6tables -A INPUT -p tcp --dport 443 -j ACCEPT
# Or unify both families under nftables
nft add table inet dual_stack
nft add chain inet dual_stack input { type filter hook input priority 0; }
nft add rule inet dual_stack input tcp dport { 80, 443 } accept
```
The rule: **every rule you write for IPv4, write again for IPv6.** Treat them as one policy with two encodings, not as two separate systems.
## The Four Failures That Actually Bite
**Failure 1 - carrier IPv6 is not routed.** The most common. The modem or router does not have IPv6 enabled, or the carrier allocated an address but not a route. Diagnose in order:
```bash
ip -6 addr show # is there a global address?
ip -6 route show default # is there a default route?
ping6 -c 4 2001:4860:4860::8888 # reach Google's IPv6 DNS?
ping6 -c 4 ipv6.test-ipv6.com # reach an external IPv6 site?
traceroute6 -n ipv6.test-ipv6.com# where does it stop?
```
The default route is the silent killer. An interface can have a global address and no default route, and everything over IPv6 fails while IPv4 sails on.
**Failure 2 - DNS returns A only.** The client gets only an IPv4 address and never tries IPv6. Check with a query that bypasses your local resolver, to rule out local cache:
```bash
dig -t AAAA example.com @1.1.1.1 +short
dig -t AAAA example.com @8.8.8.8 +short
```
**Failure 3 - firewall covers IPv4 only.** The service is reachable over IPv4 and silently blocked or silently open over IPv6. Check the rules for both families, then test the port:
```bash
nc -6 -vz example.com 443
```
**Failure 4 - the app listens on IPv4 only.** The listener address tells you everything:
```bash
ss -tlnp | grep :443
# IPv4 only: 0.0.0.0:443
# dual-stack: [::]:443
```
If you see `0.0.0.0`, the app needs to bind `::`. Node does it with `server.listen(443, '::')`; [Python](https://docs.python.org/) with an `AF_INET6` socket, which accepts IPv4-mapped IPv6 addresses. A `::` bind covers both families on most systems.
## Security: The Shadow IPv6 Problem
The security angle is the one most teams get backwards. They assume IPv6 is more secure because of native IPSec, and they leave the firewall rules blank. The result is shadow IPv6: an attack surface that exists over IPv6 while the IPv4 policy looks solid.
```bash
# Are there ANY IPv6 firewall rules? If not, you are wide open.
ip6tables -L -n -v
# or
nft list ruleset | grep -i ipv6
# If empty, set a default policy immediately:
ip6tables -P INPUT DROP
ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
ip6tables -A INPUT -p tcp --dport 443 -j ACCEPT
ip6tables -A INPUT -p tcp --dport 80 -j ACCEPT
```
Also worth doing on the LAN side: enable RA Guard on switches so a rogue router advertisement cannot rewrite the default route, and enable privacy extensions so a host's stable address cannot be used to track it:
```bash
sysctl -w net.ipv6.conf.all.use_tempaddr=2
sysctl -w net.ipv6.conf.default.use_tempaddr=2
```
## The Migration Checklist
I run this before and after a dual-stack cutover. It is short on purpose - if any line is red, I stop. One planning note: internal segments are usually private ranges defined by [RFC 1918](https://www.rfc-editor.org/rfc/rfc1918), so plan the IPv4 and IPv6 internal addressing together - dual-stacking the edge while leaving the core IPv4-only is how you end up with a half-working deployment.
```bash
# Before
# [ ] IPv6 address allocated and routed (ip -6 route show default)
# [ ] AAAA record published (dig -t AAAA example.com +short)
# [ ] Service listens on [::] (ss -tlnp | grep :443)
# [ ] Firewall rules exist for IPv6 (ip6tables -L)
# [ ] App tested over IPv6 (curl -6 https://example.com)
# [ ] Monitoring and alerts cover IPv6
# After
# [ ] curl -6 https://example.com succeeds
# [ ] dig -t AAAA returns the address
# [ ] Main user group has working IPv6 connectivity
# [ ] Performance test shows no regression
# [ ] Security scan finds no shadow IPv6
```
## Validating Performance
IPv6 should be at parity with IPv4 - often slightly better, because there is no NAT. If it is noticeably worse, suspect MTU. The IPv6 minimum MTU is 1280 bytes, and a misconfigured device in the path can cause fragmentation issues that IPv4 never exposed.
```bash
ping6 -c 10 example.com # latency vs the IPv4 result
iperf3 -s -V # IPv6 server
iperf3 -c -V -t 10 # IPv6 client
ab -n 1000 -c 10 https://[2001:db8::1]/ # app-level test
```
## FAQ and Originality Statement
My honest position: do not chase pure IPv6. Get dual-stack running and stable first, across public-facing services, then internal services, then the network gear, and only then start trimming IPv4 dependencies. The three things that bite are almost always the same three - a missing AAAA record, a missing IPv6 firewall rule, and a service that never learned to listen on `::`. Fix those three and the migration is mostly done.
This article is my own work, written from the migrations I have done. The configs, the diagnostic order, the checklist, and the framing are original to this piece and were not translated from any other source.
## Related Articles
- [IANA special-IP and protocol-number resolver (classify any address or number)](../tools/iana-lookup/index.md)
- [TCP Troubleshooting: ss + tcpdump Decision Tree](tcp-troubleshoot.md)
- [DNS Troubleshooting: Six-Symptom Decision Tree](dns-troubleshoot.md)
- [Edge Computing Network Design](edge-computing-network.md)
- [IPv6 Transition in Practice: Dual Stack, 6in4, NAT64, and What to Actually Run](ipv6-transition-tunneling.md) — tunneling mechanisms, NAT64, and transition discipline, with RFC references and fact-warehouse entries
> The RFCs referenced in this article ([RFC 1034](https://www.rfc-editor.org/rfc/rfc1034) / [RFC 1035](https://www.rfc-editor.org/rfc/rfc1035) DNS, [RFC 1918](https://www.rfc-editor.org/rfc/rfc1918) private ranges, [RFC 3056](https://www.rfc-editor.org/rfc/rfc3056) 6to4, [RFC 6180](https://www.rfc-editor.org/rfc/rfc6180) transition guidelines) also exist as machine-readable entries in the [ops fact warehouse](https://github.com/fxlcj/ops-fact-warehouse), each with its official source URL and a check date.
---
## IPv6 Transition in Practice: Dual Stack, 6in4, NAT64, and What to Actually Run
URL: https://ops.jiunotes.top/en/network/ipv6-transition-tunneling.md
摘要: First-person guide to choosing and deploying IPv6 transition: why dual stack is always the first choice, the failure modes of 6to4/Teredo/ISATAP, a working Hurricane Electric 6in4 tunnel, NAT64+DNS64 for IPv6-only networks, carrier DS-Lite/MAP-E/MAP-T, and the MTU black-hole trap.
### Answer
IPv6 transition tunnels encapsulate IPv6 packets inside IPv4 to carry IPv6 across a network that is not natively IPv6. My rule: run dual stack whenever the ISP or cloud gives it; only when IPv6 is genuinely unavailable do I use a 6in4 user tunnel, and I avoid the deprecated 6to4 and Teredo entirely. On a true IPv6-only network, NAT64+DNS64 is the translation layer that reaches IPv4.
### FAQ
Q: Dual stack or tunnel for a new build — is there a one-line answer?
A: Dual stack if you can, tunnel only if you cannot, and of the tunnels prefer 6in4 and never touch 6to4 or Teredo. Dual stack runs IPv4 and IPv6 on the same device with no encapsulation overhead and native reachability at both ends; it is the IETF and every carrier's preferred migration path. Only when the ISP will not hand you IPv6 and you genuinely need it do I stand up a Hurricane Electric 6in4 broker tunnel. 6to4 depends on public relays, is slow and insecure, and RFC 7526 formally deprecated it; Teredo was built to traverse NAT but is disabled by default on most modern systems. Both are historical baggage to avoid in new deployments.
Q: What are NAT64 and DNS64, and how do they differ from a tunnel?
A: They are not tunnels — they are protocol translation solving the opposite problem: letting an IPv6-only network reach IPv4-only servers. NAT64 at the gateway translates IPv6 packets into IPv4; DNS64 synthesizes an IPv6 address (normally the 64:ff9b::/96 prefix) for a domain that only has an A record, so the IPv6-only host thinks the peer is also IPv6 while the traffic is actually translated to IPv4. This is the pair you see in mobile IPv6-only networks and modern data centers that want IPv4 gone internally. The cost is stateful translation, incompatibility with some apps that do not tolerate NAT (certain VoIP, FTP active mode), and it is one-directional — an IPv4-only host cannot proactively reach IPv6 resources.
Q: A 6in4 tunnel is slow and large transfers stall — what is it usually?
A: In my experience it is the MTU black hole about eight times out of ten. The IPv6 packet gains an IPv4 header, so the total frame is bigger; if the link MTU is not reduced accordingly, oversized packets are dropped and PMTUD fails because the firewall blocks ICMP. The symptom: small requests work, large files or some HTTPS resources hang. The fix: set a smaller MTU on the tunnel interface (I use 1480 or 1420) and allow ICMPv6/ICMP so PMTUD works; then use an increasing `ping -s` to locate the breakpoint. Tunnels must always have MTU tuned with them.
Q: What are DS-Lite, MAP-E and MAP-T, and do they affect an ordinary user?
A: These are carrier-side transition schemes an ordinary user does not configure but does ride on. When the carrier runs out of IPv4, it hands you only IPv6 and encapsulates your IPv4 traffic into IPv6 toward its CGNAT: DS-Lite is IPv4-in-IPv6 to the carrier, 464XLAT gives IPv4-only apps a client-side NAT64, and MAP-E/MAP-T are stateless port-restricted NAT mappings. The effect on the user: no public IPv4, inbound connections basically impossible, and some P2P and game connectivity suffers. Understanding them explains why you have no public IP and why port mapping fails, rather than chasing it blindly.
Q: If I am already full IPv6 single-stack, do I still need tunnels?
A: Probably not tunnels, but yes to a NAT64/DNS64 safety net. A real IPv6-only network means no IPv4 is allocated internally; the only path to the pure-IPv4 internet is the NAT64+DNS64 translation layer, not a tunnel. Conversely, if you are still in an IPv4 sea and want to bridge an IPv6 island (an internal segment running an IPv6 test), you need a 6in4-style tunnel. So: dual stack is the transition-era mainstream, IPv6-only is the endpoint with NAT64 as its backstop, and tunnels are a temporary bridge for IPv6 inside an IPv4 environment — the further you go, the less you use them.
### Full Content
# IPv6 Transition in Practice: Dual Stack, 6in4, NAT64, and What to Actually Run
IPv4 addresses ran out long ago, but IPv6 cannot replace the whole internet overnight. So in a transition that has lasted over a decade, islands of IPv6 float in a sea of IPv4, and the two must coexist and interconnect. The bridges are the transition technologies, in three families: dual stack, tunnels, and translation. This post does not pile up RFC numbers; it covers how I choose and configure them in a real network and which traps I actually hit. The canonical overview of the transition toolset is in [RFC 6144](https://www.rfc-editor.org/rfc/rfc6144) and the [IETF IPv6 transition mechanisms](https://datatracker.ietf.org/doc/rfc6180/).
## 1. Set the tone: dual stack is always the first choice
If the device, the OS, and the upstream link all support it, run dual stack directly — the same machine holds both an IPv4 and an IPv6 address, and the application picks its path by what it supports. It needs no encapsulation overhead and is natively reachable at both ends; it is the IETF and every mainstream carrier's preferred migration path. Tunnels and translation are compromises for "upstream gives no IPv6" or "you want to be fully IPv6-only." So before touching anything, check: does my ISP or cloud give IPv6? If yes, go dual stack and skip the tunnel.
## 2. Tunnel mechanics: stuffing an IPv6 packet into IPv4
When a segment of the path only speaks IPv4, a tunnel wraps the whole IPv6 packet inside an IPv4 packet, transports it, and unwraps at the far end. The common kinds and their weaknesses:
- **6in4 (manual tunnel)**: you configure both endpoints by hand; the most stable and reliable. Hurricane Electric's tunnelbroker.net gives these free, and they suit individuals and small networks whose ISP offers no IPv6. No public relay, so latency and stability are controllable.
- **6to4 ([RFC 3056](https://www.rfc-editor.org/rfc/rfc3056))**: auto-builds a tunnel from the IPv4 address embedded in a special prefix, with no registration. But it relies on public relays that are often unreliable and slow and can be intercepted by an arbitrary relay, so it is insecure. [RFC 7526](https://www.rfc-editor.org/rfc/rfc7526) formally deprecated it; do not use it in new builds.
- **Teredo ([RFC 4380](https://www.rfc-editor.org/rfc/rfc4380))**: built to traverse NAT by hiding IPv6 inside UDP/IPv4. Costs are high latency, it skirts security policy, and most modern OSes disable it by default. Legacy; avoid.
- **ISATAP ([RFC 5214](https://www.rfc-editor.org/rfc/rfc5214))**: used to auto-assign IPv6 to hosts inside an IPv4 site, mainly during enterprise-internal transition; no longer recommended.
The selection mnemonic I use: **use 6in4, never touch 6to4 or Teredo.**
## 3. In practice: a Hurricane Electric 6in4 tunnel
The standard move when the ISP offers no IPv6. After registering at [tunnelbroker.net](https://tunnelbroker.net/), build the tunnel interface on Linux:
```bash
ip tunnel add he-ipv6 mode sit remote 216.66.22.2 local YOUR_PUBLIC_IPV4
ip link set he-ipv6 up
ip addr add 2001:470:xxxx::2/64 dev he-ipv6
ip route add ::/0 dev he-ipv6
```
`mode sit` is the 6in4 encapsulation; `remote` is HE's tunnel server and `local` must be your public-facing IPv4 (under CGNAT this fails, because HE cannot see your real egress). Once up, test reachability with `ping6`, then route your /48 or /64 block in from the HE panel so the internal network can allocate IPv6. Two engineering points: first, **the MTU must come down** (Section 6); second, the tunnel is a single point — if the HE server goes down your IPv6 is gone, so monitor it.
## 4. NAT64 + DNS64: letting an IPv6-only network reach IPv4
This is the opposite-direction tool: when your network is already IPv6-only (common on mobile carriers and modern data centers) but the internet still holds plenty of IPv4-only servers, you need translation rather than a tunnel. NAT64 at the gateway translates IPv6 packets into IPv4; DNS64 synthesizes an IPv6 address (standard prefix `64:ff9b::/96`) for a domain that only has an A record, so the IPv6-only host believes the peer is also IPv6 while the traffic actually goes out as IPv4.
The combined flow: the host queries `example.com`, DNS64 sees only an A record, and constructs a `64:ff9b::` address to return; the host sends packets to that address and the NAT64 gateway extracts the embedded IPv4 and sends it out. The cost is that translation is stateful, some apps that do not tolerate NAT (certain VoIP, FTP active mode) break, and it is one-directional — an IPv4-only host cannot proactively reach IPv6 resources.
## 5. Carrier schemes: DS-Lite / 464XLAT / MAP-E / MAP-T
Ordinary users do not configure these but do ride on them. When the carrier's IPv4 is exhausted it hands out only IPv6 and encapsulates IPv4 traffic into IPv6 toward its CGNAT: DS-Lite is the IPv4-in-IPv6 tunnel to the carrier; 464XLAT gives IPv4-only apps a client-side NAT64; MAP-E and MAP-T are stateless port-restricted NAT mappings. The effect on the user: no public IPv4, inbound connections basically impossible, and some P2P and game connectivity suffers. Understanding them explains "why do I have no public IP at home" and "why does port mapping not work" instead of chasing it blindly.
## 6. The MTU black hole: the classic tunnel trap
The IPv6 packet gains an IPv4 header, so the encapsulated frame is bigger. If the link MTU is not reduced to match, any packet above MTU is dropped, and PMTUD (path MTU discovery) often fails because a firewall blocks ICMP. The symptom: small requests are fine; large files or certain HTTPS resources hang. The fix: set the tunnel interface MTU to 1480 or 1420 and allow ICMPv6/ICMP so PMTUD works; then use an increasing `ping6 -s` to locate the breakpoint. Any tunnel you build must have MTU tuned with it.
## 7. Discipline: how transition rots, and how I stop it
An IPv6 transition config looks like a one-time job but degrades: the HE tunnel credential expires, the ISP one day starts giving native IPv6 and dual stack conflicts with the tunnel, or the NAT64 gateway fails and the IPv6-only network suddenly cannot reach IPv4. My standing discipline:
- **Daily**: monitor tunnel endpoint-to-HE connectivity and NAT64 gateway liveness; if it drops, the IPv6 egress silently degrades.
- **Monthly**: confirm the HE account and tunnel state are not expired; check internal IPv6 address allocation (SLAAC/DHCPv6) is still healthy.
- **Before any ISP change**: if the ISP begins offering native IPv6, switch to dual stack and tear down the user tunnel so two exits do not fight over routing.
- **Red lines**: never run 6to4/Teredo in production; never build a tunnel without tuning MTU; never turn off IPv4 on an IPv6-only network without a NAT64 backstop.
## FAQ
**Q: Dual stack or tunnel — one-line answer?**
A: Dual stack if you can, tunnel only if you cannot, and of tunnels use 6in4 and avoid 6to4 and Teredo. Dual stack has no encapsulation overhead and native reachability both ways; it is the preferred path. A tunnel is the compromise when the ISP gives no IPv6 and you need it.
**Q: What are NAT64 and DNS64 for?**
A: Protocol translation for an IPv6-only network reaching IPv4 servers. NAT64 translates packets at the gateway; DNS64 synthesizes an IPv6 address from a domain's A record so the IPv6-only host thinks the peer is IPv6 while traffic exits as IPv4. Cost: stateful, some NAT-intolerant apps break, one-directional.
**Q: Tunnel is slow and large transfers stall?**
A: Usually the MTU black hole. The encapsulated frame is bigger than the link MTU and PMTUD fails because ICMP is blocked. Set the tunnel MTU to 1480/1420, allow ICMPv6, and probe with an increasing `ping -s`. Always tune MTU with the tunnel.
**Q: What are DS-Lite, MAP-E, MAP-T to me?**
A: Carrier-side schemes you ride on but do not configure. When the carrier gives only IPv6, it tunnels your IPv4 to its CGNAT. You get no public IPv4, no inbound, and some P2P/games suffer. Knowing this explains why you have no public IP.
**Q: Full IPv6 single-stack — still need tunnels?**
A: Not tunnels, but yes to NAT64/DNS64 as the backstop. An IPv6-only network reaches IPv4 only through translation. Tunnels are a bridge for IPv6 islands inside an IPv4 sea — the further the transition goes, the less you use them.
## Related articles
- [DNS resolution and troubleshooting fundamentals](dns-resolution.md)
- [dnsmasq configuration: a local DNS cache for the internal zone](dnsmasq-config.md)
- [Zero-trust network design: from perimeter to identity](zero-trust-network.md)
> The RFCs cited here (3056/7526/4380/5214, etc.) and the NAT64 prefix `64:ff9b::/96` have machine-readable entries (official source URL + check date) in the [ops fact warehouse](https://github.com/fxlcj/ops-fact-warehouse), ready to cite.
---
## Kubernetes Network Troubleshooting: A Layer-by-Layer Decision Tree and Five Real Incidents
URL: https://ops.jiunotes.top/en/network/kubernetes-network-troubleshoot.md
摘要: A first-person walkthrough of Kubernetes networking failures: a decision tree from DNS to Service endpoints, kube-proxy, CNI, NetworkPolicy and cloud firewalls, five incidents and copy-paste checks.
### Answer
Walk DNS to Service to kube-proxy; empty endpoints is the top culprit.
### FAQ
Q: What is the single most common cause of Kubernetes service failures I should check first?
A: An empty Endpoints object. Before touching CNI or firewall rules, run kubectl get endpoints . If the address list is empty, the pod selector is wrong, the pod is not Ready, or the port name does not match the targetPort.
Q: When should I suspect the CNI plugin instead of kube-proxy?
A: When same-node pod-to-pod traffic works but cross-node traffic hangs. kube-proxy handles service load balancing on every node, while cross-node reachability is the CNI's overlay tunnel. Check the tunnel port, for example UDP 8472 for flannel VXLAN or BGP 179 for calico.
Q: How do I tell a NetworkPolicy from a firewall drop?
A: Run kubectl describe networkpolicy and check the podSelector and the allowed ingress rules. NetworkPolicy is namespace-scoped and applied by the CNI, so packet counters in iptables may not move. A cloud security group drop, by contrast, shows up as connection timeouts and is visible on the node's conntrack with no reply packets.
Q: Can an Ingress object exist while the controller is not running?
A: Yes. The Ingress resource is just declarative state. If no controller is watching it, the resource sits there with no LoadBalancer address and no endpoint. Check kubectl get deploy -n ingress-nginx and kubectl get svc -n ingress-nginx before blaming the Service.
Q: What is the fastest way to capture packets from inside a pod?
A: Run kubectl debug with a network image such as nicolaka/netshoot, then use tcpdump inside that ephemeral container. This captures traffic on the pod's veth interface and tells you whether packets leave the pod and whether replies ever return.
### Full Content
# Kubernetes Network Troubleshooting: A Layer-by-Layer Decision Tree and Five Real Incidents
## It Started With a 3 A.M. Page
The page said `payment-service` was failing health checks. I had the usual suspects in my head: database down, OOM-killed pod, bad deploy. Then `kubectl get pods` showed every replica Ready, zero restarts, healthy logs. The pod was alive and the process was fine. The problem was the road between the pod and the thing it needed to talk to. That is the moment [Kubernetes](https://kubernetes.io/docs/) networking stops being theory and becomes a 3 a.m. debugging session.
I have worked enough of these to know the failure is rarely in one magical place. It is usually a chain: DNS, then Service, then the proxy rules, then the overlay, then policy, then the cloud firewall. This article walks the chain the way I actually do it, one layer at a time, with the five incidents that burned me the hardest.
## The Decision Tree: Six Layers, One Direction
When a pod cannot reach a backend, I never guess. I start at the top and peel down. Each layer has one cheap command that tells me whether to keep going or stop and fix.
| Layer | What it answers | One command |
|-------|-----------------|-------------|
| DNS | Does the name resolve to the right IP? | `nslookup` inside the pod |
| Service/Endpoints | Are there healthy backends behind the ClusterIP? | `kubectl get endpoints` |
| kube-proxy | Are the NAT rules programmed on the node? | `iptables -t nat -L` |
| CNI | Does the overlay tunnel carry cross-node traffic? | `ip route`, `ss -lunp` |
| NetworkPolicy | Is policy silently dropping packets? | `kubectl describe networkpolicy` |
| Node/cloud firewall | Is the host or security group blocking the port? | `firewall-cmd`, cloud console |
The order matters: DNS is the cheapest to test, the cloud firewall is the most expensive to touch. Every incident below follows this exact order, and each could have been found in under five minutes if I had trusted the tree instead of my instincts.
## Layer 1 — DNS: The Name That Resolves to the Wrong Place
**Incident #1: CoreDNS resolving a stale IP.** A worker pod kept trying to reach `redis.internal.svc.cluster.local` and getting connection refused. DNS resolved fine — to an IP that was no longer the [Redis](https://redis.io/docs/) service.
```bash
kubectl run dns-test --rm -it --image=busybox -- nslookup redis.internal.default.svc.cluster.local
```
```text
Name: redis.internal.default.svc.cluster.local
Address: 10.96.12.34
```
The address was plausible, so I wasted twenty minutes on the Service. The real bug was upstream: a hand-edited `/etc/hosts` entry in a CoreDNS ConfigMap had pinned that name to an old ClusterIP. The fix was deleting the stale `hosts` block, not touching any network path.
```bash
kubectl get configmap -n kube-system coredns -o yaml
kubectl get configmap -n kube-system coredns -o yaml | grep -A3 hosts
```
The signal is a name that resolves to an IP nothing listens on. The command runs inside the pod's own network namespace, so it tests exactly the path the application uses.
## Layer 2 — Service and Endpoints: The Selector Mismatch
**Incident #2: an empty Endpoints object.** This is my number one cause of "service is down" pages. The Service exists, the pods look fine, but the traffic goes nowhere.
```bash
kubectl get svc backend
kubectl get endpoints backend
```
```text
NAME TYPE CLUSTER-IP PORT(S) AGE
backend ClusterIP 10.96.7.88 8080/TCP 21d
NAME ENDPOINTS AGE
backend 21d
```
`` is the smoking gun. The Service and the pods have a mismatch. I compare the selector with the pod labels:
```bash
kubectl get svc backend -o jsonpath='{.spec.selector}'
kubectl get pods -l app=backend
```
The selector was `app: backend-api`, but every pod carried `app: backend`. One typo, no endpoints, total outage. Fixing the selector brought the endpoints back instantly. This layer is also where a pod that is Ready but on the wrong port shows up — check `targetPort` if the endpoint count looks right but connections still fail.
## Layer 3 — kube-proxy: The Rules in the Middle
When endpoints exist but traffic still fails from another node, I look at whether the load-balancing rules exist on the node. kube-proxy programs iptables (or IPVS) on every node to redirect ClusterIP traffic to the pod IPs.
```bash
kubectl logs -n kube-system daemonset/kube-proxy --tail=20
iptables -t nat -L KUBE-SERVICES -n | grep backend
```
```text
KUBE-SERVICES dpt:8080 -> 10.96.7.88:8080
```
If the rule is missing, kube-proxy is not syncing. Check its logs and confirm the kube-proxy pods are not stuck in CrashLoopBackOff. A less obvious variant: the rule exists under IPVS but the real-servers list is empty. The layer is healthy when the rule maps ClusterIP to the right backend list.
## Layer 4 — CNI: Flannel, Calico, Cilium
Same-node traffic working while cross-node traffic hangs is the CNI signature. The overlay tunnel is the culprit. This is where the plugin choice determines what you check.
| CNI | Data plane | Check |
|-----|-----------|-------|
| flannel | VXLAN over UDP 8472 | `ss -lunp \| grep 8472` |
| calico | BGP over TCP 179 or IPIP proto 4 | `calicoctl node status`, `ip route` |
| cilium | eBPF datapath | `cilium status`, `hubble status` |
**Incident #3: VXLAN port 8472 blocked.** Cross-node traffic was black-holing on a flannel cluster. The tunnel was up, both nodes had a `flannel.1` interface, but packets never crossed.
```bash
ip -d addr show flannel.1
ss -lunp | grep 8472
```
```text
udp UNCONN 0 0 *:8472
```
The port was listening, so I checked the host firewall and found UDP 8472 denied in the security group on the target node. VXLAN needs 8472 open between every node pair. The fix was opening the port in the security group, not touching Kubernetes at all.
For calico, the same failure mode appears when BGP neighbor sessions are down:
```bash
calicoctl node status
```
For cilium, the eBPF datapath makes drops visible. `cilium status` shows datapath health, and `hubble observe --verdict DROPPED` frequently names the policy that did it before I ever open a YAML file.
## Layer 5 — NetworkPolicy: The Silent Packet Killer
**Incident #4: default-deny blocking DNS.** A freshly deployed namespace came up and every pod could not resolve anything. DNS itself was fine from the host. Inside the namespace, everything timed out.
```bash
kubectl get networkpolicy -n checkout
kubectl describe networkpolicy deny-all -n checkout
```
The policy had a `podSelector: {}` matching everything and an empty `ingress` list. That is the default-deny pattern, and it silently killed UDP 53 toward CoreDNS. The application never saw an error; packets just vanished. The tell is that DNS works from the host but not from the pod, and the policy description shows no allowed ingress.
The fix is an explicit allow rule to the DNS service. NetworkPolicy is the layer to suspect whenever a service starts failing right after a new namespace is created or a policy is applied.
## Layer 6 — Node and Cloud Firewalls
The final layer is the one everyone resists checking because it is outside the cluster. On bare metal, the node firewall:
```bash
firewall-cmd --list-all
ufw status verbose
```
On a cloud, the security group is the same thing with a different console. I lost a morning to a security group that allowed 443 inbound but not the node-to-node pod CIDR. The symptom: everything inside the cluster is healthy, but external traffic to a `NodePort` or `LoadBalancer` times out.
## Pod-Level Capture: netshoot and tcpdump
When every layer looks clean but the connection still fails, I stop theorizing and capture the packets. Modern Kubernetes lets me do this without a debug pod image of my own.
```bash
kubectl debug -it --image=nicolaka/netshoot --target=
```
Inside the ephemeral container I run tcpdump on the pod's veth. The question is always the same: do packets leave, and do replies come back?
```bash
tcpdump -i eth0 -nn -c 50 'tcp port 8080 or udp port 53'
```
If I see SYN packets leaving but no SYN-ACK, the backend is unreachable — that points to the overlay or a firewall. If I see nothing, the application is not even sending, which is a code problem. This capture has saved me from two days of blaming the wrong layer.
## Incident #5 — The Ingress Object With No Controller
One last story that does not fit neatly into the tree. A user swore the Ingress was broken. The object existed and the hostname looked right, but no address was assigned.
```bash
kubectl get ingress web
kubectl get deploy -n ingress-[nginx](https://nginx.org/en/docs/)
kubectl get svc -n ingress-nginx
```
```text
NAME CLASS HOSTS ADDRESS
web nginx app.example.com
```
The `` address was the clue. The Ingress controller namespace had no Deployment running at all — someone had scaled it to zero and forgotten. The Ingress resource is just declarative state; without a controller watching it, it does nothing. Once I scaled the controller back up, the address was assigned within seconds.
## FAQ
**What is the single most common cause of Kubernetes service failures I should check first?**
An empty Endpoints object. Run `kubectl get endpoints ` first. If the list is empty, the pod selector is wrong, the pod is not Ready, or the port name does not match `targetPort`.
**When should I suspect the CNI plugin instead of kube-proxy?**
When same-node pod-to-pod traffic works but cross-node hangs. Cross-node reachability is the CNI overlay tunnel. Check the tunnel port: UDP 8472 for flannel VXLAN, BGP 179 for calico.
**How do I tell a NetworkPolicy from a firewall drop?**
Run `kubectl describe networkpolicy` and inspect the `podSelector` and allowed ingress rules. NetworkPolicy is namespace-scoped and enforced by the CNI. A security group drop shows as timeouts with no reply packets in tcpdump.
**Can an Ingress object exist while the controller is not running?**
Yes. The Ingress resource is just declarative state. If no controller watches it, it gets no address and no endpoints. Check `kubectl get deploy -n ingress-nginx` before blaming the Service.
**What is the fastest way to capture packets from inside a pod?**
Run `kubectl debug` with `nicolaka/netshoot`, then `tcpdump` inside that container. This captures traffic on the pod's veth and tells you whether packets leave and replies return.
## Related Articles
- [SSL/TLS Handshake Troubleshooting](ssl-tls-handshake-troubleshoot.md)
- [TCP Troubleshooting: A Field Guide](tcp-troubleshoot.md)
- [Nginx 504 Troubleshooting](nginx-504-troubleshoot.md)
- [Multi-Cloud Networking: Choosing the Right On-Ramp and Designing the Backbone](multicloud-network.md)
---
## Linux Network Kernel Tuning: A sysctl + TCP Congestion Control Playbook
URL: https://ops.jiunotes.top/en/network/linux-network-tuning.md
摘要: A production playbook for Linux network kernel tuning: tiered tcp_* matrix with rollbacks, BBR vs CUBIC vs Reno comparison, measured iperf3/ss -tin BBR data, and five incidents with revert steps.
### Answer
Tiered sysctl matrix with BBR data; five incidents show rollback wins.
### FAQ
Q: Is it safe to enable BBR on any server?
A: Only on clean, low-loss paths. BBR inflates queues on lossy or shallow-buffer links. Measure first, keep a rollback.
Q: How do I make a sysctl change survive a reboot?
A: Put it in /etc/sysctl.d/99-network.conf and run sysctl --system. Plain sysctl -w is lost on reboot.
Q: Why did my throughput drop after raising tcp_rmem?
A: Raising tcp_rmem too far makes the kernel over-allocate and can OOM. Revert to defaults and raise it modestly.
Q: What is the first command I run when a box is slow?
A: ss -tin for retransmits and cwnd, plus netstat -s for drops. Those two point at congestion control or a backlog drop.
Q: Does tcp_syncookies protect against SYN floods?
A: Yes, but only when the SYN queue fills. Forcing 1 always can misbehave under load; 2 is the modern default.
### Full Content
# Linux Network Kernel Tuning: A sysctl + TCP Congestion Control Playbook
The internet is full of "enable BBR in one command" posts. They are not wrong, but they are not tuning either. I have watched a single `sysctl -w net.ipv4.tcp_congestion_control=bbr` turn a perfectly healthy box into a paging incident, and I have watched the same one-liner double a CDN egress. The difference is never the algorithm — it is whether I measured before and whether I could roll back after. This article is my playbook: what I actually set on production boxes, what I refuse to touch without a revert, and the five incidents that taught me the difference.
## 1. The Quick-Reference Toolkit
I keep four habits, all of which are one command.
```bash
# 1. See what is set, filtered. This is the whole surface I tune.
sysctl -a | grep -E 'net\.(ipv4|core)\.(tcp_|rmem|wmem|somaxconn|netdev_max_backlog|optmem_max)'
# 2. Change it for now only — dies on reboot.
sysctl -w net.ipv4.tcp_congestion_control=bbr
# 3. Persist it. One file per box, sourced by [systemd](https://www.freedesktop.org/software/systemd/man/latest/) at boot.
cat /etc/sysctl.d/99-network.conf
sysctl --system # reload every file in /etc/sysctl.d/ — no reboot
# 4. Write a rollback line BEFORE you change anything.
sysctl -w net.ipv4.tcp_rmem='4096 131072 6291456' # snapshot the default
```
Habit four is the one I am most religious about. Every incident in this article was avoidable by a single saved value. I keep a `/root/network-baseline.conf` with the stock values of everything I touch, so "rollback" is always `cp` + `sysctl --system`.
## 2. The Production Parameter Matrix
I do not tune fifty knobs. I tune the ones with real leverage, and I sort them by how much I trust them.
### Must-set — safe, high-leverage
| Parameter | Value | Purpose | Rollback |
|---|---|---|---|
| `net.core.somaxconn` | `4096` | raise listen backlog above [nginx](https://nginx.org/en/docs/)'s 128 default | `128` |
| `net.ipv4.tcp_max_syn_backlog` | `4096` | SYN queue headroom | `1024` |
| `net.ipv4.tcp_fin_timeout` | `30` | fast-close TIME_WAIT for short-lived HTTP | `60` |
| `net.ipv4.tcp_tw_reuse` | `1` | reuse TIME_WAIT sockets as a client | `0` |
| `net.ipv4.tcp_slow_start_after_idle` | `0` | no ssthresh reset after idle — huge for spiky APIs | `1` |
| `net.ipv4.tcp_congestion_control` | `bbr` | the algorithm itself (see §3) | `cubic` |
| `net.core.default_qdisc` | `fq` | fair-queueing pacing, required for BBR | `pfifo_fast` |
### Advanced — measure, then decide
| Parameter | Value | Purpose | Rollback |
|---|---|---|---|
| `net.core.rmem_max` | `16777216` | allow sockets to grow receive buffer | `212992` |
| `net.core.wmem_max` | `16777216` | allow sockets to grow send buffer | `212992` |
| `net.ipv4.tcp_rmem` | `4096 262144 16777216` | per-socket RX min/default/max | `4096 131072 6291456` |
| `net.ipv4.tcp_wmem` | `4096 65536 16777216` | per-socket TX min/default/max | `4096 16384 4194304` |
| `net.ipv4.tcp_notsent_lowat` | `16384` | cap unsent bytes; lowers BBR latency at the cost of bulk throughput | `-1` |
| `net.ipv4.tcp_mtu_probing` | `1` | black-hole detection on links with odd MTUs | `0` |
### Dangerous — do not touch without a revert and a window
| Parameter | Why it bites |
|---|---|
| `net.core.netdev_max_backlog` | Raising it hides a NIC ring that is already full; the drops just move. I raise it only when `netstat -s` shows `backlog drops` **and** `softnet_stat` shows drops. |
| `net.ipv4.tcp_rmem` max | Too large and the kernel over-allocates per socket; N connections × max bytes can OOM. Incident §5. |
| `net.ipv4.tcp_syncookies` | `1` forces cookies always and the syncache misbehaves under normal load. `2` is the modern conditional default. Incident §6. |
| `net.ipv4.tcp_low_latency` | Busy-polling burns a CPU per socket. Only for a handful of high-frequency sockets. |
| `net.ipv4.tcp_sack` / `tcp_fack` | Turning these off for "latency" usually just costs retransmit efficiency. |
A concrete file I ship on most web boxes:
```ini
# /etc/sysctl.d/99-network.conf
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_congestion_control = bbr
net.core.default_qdisc = fq
```
## 3. BBR vs CUBIC vs Reno: A Decision Table
| | Reno | CUBIC | BBR |
|---|---|---|---|
| **Model** | AIMD, window-based | AIMD, cubic growth | rate-based, BDP-derived |
| **Uses loss as signal** | yes, aggressively | yes, gently | no — models bandwidth & RTT |
| **Best for** | [RFC](https://www.rfc-editor.org/)-compliant, lossy paths, tiny RTTs | default, general internet, bulk transfer | clean low-loss links, high-BDP, mobile |
| **Throughput** | lowest | good | highest on clean paths |
| **Latency under load** | high (inflates queues) | high | low — but only with `fq` |
| **Shallow buffer** | recovers | recovers | **can underperform** — queues inflate, loss wins |
| **When NOT to use** | nearly always obsolete | when BBR measured better | lossy/satellite/shallow-buffer links |
| **Kernel ≥** | forever | 2.6.19 | 4.9 (5.6 stable-ish) |
The `fq` qdisc is not optional. BBR paces packets and needs a queueing discipline that honors pacing; `pfifo_fast` ignores it and BBR silently degrades to bursty CUBIC-like behaviour. That is the #1 "BBR made it worse" cause I meet.
```bash
# confirm the pair is active together
sysctl net.ipv4.tcp_congestion_control net.core.default_qdisc
# -> tcp_congestion_control = bbr
# -> default_qdisc = fq
```
## 4. Measured Data: One Box, Before and After
An egress CDN cache node, 16 vCPU, 10 Gbps NIC, serving TLS objects. I enabled `fq` + BBR, and measured the same 4 GB file transfer over the same WAN path with iperf3.
**Before (CUBIC):**
```bash
iperf3 -c 10.0.1.20 -t 30 -P 4
# [SUM] 0.00-30.00 sec 2.61 GBytes 748 Mbits/s sender
# [SUM] 0.00-30.00 sec 2.60 GBytes 746 Mbits/s receiver
ss -tin | grep -E 'rto|cwnd|rtt'
# rtt:3.2/4.1/5.1 rto:204 rttvar:2.9 cwnd:126
```
**After (BBR + fq):**
```bash
sysctl -w net.ipv4.tcp_congestion_control=bbr
sysctl -w net.core.default_qdisc=fq
iperf3 -c 10.0.1.20 -t 30 -P 4
# [SUM] 0.00-30.00 sec 4.92 GBytes 1.41 Gbits/s sender
# [SUM] 0.00-30.00 sec 4.90 GBytes 1.40 Gbits/s receiver
ss -tin | grep -E 'rto|cwnd|rtt'
# rtt:2.8/3.6/4.9 rto:204 rttvar:2.6 cwnd:412
```
Throughput 1.9×, cwnd 3.3×, p95 RTT actually **down** 0.5 ms. The win came not from the algorithm but from BBR's model holding a much larger in-flight window on a path that never loss-signals — RTT stayed flat while cwnd tripled. That is the only kind of result I keep.
Retransmits stayed flat, which is how I know I am on a clean path:
```bash
netstat -s | grep -E 'retrans|reorder'
# 1232 segments retransmited (before)
# 1198 segments retransmited (after)
```
## 5. Incident: tcp_rmem Set Too Large → OOM
A colleague tuned a 64 GB box for "high throughput" and set `tcp_rmem` max to 256 MB. With 2,000 concurrent connections, the kernel did not allocate 256 MB each — but with `rmem_max` that high, receive buffers ballooned per connection, and the sum of in-flight data plus the page cache hit cgroup memory limits. OOM-killer ate the web worker.
**Symptom:** `dmesg` shows `Out of memory: Killed process ... web_worker`, and `cat /proc/meminfo | grep CommitLimit` is nearly reached.
```bash
# what it looked like
sysctl net.ipv4.tcp_rmem
# -> net.ipv4.tcp_rmem = 4096 262144 268435456
grep -E 'CommitLimit|Committed_AS' /proc/meminfo
```
**Rollback:**
```bash
sysctl -w net.ipv4.tcp_rmem='4096 262144 16777216'
sysctl -w net.core.rmem_max=16777216
echo 'net.ipv4.tcp_rmem = 4096 262144 16777216' >> /etc/sysctl.d/99-network.conf
echo 'net.core.rmem_max = 16777216' >> /etc/sysctl.d/99-network.conf
sysctl --system
```
The lesson: the **max** is a ceiling, not a target. The kernel grows buffers toward the default first; only pressure pushes them to max. Raise the default, not the ceiling, unless the path is genuinely high-BDP and you can cap connection count.
## 6. Incident: tcp_syncookies Set to 1 → Misjudged Flood
A monitoring alert fired on SYN backlog. Someone "fixed" it with `sysctl -w net.ipv4.tcp_syncookies=1`, which forces cookies **always**. Under ordinary load, the syncache then generates cookies for connections that would have used the normal path, the handshake becomes stateless, and I lost visibility into the real backlog — worse, a moderate burst that the queue would have absorbed started failing handshakes.
**Symptom:** `netstat -s | grep -i syn` shows no SYN drop counters, yet `ss -s` shows a full SYN queue and clients time out.
```bash
netstat -s | grep -iE 'SYN|Listen'
# 0 SYNs to LISTEN sockets dropped <- suspiciously clean
# 0 times the listen queue of a socket overflowed
ss -lnt | head -3
```
**Rollback:**
```bash
sysctl -w net.ipv4.tcp_syncookies=2 # conditional: cookies only when the queue fills
echo 'net.ipv4.tcp_syncookies = 2' >> /etc/sysctl.d/99-network.conf
sysctl --system
```
Value `2` is the modern default on most distros: cookies kick in only when the SYN queue overflows, which is exactly when you want them. `1` removes the queue logic entirely and hides the problem.
## 7. Incident: BBR Underperforming on a Shallow-Buffer Link
I enabled BBR on a box behind a low-latency, shallow-buffer metro link. Throughput dropped ~30% and latency spiked. The classic explanation: BBR models bandwidth and RTT, and on a path with a small buffer, it sends at a rate that the bottleneck cannot buffer, so packets are dropped and the model over-corrects. CUBIC, which reacts to loss more conservatively, held a steadier rate.
**Symptom:** BBR enabled, `iperf3` worse than CUBIC, and `ss -tin` shows `cwnd` oscillating wildly.
```bash
ss -tin | grep -E 'cwnd|rtt'
# cwnd:96 rtt:1.2/1.4/1.9 <- tiny, bouncing
```
**Rollback:**
```bash
sysctl -w net.ipv4.tcp_congestion_control=cubic
sysctl -w net.core.default_qdisc=fq_codel
echo 'net.ipv4.tcp_congestion_control = cubic' >> /etc/sysctl.d/99-network.conf
sysctl --system
```
Decision rule I now use before enabling BBR: if `ss -ti | grep rtt` shows a p95 RTT under ~2 ms **and** the link is a carrier ethernet handoff, I test CUBIC side-by-side for a full day. On shallow-buffer links, `fq_codel` + CUBIC often beats BBR.
## 8. Incident: netdev_max_backlog Raised to Hide a Drop
Same story as syncookies: a backlog alert, a knee-jerk raise. I bumped `net.core.netdev_max_backlog` to 262144 and the drop counter went quiet for a day — then returned. The raise did nothing because the real bottleneck was the NIC ring and the application's single-threaded polling, not the queue length.
**Symptom:** drops persist after the raise, and `softnet_stat` is the honest counter.
```bash
# the honest counters
cat /proc/net/softnet_stat | awk '{print $1, $2, $3}' | head
# dropped time_squeeze cpu_collision
netstat -s | grep -i drop
```
**Rollback:**
```bash
sysctl -w net.core.netdev_max_backlog=1000
echo 'net.core.netdev_max_backlog = 1000' >> /etc/sysctl.d/99-network.conf
sysctl --system
```
The real fix was application-side: `RPS`/`XPS` spread across the 16 cores, and `netdev_budget` was left alone. I now read `/proc/net/softnet_stat` before and after **any** backlog change; if `dropped` does not fall, the change is cosmetic and I revert.
## 9. Incident: rwnd Clamping Capping Throughput
A large file transfer on a 300 ms RTT path capped at ~90 Mbps no matter what I did. `ss -tin` told me: `cwnd` was fine, but the window was clamped by the receiver's `rwnd`, which never grew past a fixed value. The receiver's `tcp_rmem` max was still the stock 6 MB, so even though the sender could send, the receiver advertised a tiny window and the transfer was window-limited.
```bash
# on the receiver — the clamp
sysctl net.ipv4.tcp_rmem
# -> net.ipv4.tcp_rmem = 4096 131072 6291456
ss -tin | grep -E 'cwnd|rtt|bytes_acked'
# cwnd:64 rwnd:4096 <- rwnd stuck at one MSS-ish
```
**Fix (receiver side):**
```bash
sysctl -w net.ipv4.tcp_rmem='4096 131072 16777216'
sysctl -w net.core.rmem_max=16777216
echo 'net.ipv4.tcp_rmem = 4096 131072 16777216' >> /etc/sysctl.d/99-network.conf
sysctl --system
```
Throughput recovered to ~380 Mbps. The rule: on high-BDP paths, the **receiver** must be willing to advertise a big window, not just the sender to send. The product of `rwnd` and 8 divided by RTT is the ceiling; 16 MB / 0.3 s ≈ 425 Mbps was the new cap, and I nearly hit it.
## 10. FAQ
**Q: Is it safe to enable BBR on any server?**
A: Only on clean, low-loss paths. BBR inflates queues on lossy or shallow-buffer links. Measure first, keep a rollback.
**Q: How do I make a sysctl change survive a reboot?**
A: Put it in `/etc/sysctl.d/99-network.conf` and run `sysctl --system`. Plain `sysctl -w` is lost on reboot.
**Q: Why did my throughput drop after raising tcp_rmem?**
A: Raising `tcp_rmem` too far makes the kernel over-allocate and can OOM. Revert to defaults and raise it modestly.
**Q: What is the first command I run when a box is slow?**
A: `ss -tin` for retransmits and cwnd, plus `netstat -s` for drops. Those two point at congestion control or a backlog drop.
**Q: Does tcp_syncookies protect against SYN floods?**
A: Yes, but only when the SYN queue fills. Forcing `1` always can misbehave under load; `2` is the modern default.
**Q: When should I NOT use BBR even though the link is clean?**
A: When the application is latency-sensitive and the box is behind a single shallow buffer, or when you cannot install `fq`. Without `fq`, BBR degrades to bursty behaviour and can lose to CUBIC.
## Related Articles
- [TCP Troubleshooting: TIME_WAIT / RST / SYN Half-Open / Retransmission](tcp-troubleshoot.md)
- [iptables Port Forwarding in Production — SNAT/DNAT Chain Architecture, Failure Modes, and nftables Migration](iptables-port-forwarding.md)
- [TCP/IP Internals: Layered Model, Handshake, Teardown, RTO, CUBIC vs BBR](tcp-ip.md)
---
## Micro-segmentation: Cutting the Flat Network Before the Attacker Does
URL: https://ops.jiunotes.top/en/network/micro-segmentation.md
摘要: A working engineer's micro-segmentation playbook: why lateral movement wins in flat networks, the three design principles (business domain, default-deny, minimal policy), a copy-paste Kubernetes NetworkPolicy set, NSX-T and physical ACL variants, and two real breach case studies I worked.
### Answer
Micro-segmentation is default-deny at the workload level. Instead of one big flat network, you split it into small business domains, each with its own policy, and every cross-domain hop needs explicit authorization. The key to stopping lateral movement is a simple chain: database only accepts backend, backend only accepts frontend, frontend only accepts the load balancer. Kubernetes uses NetworkPolicy, virtualized stacks use NSX-T, physical networks use ACLs.
### FAQ
Q: What is the difference between micro-segmentation and a VLAN?
A: A VLAN is layer-2 isolation; micro-segmentation is policy isolation. A VLAN groups machines by geography or department and relies on layer-3 routing between segments. Micro-segmentation groups by application, label, or identity, and the enforcement point is a policy engine. In short: VLAN is physical separation, micro-segmentation is logical separation.
Q: Does micro-segmentation hurt performance?
A: There is a small cost because every packet goes through policy evaluation, but modern implementations (eBPF, hardware offload) make it nearly imperceptible. The real risk is policy sprawl — ten thousand rules is worse than one hundred well-designed ones. Stay lean: default-deny, then open only what you can justify.
Q: How does micro-segmentation relate to zero trust?
A: Zero trust is the philosophy (never trust, always verify); micro-segmentation is the implementation mechanism. You cannot truly land zero trust without segmenting workloads into business domains with least-privilege access. Micro-segmentation is what makes 'verify every request' concrete at the network layer.
Q: What is the single most common failure when rolling out micro-segmentation?
A: Accidentally cutting a legitimate dependency. You write default-deny, and the first thing that breaks is a cross-team API call you did not document. The fix is not to widen the policy — it is to discover the dependency first. I run a two-week discovery window with full-flow logging before I flip any default-deny.
Q: Do I need micro-segmentation if I already have a firewall between zones?
A: A traditional firewall only sees east-west traffic at the zone boundary. Once an attacker lands on one host inside a zone, everything else in that zone is reachable. Micro-segmentation pushes the enforcement point to the workload, so a compromised pod or VM cannot hop to its neighbor. Zone firewalls and micro-segmentation are complementary, not either-or.
### Full Content
# Micro-segmentation: Cutting the Flat Network Before the Attacker Does
The first time I watched a breach replay in a post-incident review, I was embarrassed for the network team. An attacker landed on one frontend box, scanned the internal network, and reached a database server in under four minutes. Not because the firewall was weak — because there was nothing between the frontend and the database. It was one giant flat L3 domain, and every host could talk to every host. That is the problem micro-segmentation solves, and this article is the playbook I wish I had that day.
## Why Lateral Movement Is the Whole Game
Perimeter security works until it does not. Once an attacker breaches the edge, the internal network is a buffet unless you segmented it. The standard kill chain looks like this:
```
attacker compromises frontend web server
↓
scans internal network for reachable services
↓
finds database server
↓
pivots to database, exfiltrates data
```
I have seen this exact path four times. Three of the four succeeded because the internal network was flat. The single worst case was an e-commerce shop in 2023: the attacker came in through a compromised marketing-system server, which sat in the same flat segment as the database tier, and pulled five million user records. They were inside for three months. No one noticed because nothing on the network was watching east-west traffic.
## The Three Design Principles That Matter
Micro-segmentation fails for two reasons: bad policy design and operational friction. These three principles prevent both.
### Principle 1: Segment by business domain, not by department
The instinct is to carve the network by org chart. That is wrong. A finance department and a research department have wildly different network access needs, but an order system and a payment system have a stable, predictable relationship.
```
WRONG: finance-net, research-net, ops-net
RIGHT: order-system, user-system, payment-system, log-system
```
A business domain has a consistent set of peers. The order system only talks to the user system and the payment system. That consistency is what makes policies writable and reviewable. Departmental segments are a moving target because headcount changes constantly and nobody agrees on what "finance needs" means.
### Principle 2: Default-deny, allow as needed
Every segment starts closed. You write the explicit allows on top. The trap is the reverse: write a permissive baseline and then try to tighten it later. Tightening is where you break production, so it never happens.
```yaml
# WRONG: permissive baseline
allow all from any
# RIGHT: closed baseline
default_deny all
allow from frontend to backend on port 8443
allow from backend to database on port 5432
```
### Principle 3: Keep policies minimal and specific
A rule that matches too broadly is a rule that does not protect anything.
```yaml
# WRONG: too loose
allow from any to database
# RIGHT: exact match
allow from pod(label=backend) to pod(label=database) on port 5432
```
## The Rollout Cadence: Observe, Reconcile, Enforce
The hard part is not writing the policy. It is how you flip it on. The moment you go straight to enforce, the first missing dependency cuts a real business flow. In production I always run a three-phase cadence.
Phase one: log-only mode. Set the policy engine to record but not block, and let it run for one to two weeks. During that window the engine logs every real cross-domain flow and you export a "real-traffic allow list." That list is more honest than any architecture document — it records every flow that actually ran in production, including the cross-team calls nobody remembers or ever wrote down.
Phase two: reconcile. Diff that list against the policies you wrote. Two things to hunt for: flows the policy allows but the list never shows (usually a made-up requirement copied from a diagram — delete them, they only widen your attack surface), and flows the list shows but the policy does not allow (gaps that will break the moment you enforce). Patch the second kind in, and delete the first kind.
Phase three: switch to enforce and keep a seven-to-ten-day rollback window. Rollback is not "delete the policies and reconfigure." It is a single switch that flips the engine from enforce back to log-only. Before you announce the change to the business, test the rollback itself: in a low-traffic window, really flip it back and forth once and confirm it takes effect in seconds. Too many teams skip this, and the day they need to roll back they find the rollback script was never tested.
This cadence costs you a week or two. In return, launch day does not break production on a missing rule. In every project I have run it through, the log-only pass surfaced three to five cross-domain dependencies per system that were never in the architecture doc.
## [Kubernetes](https://kubernetes.io/docs/) NetworkPolicy: The Copy-Paste Set
Kubernetes gives you micro-segmentation out of the box. Here is the complete five-policy set I deploy to every production namespace. The chain is the point: load balancer → frontend → backend → database, with nothing else permitted in.
```yaml
# 1. Default-deny all ingress for the whole namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
---
# 2. Allow the monitoring namespace to scrape everything on 9090
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-monitoring
namespace: production
spec:
podSelector: {}
ingress:
- from:
- namespaceSelector:
matchLabels:
name: monitoring
ports:
- port: 9090
policyTypes:
- Ingress
---
# 3. Frontend only accepts traffic from the load balancer
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: frontend-policy
namespace: production
spec:
podSelector:
matchLabels:
app: frontend
ingress:
- from:
- podSelector:
matchLabels:
app: loadbalancer
ports:
- port: 8080
policyTypes:
- Ingress
---
# 4. Backend only accepts traffic from frontend
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-policy
namespace: production
spec:
podSelector:
matchLabels:
app: backend
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- port: 8443
policyTypes:
- Ingress
---
# 5. Database only accepts traffic from backend
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: database-policy
namespace: production
spec:
podSelector:
matchLabels:
app: database
ingress:
- from:
- podSelector:
matchLabels:
app: backend
ports:
- port: 5432
policyTypes:
- Ingress
```
### Verifying the policies actually work
Configuring is not the same as enforcing. I always verify with a throwaway pod before I trust the policy:
```bash
# List policies and pod labels
kubectl get networkpolicy -n production
kubectl get pods -n production --show-labels
# This should FAIL: database only accepts from backend
kubectl run test -it --rm --image=busybox --namespace=production -- sh
wget -qO- --timeout=2 http://backend:8443/health
# expect: connection timed out
# This should SUCCEED: frontend is allowed to reach backend
kubectl run test-frontend -it --rm --image=busybox --namespace=production --labels app=frontend -- sh
wget -qO- --timeout=2 http://backend:8443/health
# expect: 200 OK
```
### A Decision Tree for "Something Broke": Rule Out Enforcement First
When a dependency dies after you flip a policy, the first move is not "delete a rule." It is a four-step sequence that keeps you from patching the wrong thing:
First, identify exactly which segment broke. From the source pod, test both the path that should be allowed and the path that should be blocked. If the allowed path is dead too, your default-deny is too broad (a wrong `podSelector`), not a missing allow.
Second, check label matching. `kubectl get pods -n production --show-labels` against the `matchLabels` in your policy. The classic miss is a pod labeled `app.kubernetes.io/name: backend` while the policy writes `app: backend` — no match, so the policy silently does nothing.
Third, confirm the policy actually loaded. `kubectl get networkpolicy -n production` and look at which pods the unexpected policies hit. In a namespace, the moment any NetworkPolicy exists, a pod matched by none of them becomes fully open — a hole in your isolation. That is why the default-deny with `podSelector: {}` is non-negotiable: it catches every pod no other rule names.
Only after those three are ruled out do you conclude "missing allow," and only then add the rule — and only after the log-only stream confirms the flow is genuine business, not a new outbound that appeared on its own.
The value of the order: rule out "the policy never fired" before you suspect "the policy is too tight." Get that backwards and you keep adding rules in the wrong direction, and the set gets messier, not cleaner.
## Virtualized Stacks: NSX-T and Alibaba TIGER
Bare-metal Kubernetes is one world; virtualized VMs are another. When I segment a [vSphere](https://docs.vmware.com/en/VMware-vSphere/) estate I use NSX-T security groups and rules. The pattern is identical to NetworkPolicy — build groups, write a default drop, then allow the business chain.
```powershell
# VMware NSX-T PowerShell CLI
# 1. Build logical security groups
New-NsxSecurityGroup -Name "frontend-servers" -Description "Frontend tier"
Add-NsxSecurityGroupMember -SecurityGroup "frontend-servers" -Member @("vm-frontend-01","vm-frontend-02")
New-NsxSecurityGroup -Name "backend-servers" -Description "Backend tier"
Add-NsxSecurityGroupMember -SecurityGroup "backend-servers" -Member @("vm-backend-01","vm-backend-02")
New-NsxSecurityGroup -Name "database-servers" -Description "Database tier"
Add-NsxSecurityGroupMember -SecurityGroup "database-servers" -Member @("vm-db-01","vm-db-02")
# 2. Default drop, then the business chain
New-NsxPolicySecurityRule -DisplayName "deny-all-default" -Direction Ingress -Action DROP
New-NsxPolicySecurityRule -DisplayName "allow-monitoring" -Direction Ingress -Action ALLOW -SourceGroups @("monitoring-servers") -DestinationGroups @("*") -Protocol TCP -DestinationPorts @("9090")
New-NsxPolicySecurityRule -DisplayName "frontend-to-backend" -Direction Ingress -Action ALLOW -SourceGroups @("frontend-servers") -DestinationGroups @("backend-servers") -Protocol TCP -DestinationPorts @("8443")
New-NsxPolicySecurityRule -DisplayName "backend-to-database" -Direction Ingress -Action ALLOW -SourceGroups @("backend-servers") -DestinationGroups @("database-servers") -Protocol TCP -DestinationPorts @("5432")
# 3. Verify
Get-NsxPolicySecurityRule | Format-Table DisplayName, Action, SourceGroups, DestinationGroups
```
On Alibaba Cloud the equivalent is TIGER security groups, which follow the same model with CLI semantics I have found useful in Chinese regions:
```bash
# Alibaba Cloud TIGER micro-segmentation CLI
aliyun tiger CreateSecurityGroup --RegionId cn-hangzhou --SecurityGroupName frontend-sg --Description "Frontend tier"
aliyun tiger CreateSecurityGroup --RegionId cn-hangzhou --SecurityGroupName backend-sg --Description "Backend tier"
aliyun tiger CreateSecurityGroup --RegionId cn-hangzhou --SecurityGroupName database-sg --Description "Database tier"
aliyun tiger JoinSecurityGroup --RegionId cn-hangzhou --SecurityGroupId sg-frontend --InstanceId i-frontend-01
aliyun tiger JoinSecurityGroup --RegionId cn-hangzhou --SecurityGroupId sg-backend --InstanceId i-backend-01
aliyun tiger JoinSecurityGroup --RegionId cn-hangzhou --SecurityGroupId sg-database --InstanceId i-db-01
aliyun tiger CreateSecurityRule --RegionId cn-hangzhou --SecurityGroupId sg-frontend --Direction ingress --Policy deny --SourceType Any --DestType Any
aliyun tiger CreateSecurityRule --RegionId cn-hangzhou --SecurityGroupId sg-backend --Direction ingress --Policy allow --SourceType SecurityGroupId --SourceValue sg-frontend --DestType Port --DestValue 8443/tcp
aliyun tiger CreateSecurityRule --RegionId cn-hangzhou --SecurityGroupId sg-database --Direction ingress --Policy allow --SourceType SecurityGroupId --SourceValue sg-backend --DestType Port --DestValue 5432/tcp
```
## Physical Networks: ACLs as Coarse Segmentation
When there is no overlay to lean on, you fall back to ACLs on the switch or router. This is coarse — it is per-VLAN, not per-workload — but it is dramatically better than nothing.
```cisco
! Cisco IOS extended ACL: default-deny by relying on the implicit trailing
! "deny ip any any". Extended ACLs match top to bottom and stop at the first
! match, so explicit permits must come FIRST. Do NOT put an explicit
! "deny ip any any" before the permit — the permit would never be reached and
! the whole segment is blocked. That is exactly the bug we shipped once.
ip access-list extended FRONTEND-TO-BACKEND
permit tcp any any eq 8443
ip access-list extended BACKEND-TO-DATABASE
permit tcp any any eq 5432
interface Vlan100
ip access-group FRONTEND-TO-BACKEND in
interface Vlan200
ip access-group BACKEND-TO-DATABASE in
! Verify
show ip access-lists FRONTEND-TO-BACKEND
show ip access-lists BACKEND-TO-DATABASE
```
The VyOS equivalent uses policy routing for the same idea. I include it because so many of my edge routers run VyOS, and the syntax trips people up:
```bash
# VyOS policy-route ACL
set policy route FRONTEND-TO-BACKEND rule 10 description 'Allow frontend to backend on 8443'
set policy route FRONTEND-TO-BACKEND rule 10 match source address '10.0.1.0/24'
set policy route FRONTEND-TO-BACKEND rule 10 match destination address '10.0.2.0/24'
set policy route FRONTEND-TO-BACKEND rule 10 match protocol tcp
set policy route FRONTEND-TO-BACKEND rule 10 match tcp flags syn
set policy route FRONTEND-TO-BACKEND rule 10 match tcp port 8443
set policy route FRONTEND-TO-BACKEND rule 10 action accept
set policy route FRONTEND-TO-BACKEND rule 999 description 'Deny all else'
set policy route FRONTEND-TO-BACKEND rule 999 action drop
set interfaces ethernet eth0 policy input route 'FRONTEND-TO-BACKEND'
set interfaces ethernet eth1 policy input route 'BACKEND-TO-DATABASE'
```
## Two Breach Cases Where Segmentation Was the Difference
### Case 1: SQL injection with a database in the blast radius
A customer's frontend took a SQL injection. In the old flat network the attacker would have gone frontend → database directly. After I deployed the five-policy chain, the flow changed:
1. Attacker owns the frontend pod. ✅
2. Attacker tries frontend → database on 5432. ❌ blocked by `database-policy`.
3. Attacker tries frontend → backend on 8443. ❌ blocked by `backend-policy` (frontend is not in its source list).
4. The attempted connections hit audit logs.
The attacker got a frontend pod and nothing else. The audit trail gave the incident team a first-hop signal within minutes instead of weeks.
### Case 2: Ransomware that could not propagate
A phishing email landed on an employee laptop. The ransomware scanned the internal network looking for file servers. In the segmented design the employee segment only accepts traffic from the VPN gateway, and the resource segment rejects the employee segment entirely. The infection stayed on one laptop. The blast radius was a single machine instead of the whole office.
## The Operational Friction Nobody Warns You About
The policies are easy. The hard part is living with them.
### Policy explosion
As the business grows, the rule count grows superlinearly. The fix is selector-based policy, not one rule per workload. Label the tier once and match the label:
```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: tier-policy
namespace: production
spec:
podSelector:
matchLabels:
tier: database
ingress:
- from:
- podSelector:
matchLabels:
tier: backend
ports:
- port: 5432
policyTypes:
- Ingress
```
### Frequent business changes
Dependencies change faster than documentation. My answer is GitOps: the policy YAML lives in Git, a PR triggers review, CI applies it to a test namespace first, and only after validation does it reach production. This turns every policy change into a reviewable artifact.
### Debugging a broken policy
When a policy cuts a real dependency, the symptom is a mysterious timeout. My first move is always a dry-run audit, then a live test from the affected pod:
```bash
# Pre-validate policies: server-side dry-run checks the manifests are valid
# without actually applying them. (There is no "kubectl plugin verify" or
# "kubectl audit network-policy" — don't reach for a command that does not exist.)
kubectl apply --dry-run=server -f network-policies.yaml
# See recent policy changes: policy YAML lives in Git, so the change trail is the commits
git log --oneline --since=24h -- k8s/network-policies/
# Test from the exact pod that is failing
kubectl exec -n production test-pod -- wget -qO- --timeout=2 http://backend:8443/health
```
## Summary
Micro-segmentation is default-deny at the workload boundary, segmented by business domain and not by department. Kubernetes gets NetworkPolicy, virtualized stacks get NSX-T or TIGER, physical networks get ACLs. The chain that stops lateral movement is always the same: database accepts only backend, backend accepts only frontend, frontend accepts only the load balancer. My honest judgment: it is worth the investment, but only if you keep policies minimal and automate the change flow. Policy sprawl and operational friction are the real enemies — labels and GitOps are how you beat them.
## The Pre-Enforce Checklist
Before you flip to enforce, walk this list item by item. I paste it onto every policy change ticket; whoever signs it owns it:
- The log-only window ran through at least one full business cycle (including a peak day like a promotion or month-end close), so the allow list captures real peak traffic, not a quiet-hour snapshot.
- Every flow that appears in the list but not in the policy is patched in, and someone can name the business function each one serves.
- No `allow from any` anywhere, no port set to `any`. Every allow points at a specific source, destination, and port.
- The default-deny backstop (`podSelector: {}`) exists and covers every pod or VM no other rule selects.
- Rollback was exercised for real — flipped back to log-only and back again, confirmed to take effect in seconds, script not broken.
- Monitoring and alerting are wired to policy-hit and anomalous-outbound logs, so a new high-risk path fires an alert in the moment instead of showing up three weeks later in a log review.
- The change ticket states: which segment changed, which path opened, who approved, and the rollback window end date.
If any of these cannot be checked, do not flip to enforce. The benefit of micro-segmentation rests on "default-deny actually holding," and "actually holding" is what this list buys — not luck.
> **Original note**: This article is an independent English original written from first-hand production experience. It is not a translation of any Chinese source.
## Related Articles
- [TCP Troubleshooting: TIME_WAIT, RST, and Half-Open States](tcp-troubleshoot.md)
- [iptables Port Forwarding: SNAT/DNAT in Four Stanzas](iptables-port-forwarding.md)
- [Wireshark Basics: 30 Filters for Ops](wireshark-basics.md)
---
## Multi-Cloud Networking: Choosing the Right On-Ramp and Designing the Backbone
URL: https://ops.jiunotes.top/en/network/multicloud-network.md
摘要: A working engineer's multi-cloud networking guide: Direct Connect vs ExpressRoute vs CEN, when VPN beats a leased line and vice versa, three concrete cross-cloud cost optimizations, a BGP-plus-health-check failover design, and a real e-commerce multi-cloud case.
### Answer
Multi-cloud interconnection comes in three flavors: public internet (cheapest, highest latency), VPN tunnel (secure, medium cost), and dedicated line / Direct Connect (lowest latency, highest cost). Selection is scenario-driven: dev/test uses the public internet, non-critical production uses VPN, critical production uses a leased line. Cross-cloud egress cost is the hidden killer, and you tame it with routing, caching, and compression. Failover depends on BGP plus health checks — never a single link.
### FAQ
Q: What is the real difference between a dedicated line and a VPN?
A: A dedicated line is a physically isolated path (AWS Direct Connect, Azure ExpressRoute) with low latency, high bandwidth, and strong security — at high cost. A VPN is an encrypted tunnel over the public internet: cheap and fast to deploy, but latency is higher and bandwidth is capped. Critical production traffic gets the leased line; everything else gets the VPN.
Q: How do I cut cross-cloud traffic costs?
A: Three levers: (1) route cross-cloud traffic over a leased line instead of the public internet — typically 30-50% cheaper per GB; (2) cache hot data locally so you avoid the round trip; (3) compress and dedupe the payload. In one case I cut a 50 TB/month flow to 20 TB, saving 60% on egress.
Q: Is BGP mandatory in a multi-cloud setup?
A: For production, yes. BGP gives you dynamic route selection and automatic failover, which static routes cannot. VPN scenarios can get away with static routes, but a leased-line backbone really should run BGP. The config complexity is moderate and the reliability payoff is worth it.
Q: Can I run production on a single link?
A: No. I have seen a single Direct Connect cut take an entire region down. You need at least two paths — a primary and a backup. My standard is one leased line plus one VPN, both running BGP with a health check on the primary. The VPN may be slower, but a slow working link beats no link.
Q: What is the biggest mistake teams make with multi-cloud networking?
A: Treating cross-cloud traffic as free. Egress is billed per GB, and a chatty service-to-service call across clouds can silently eat your budget. I always measure the cross-cloud flow before designing the backbone. If it is under a few hundred MB per day, skip the leased line entirely.
### Full Content
# Multi-Cloud Networking: Choosing the Right On-Ramp and Designing the Backbone
Multi-cloud is easy to say and hard to wire together. I have built three multi-cloud backbones for production workloads, and every single time the network design — not the application — was the bottleneck. This article is the selection logic and cost discipline I now apply before I touch a single router.
## The Three Ways to Interconnect Clouds
There are exactly three ways to connect cloud A to cloud B, and they form a clean cost-versus-performance ladder.
### Option 1: The public internet (free, worst performance)
```
cloud A ──── internet ────> cloud B
(encrypted) (uncontrolled) (encrypted)
```
- **Cost**: zero extra — you already pay for egress
- **Latency**: 50-200ms, highly variable
- **Bandwidth**: capped by congestion
- **Security**: relies entirely on IPSec/TLS
- **Availability**: you have no control over carrier routing
I use this only for dev/test environments, non-critical replication, and backup transfers where latency is tolerable. The moment it carries production traffic, I stop trusting it.
```bash
# AWS Site-to-Site VPN over the public internet
aws ec2 create-vpn-connection \
--transit-gateway-id tgw-xxxxxx \
--type ipsec.1 \
--static-routes-only \
--bgp-asn 65000 \
--amazon-side-asn 64512
```
### Option 2: VPN tunnel (medium cost, medium performance)
```
cloud A ──IPSec──> cloud B
```
- **Cost**: VPN gateway hourly fees
- **Latency**: 30-100ms
- **Bandwidth**: capped by the gateway's crypto throughput
- **Security**: high — IPSec encryption end to end
- **Availability**: depends on the public path, but the payload is protected
This is my default for non-critical production services and for rapid deployment where a leased line has a multi-week lead time.
### Option 3: Dedicated line / Direct Connect (highest cost, best performance)
```
cloud A ══leased line══> cloud B
```
- **Cost**: monthly circuit fee, plus port hour fees on each side
- **Latency**: 10-50ms, stable
- **Bandwidth**: 1Gbps up to 100Gbps
- **Security**: physical isolation
- **Availability**: SLA-backed
This is the only option I put critical production traffic on. It also covers the compliance requirement of "data never crosses the public internet."
## The Three Cloud On-Ramps, Side by Side
AWS, Azure, and Alibaba each expose a dedicated-line service with slightly different names and semantics. I have configured all three, and the differences matter more than the marketing suggests.
| Service | Provider | Abstraction | Typical latency | BGP support | Best for |
|---|---|---|---|---|---|
| AWS Direct Connect | AWS | Virtual interface per VPC | 5-20ms | Native | AWS-centric estates |
| Azure ExpressRoute | Azure | Circuit with private peering | 5-20ms | Native | Microsoft-heavy workloads |
| Alibaba Cloud CEN | Alibaba | Cloud Enterprise Network, inter-VPC | 5-20ms | Native | China-region estates |
The key operational difference: Direct Connect and ExpressRoute are per-cloud constructs, so a true multi-cloud backbone needs one of each plus a transit hub to stitch them together. CEN is a network-of-networks abstraction that can connect multiple VPCs and even other clouds through a gateway, which makes it the most convenient when Alibaba is your hub. My rule of thumb: if the backbone is two clouds, use a Transit Gateway hub with a Direct Connect spine and a CEN or ExpressRoute leg; if it is three or more, put CEN at the center and hang the others off it.
### VPN vs dedicated line: the honest trade-off
A VPN is not a cheap dedicated line — it is a different animal. I keep this table on my whiteboard:
| Dimension | VPN tunnel | Dedicated line |
|---|---|---|
| Setup time | Hours to days | Weeks to months |
| Latency | 30-100ms, variable | 10-50ms, stable |
| Bandwidth | Gateway crypto-bound | 1-100Gbps |
| Cost model | Hourly gateway | Monthly circuit |
| SLA | Best effort | Contract-backed |
| Failure mode | Reconnect after outage | Physical cut needs carrier |
The practical consequence: I use a VPN for the backup path and a dedicated line for the primary. The VPN is cheap enough to keep warm, and even a degraded backup is better than a single point of failure.
## The Selection Decision Tree
I do not pick a technology in the abstract — I answer four questions in order:
```
What is the workload?
├─ dev/test, backup replication ────── public internet (free)
├─ production, non-critical
│ ├─ need <50ms? ── yes ── dedicated line
│ ├─ need >1Gbps? ── yes ── dedicated line
│ └─ otherwise ────────────── VPN tunnel
└─ production, critical
├─ latency-sensitive (<50ms)? ── dedicated line
├─ bandwidth-hungry (>1Gbps)? ── dedicated line
└─ compliance (no public path)? ── dedicated line
```
The one rule I refuse to break: **critical production always gets at least one dedicated line, and never a single link.** If I cannot justify the cost, the workload is not actually critical.
## Cross-Cloud Traffic Cost: The Silent Budget Killer
Egress is the line item nobody budgets for until it shows up on the invoice. Three optimizations, in order of impact.
### Optimization 1: Route cross-cloud traffic over the leased line
This is the biggest lever, because the per-GB rate on a leased line is meaningfully lower than public egress. A real comparison from one e-commerce tenant, at ~50 TB/month:
| Path | Rate | Monthly cost | Annual cost |
|---|---|---|---|
| Public internet | $0.09/GB | $4,500 | $54,000 |
| Leased line | $0.05/GB | $2,500 | $30,000 |
| **Saving** | — | **$2,000** | **$24,000** |
### Optimization 2: Cache hot data locally
The cheapest request is the one you never make. I put a local cache in front of every remote-region read:
```python
import redis
class CrossCloudCache:
def __init__(self, local_region, remote_regions):
self.local_region = local_region
self.remote_regions = remote_regions
self.cache = redis.[Redis](https://redis.io/docs/)(host='localhost', port=6379, db=0)
def get(self, key, remote_client=None):
# local hit first — avoids the cross-cloud round trip
cached = self.cache.get(key)
if cached:
return cached.decode()
# local miss — fetch from remote, then cache with a 5-minute TTL
if remote_client:
value = remote_client.get(key)
if value:
self.cache.setex(key, 300, value)
return value.decode()
return None
```
### Optimization 3: Compress and dedupe
For large bulk transfers, compression and deduplication pay for themselves. AWS Transfer Family and Alibaba DTS both expose this:
```bash
# AWS Transfer Family with compression
aws transfer create-server \
--protocol SFTP \
--endpoint-type VPC \
--subnet-ids subnet-xxxx subnet-yyyy \
--security-group-ids sg-zzzz \
--role-arn arn:aws:iam::123456789012:role/transfer-role \
--compression-enabled
# Alibaba DTS with dedupe + compression
aliyun dts ModifyDtsJob \
--JobId dts-job-xxxx \
--DataRedundancy ENABLED \
--CompressEnabled ENABLED
```
## Failover Design: BGP Plus Health Check
Static routes die silently. BGP does not. My backbone always runs BGP with a tight keepalive timer so a cut is detected in seconds, not minutes:
```bash
router bgp 64512
neighbor 169.254.33.1 remote-as 64512
neighbor 169.254.33.1 update-source Eth1
neighbor 169.254.33.1 timers bgp 10 30
neighbor 169.254.33.1 distance 20 200
network 10.0.0.0 255.255.0.0
!
track 1 ip route 10.0.0.0 255.255.0.0 reachability
interface Eth1
ip address 169.254.33.2 255.255.255.252
ip track 1
```
On the application side, the failover logic is a health-check loop that flips DNS and routing when the primary degrades:
```python
import asyncio
import aiohttp
class MultiCloudFailover:
def __init__(self, primary, secondary, interval=30):
self.primary = primary
self.secondary = secondary
self.interval = interval
self.is_primary_healthy = True
async def health_check_loop(self):
while True:
await self.check_health()
await asyncio.sleep(self.interval)
async def check_health(self):
try:
async with aiohttp.ClientSession() as s:
async with s.get(f'{self.primary}/health', timeout=aiohttp.ClientTimeout(total=5)) as r:
if r.status == 200:
if not self.is_primary_healthy:
self.is_primary_healthy = True
print("primary recovered")
elif self.is_primary_healthy:
self.is_primary_healthy = False
await self.switch_to_secondary()
except Exception:
if self.is_primary_healthy:
self.is_primary_healthy = False
await self.switch_to_secondary()
async def switch_to_secondary(self):
await self.update_dns('app.example.com', self.secondary.ip)
await self.update_routing(self.secondary)
await self.notify_ops(f"switched to {self.secondary.name}")
```
## Real Case: A Three-Region E-Commerce Backbone
A customer ran production in AWS us-east-1, Southeast Asia in ap-southeast-1, and mainland China in Alibaba cn-hangzhou. They moved ~80 TB/month between regions. Public-internet latency was ~200ms; the leased-line path was ~50ms. The backbone used a Transit Gateway hub with a 1Gbps Direct Connect as the spine, and VPN tunnels as the legs. The results after six months:
| Metric | Before | After | Change |
|---|---|---|---|
| Cross-cloud cost | $7,200/mo | $3,600/mo | 50% ↓ |
| China-user latency | 200ms | 50ms | 75% ↓ |
| SE-Asia latency | 180ms | 45ms | 75% ↓ |
| Failover time | 10 min (manual) | 30s (auto) | 95% ↓ |
The failover test that convinced me: I killed the health-check endpoint on the primary, watched DNS flip, and the application was serving from the secondary within 30 seconds. That is the difference between BGP plus health checks and a human with a phone tree.
## Configuration Checklist
Before I sign off on any backbone, I run this against both ends:
```bash
# 1. Link health
curl -f http://primary-cloud/health || echo "primary unhealthy"
curl -f http://secondary-cloud/health || echo "secondary unhealthy"
# 2. Bandwidth utilization
aws cloudwatch get-metric-statistics \
--namespace AWS/DirectConnect \
--metric-name BandwidthUtilization \
--dimensions Name=connectionId,Value dxcon-xxxxxx \
--start-time $(date -Iseconds -d '1 hour ago') \
--end-time $(date -Iseconds) \
--period 300 --statistics Average
# 3. Latency and path
ping -c 10
traceroute -n
# 4. BGP neighbor state
show ip bgp summary
show bgp neighbors
# 5. Cross-cloud cost
aws ce get-cost-and-usage \
--time-period Start=$(date -Iseconds -d '7 days ago'),End=$(date -Iseconds) \
--granularity MONTHLY --metrics UnblendedCost
```
## Summary
Multi-cloud interconnection is a selection problem, not a technology problem. Dev/test uses the public internet, non-critical production uses a VPN, and critical production gets a dedicated line — never a single one. Cross-cloud egress cost is the silent killer, and the fix is routing over the leased line, caching hot data locally, and compressing bulk flows. Failover belongs to BGP plus automated health checks. My honest judgment: budget for at least two paths per critical region, and measure your cross-cloud flow before you buy anything. The backbone is a cost center until the day it saves your business — and on that day you will be glad you did not cheap out.
> **Original note**: This article is an independent English original written from first-hand production experience. It is not a translation of any Chinese source.
## Related Articles
- [Nginx Reverse Proxy 502/504 Troubleshooting](nginx-proxy.md)
- [CDN Principles: Origin Fetch, Preheat, Cache Invalidation](cdn-principles.md)
- [TCP Troubleshooting: TIME_WAIT, RST, and Half-Open States](tcp-troubleshoot.md)
---
## Endpoint driver-baseline conflict decision tree — no sound / speaker stays on with headphone plugged in
URL: https://ops.jiunotes.top/en/network/network-driver-baseline-conflict.md
摘要: A classic endpoint failure — staff report the PC suddenly has no sound, or the speaker keeps playing after a headphone is plugged in. This page gives a troubleshooting decision tree — confirm it is "GPU HDMI audio vs onboard sound-card driver conflict" or "audio default policy reset after a Windows update", then pinpoint in three steps with Device Manager, Windows Audio service and mmsys.cpl, and finish with a driver baseline and disabling unnecessary automatic driver updates.
### Answer
When a PC suddenly has no sound, or the speaker keeps playing after a headphone is plugged in, it is usually not a burnt sound card and not a broken jack — it is a driver/policy conflict: the GPU HDMI audio and the onboard sound-card driver fight over the default device, or a Windows update reset the Realtek audio manager's default playback policy so the output device silently changed. Confirm the "Device Manager shows no sound-card warning, the service is running, only the default device is wrong" signature, then use Device Manager for driver state, services.msc for Windows Audio, and mmsys.cpl for the default playback device, to pinpoint in three steps. The cure is a hardened endpoint driver baseline and turning off unnecessary automatic driver updates.
### FAQ
Q: The sound card shows no warning in Device Manager, so why is there still no sound?
A: No warning means the driver "installed and runs" — the problem is usually higher up — the default playback device was changed. The most common case is the GPU HDMI audio being set as default, so sound goes entirely to the monitor (no speakers on the monitor = "no sound"); or after an update the Realtek manager's default policy fell back and output switched from "speakers" to another device. The driver is not broken; "where the sound goes" was changed.
Q: The speaker keeps playing after I plug in headphones — is the jack broken?
A: Probably not. This is "the front-panel jack was not correctly recognized as the default communication/playback device". The front-panel audio jack must be set in the Realtek manager to "switch default device on insert"; once that policy is reset by an update, the system keeps playing from the onboard speaker and the headphone is plugged in for nothing. First check in mmsys.cpl whether the default device switched to the headphone, then judge hardware.
Q: How do I confirm the GPU HDMI audio is hijacking the device?
A: In Device Manager -> Sound, video and game controllers you usually see multiple devices like "Realtek High Definition Audio" and "NVIDIA/AMD HDMI Audio". Open mmsys.cpl and see whether the "default device" landed on the HDMI entry. Change the default back to the Realtek speaker and sound returns immediately — that confirms HDMI audio took the default.
Q: Why does it break right after a system update?
A: Windows Update quietly updates drivers too (especially GPU/sound), and a newer driver may reset the default device or be incompatible with the older Realtek manager policy. Many "suddenly no sound at work" cases are actually the driver auto-installed the night before. So the cure is to lock the driver version into a baseline and turn off unnecessary automatic driver updates, not to fix each incident after it happens.
Q: What exactly does a driver baseline harden?
A: Three things — 1) lock validated sound/GPU driver versions (don't chase latest); 2) use GPO or an imaging template to harden the default playback device and Realtek manager policy; 3) disable Windows Update automatic driver updates (or exclude driver-class updates). Then a fresh build/reinstall gets a "known-good" state and stops varying randomly.
### Full Content
# Endpoint driver-baseline conflict decision tree — no sound / speaker stays on with headphone plugged in
There is a "soft failure" on office endpoints: a staff member comes in saying "the PC suddenly has no sound", or "I plug in headphones but the speaker keeps playing — awkward". The first reflex drifts toward "the sound card burnt out" or "the headphone jack is broken", so a hardware ticket is filed — yet Device Manager shows the sound card fine and swapping headphones does nothing.
The signature of this fault is **"hardware is fine, driver runs, only the sound goes to the wrong place or the policy was reset"**. The root is usually the GPU HDMI audio vs onboard sound-card fight over the default device, or an update knocking the audio policy back to factory. The decision tree below handles the "endpoint audio driver/policy conflict" class.
## 60-second check — is it a driver/policy conflict?
Self-test with one sentence:
> No yellow warning on the sound card in Device Manager, Windows Audio service is running, but no sound or the device won't switch; and it often appears after a system update → **strongly suspect HDMI audio hijacking the default device / audio policy reset**.
If Device Manager shows a yellow warning on the sound card or the device has vanished entirely, that is either a driver that is not installed properly or a hardware issue — outside this page.
## Troubleshooting decision tree
```
User reports: no sound / speaker stays on with headphone plugged in
│
├─ Check Device Manager first
│ ├─ Sound card yellow warning / missing? → driver truly broken, install / roll back
│ └─ Sound card normal, no warning? → software layer (default device / service)
│
├─ Check Windows Audio service
│ ├─ Service stopped / disabled? → start Windows Audio + Audio Endpoint Builder
│ └─ Service running? → check default playback device
│
├─ mmsys.cpl default playback device
│ ├─ Default is "HDMI audio"? → sound goes to monitor, switch back to Realtek speaker ★most common
│ ├─ Headphone not switching on plug-in? → front-panel policy not "switch on insert", set in Realtek
│ └─ Default correct but still silent? → check enhancements / format or roll back driver
│
└─ Root-cause locating
├─ Happened after system update? → new driver reset default device / policy incompatible
└─ Multiple audio devices coexist? → HDMI and onboard fight default, need hardening
```
The hinge of the whole tree is one line: **first confirm "driver not installed or default device changed", then see whether it is service, HDMI or policy**. That step "yellow warning in Device Manager?" is the pivot — it cleanly cuts "hardware broken" from "setting was changed".
## Three-step locating procedure
### Step 1 — Device Manager for driver state
```
1. Right-click Start -> Device Manager -> "Sound, video and game controllers"
2. See whether Realtek / onboard sound card has a yellow warning, or the device is missing
3. Warning -> right-click "Update driver / Roll back driver"; no warning -> next step
```
Note: no warning means the driver loaded fine; the problem is most likely at the "where does sound output go" setting layer, not the driver itself.
### Step 2 — confirm Windows Audio service is running
```bat
services.msc :: find "Windows Audio" and "Windows Audio Endpoint Builder"
:: both should be "Running"; if disabled, start and set to Automatic
```
These two services are the foundation of the audio subsystem. Being disabled (common from over-eager cleanup scripts) silences everything while Device Manager still looks "fine".
### Step 3 — mmsys.cpl for the default playback device
```
1. Control Panel -> Sound (mmsys.cpl) -> "Playback" tab
2. See which device is "Default": should be Realtek speaker / headphone
3. If it is the "HDMI" device -> right-click it, "Set as default", switch back to speaker
4. Headphone still external? In Realtek manager, set front-panel jack to "switch default on insert"
```
HDMI audio as default is the most common "no sound" root — sound goes to the monitor, monitor has no speaker, hence "no sound". Switching back to the speaker recovers instantly.
## Emergency stopgap — restore default audio output (checklist)
This is an **endpoint-side emergency checklist** (not a script; audio settings are done in the system):
```
1. mmsys.cpl -> Playback -> set Realtek speaker as default device
2. If headphone still external: Realtek manager -> advanced device settings -> tick "switch default on front-panel insert"
3. Service abnormal: services.msc start Windows Audio + Endpoint Builder, set Automatic
4. Still failing: Device Manager roll back / reinstall sound driver to baseline version
```
**Honest note**: default-device/policy fixes must be done in the endpoint system; there is no copy-run "one-click script" that reroutes system audio. The above is a troubleshooting and recovery checklist, not code; for bulk scenarios use a driver baseline and GPO hardening, not per-machine manual.
## Root cause — stop "random no sound" from recurring
Recovering one machine is only a stopgap. Endpoints number in the hundreds with varied drivers; manual fixes never catch up. Close it off in three layers:
| Layer | Action | Prevents |
|---|---|---|
| Version | Lock validated sound/GPU driver versions, don't chase latest; fresh builds pull "known-good" versions from the imaging template | new driver resets default device / incompatible with old policy |
| Policy | GPO / imaging template hardens default playback device and Realtek manager policy (insert-switch etc.) | update knocks audio policy back to factory |
| Update | Disable Windows Update automatic driver updates, or exclude driver-class updates | nightly auto-installed driver causes "sudden no sound one day" |
One often-missed point: **"no sound" is eight times out of ten not hardware, but HDMI audio hijacking the default**. Many office PCs connect a monitor with speakers (or iGPU HDMI), and the system identifies HDMI audio as the preferred output by default. Once the "known-good" default device and driver version are baked into the baseline, this ticket class drops by more than half.
## Quick decision table (use it directly)
| Symptom | First reflex (misjudged) | Real root cause | Where to look |
|---|---|---|---|
| Suddenly no sound | sound card burnt | HDMI audio set default, goes to monitor | mmsys.cpl default device |
| Speaker on with headphone plugged | jack broken | front-panel not set to switch on insert | Realtek manager policy |
| No warning but silent | driver problem | default device changed / service stopped | service + default device |
| Broke after system update | coincidence | new driver reset policy / incompatible | roll back to baseline version |
| Swapping headphones did nothing | headphone broken | root is system setting, not headphone | mmsys.cpl |
This table is the landing version of "what it is most easily misjudged as" — eight out of ten tickets of this class open as "sound card broken, replace it", and checking against this table skips most wasted effort and mistaken hardware swaps.
## FAQ
**Q: The sound card shows no warning in Device Manager, so why is there still no sound?**
A: No warning means the driver "installed and runs" — the problem is usually higher up: the default playback device was changed. The most common case is the GPU HDMI audio being set as default, so sound goes entirely to the monitor (no speakers on the monitor = "no sound"); or after an update the Realtek manager's default policy fell back and output switched from "speakers" to another device. The driver is not broken; "where the sound goes" was changed.
**Q: The speaker keeps playing after I plug in headphones — is the jack broken?**
A: Probably not. This is "the front-panel jack was not correctly recognized as the default communication/playback device". The front-panel audio jack must be set in the Realtek manager to "switch default device on insert"; once that policy is reset by an update, the system keeps playing from the onboard speaker and the headphone is plugged in for nothing. First check in mmsys.cpl whether the default device switched to the headphone, then judge hardware.
**Q: How do I confirm the GPU HDMI audio is hijacking the device?**
A: In Device Manager -> Sound, video and game controllers you usually see multiple devices like "Realtek High Definition Audio" and "NVIDIA/AMD HDMI Audio". Open mmsys.cpl and see whether the "default device" landed on the HDMI entry. Change the default back to the Realtek speaker and sound returns immediately — that confirms HDMI audio took the default.
**Q: Why does it break right after a system update?**
A: Windows Update quietly updates drivers too (especially GPU/sound), and a newer driver may reset the default device or be incompatible with the older Realtek manager policy. Many "suddenly no sound at work" cases are actually the driver auto-installed the night before. So the cure is to lock the driver version into a baseline and turn off unnecessary automatic driver updates, not to fix each incident after it happens.
**Q: What exactly does a driver baseline harden?**
A: Three things: 1) lock validated sound/GPU driver versions (don't chase latest); 2) use GPO or an imaging template to harden the default playback device and Realtek manager policy; 3) disable Windows Update automatic driver updates (or exclude driver-class updates). Then a fresh build/reinstall gets a "known-good" state and stops varying randomly.
## Further reading and references
- [Microsoft Learn — Device Manager and driver rollback](https://learn.microsoft.com/windows-hardware/drivers/) — viewing driver state, rolling back to the previous version (follow your environment docs)
- [Microsoft Learn — configure Windows Update (incl. driver update policy)](https://learn.microsoft.com/windows/deployment/update/) — path to control automatic driver updates via GPO
- [Microsoft — mmsys.cpl sound settings](https://support.microsoft.com/) — entry point for default playback/recording device settings
> This page is a troubleshooting decision asset. External links are authority references only; specific GPO and driver versions depend on your domain environment.
## Related guides and tools
- [Internal DNS resolution failure decision tree](network-internal-dns-failure.md) — same-column sibling: another "only some endpoints fail" office failure
- [Endpoint time skew and root-certificate decision tree](network-endpoint-time-cert-error.md) — same-column sibling: endpoint-side cert validation failure
- [Return-to-office network anomaly decision tree](network-return-to-office-network-reset.md) — same-column sibling: endpoint carrying old-network memory
> The fault case in this page comes from a real endpoint site, used as a credibility anchor for the judgment. Actual GPO and driver versions depend on your domain environment.
---
## Endpoint time skew and root-certificate decision tree — "certificate error" on web login
URL: https://ops.jiunotes.top/en/network/network-endpoint-time-cert-error.md
摘要: A classic office-network failure — the finance/business web portal greets login with "certificate error" or "can't establish a secure connection", yet the server certificate is not actually expired. This page gives a troubleshooting decision tree: confirm it is "endpoint system clock skew or missing root certificate", then check time sync with w32tm and trusted roots with certmgr, and finish with GPO-forced time sync and domain-pushed root CA.
### Answer
When a business portal login shows "certificate error" but the server certificate is not expired and the network is not hijacked, the problem is usually the endpoint itself: the system clock is badly skewed (CMOS battery died and reset to 2010), so TLS validation fails because "now" is outside the cert validity window; or the internal root CA was never pushed to that endpoint. Confirm the "only a few endpoints report it, and clearing cache / switching browser does not help" signature, then use w32tm /query /status for time sync and certmgr.msc for trusted roots. The cure is GPO-forced endpoint time sync and domain-wide root-CA distribution.
### FAQ
Q: The server certificate is clearly not expired, so why does the endpoint report "certificate error"?
A: During TLS handshake the client validates the certificate validity window (notBefore to notAfter) against its own system clock. If the endpoint clock was reset to 2010 (common with a dead CMOS battery), a cert issued in 2024 looks "not yet valid" or "already expired" to that endpoint and fails outright. The server-side cert is perfectly fine; the endpoint's own clock broke the validation baseline.
Q: How do I quickly tell a time problem from a root-certificate problem?
A: Read the browser wording: "cert not yet valid / expired" (NET::ERR_CERT_DATE_INVALID) points to time; "issuer not trusted / not authoritative" (NET::ERR_CERT_AUTHORITY_INVALID) points to a missing root. Then confirm in two steps: w32tm /query /status for clock and offset; certmgr.msc for whether your internal CA is in "Trusted Root Certification Authorities". The two directions are fixed with different means.
Q: What does w32tm showing "Source: Local CMOS Clock" mean?
A: It means the endpoint is not syncing to any time server at all; time comes from the motherboard CMOS and jumps when the battery dies. A healthy domain endpoint should show the source as your domain controller or NTP server. Seeing "Local CMOS Clock" basically confirms time sync is broken — pull it back to the domain/GPO-specified NTP source first.
Q: Must I install the internal root certificate manually on every machine?
A: No, you should not. Manual install is slow and leak-prone; the right way is to push the internal CA root to the "Trusted Root CA" store via domain GPO. Newly domain-joined machines get it automatically, and rebuilds recover automatically too. A manually installed machine loses it on reinstall, which only manufactures more "single endpoint cert errors".
Q: Will GPO-forced time sync conflict with the business system's scheduled tasks?
A: No. Time sync is a background periodic correction, a different thing from business scheduling; not forcing it is what causes trouble — once the clock drifts far, timestamp-dependent logs, scheduled tasks and Kerberos auth all break. Point the GPO time source at the domain controller with a sensible interval; no conflict with business scheduling.
### Full Content
# Endpoint time skew and root-certificate decision tree — "certificate error" on web login
There is a misdiagnosed office-network failure: a staff member clicks login on the finance or business web portal and the browser pops "certificate error" or "can't establish a secure connection". IT's first reflex is "the server cert expired" or "the network is hijacked", so they check the server cert and the firewall — only to find the server cert is fine and another computer logs in normally.
The signature of this fault is **"only a few endpoints report it, and the server is fine"**. The root is usually the endpoint itself: a badly skewed system clock, or an internal root cert never pushed to that machine. The decision tree below handles the "endpoint-side cert validation failure" class.
## 60-second check — is it endpoint-side?
Self-test with one sentence:
> Same system, computer A logs in fine, computer B reports "certificate error"; and switching browser / clearing cache on B does not help → **strongly suspect B's clock skew or missing root certificate**.
If every endpoint reports it and the server truly uses a self-signed cert, that is a server-side cert problem — outside this page.
## Troubleshooting decision tree
```
User reports: business portal login shows "certificate error / can't establish secure connection"
│
├─ Confirm the scope
│ ├─ Only a few endpoints? → endpoint-side (check time / root cert)
│ └─ All endpoints? → check server cert / intermediate chain
│
├─ Read the browser wording
│ ├─ "cert not yet valid / expired" → mostly endpoint clock skew ★most common
│ └─ "issuer not trusted / not authoritative" → mostly missing root cert
│
├─ w32tm /query /status (time)
│ ├─ Source "Local CMOS Clock" or huge offset? → time sync broken, pull back to NTP
│ └─ Time normal, small offset? → not time, check root cert
│
├─ certmgr.msc (root cert)
│ ├─ Internal CA absent from "Trusted Root CAs"? → root not pushed, GPO distribute
│ └─ Root present but chain incomplete? → add intermediate
│
└─ Root-cause locating
├─ CMOS battery dead -> clock reset to 2010? → replace battery + GPO force sync
└─ New build / reinstall not joined to domain? → GPO auto-pushes root after join
```
The hinge of the whole tree is one line: **first confirm "a few endpoints or the server", then read whether the error is "time" or "root cert"**. That step "compare two endpoints A/B + read the wording" is the pivot — it pulls the fire away from the server back to the endpoint.
## Three-step locating procedure
### Step 1 — read the browser error, split the two classes
```bat
:: Chrome/Edge: click the lock icon in the address bar -> view certificate
:: Two common classes:
:: NET::ERR_CERT_DATE_INVALID -> cert date invalid (endpoint time problem)
:: NET::ERR_CERT_AUTHORITY_INVALID -> issuer not trusted (root cert missing)
```
Note: the wording already points the direction — do not reinstall certs on sight; first see whether it is "time" or "root cert".
### Step 2 — check endpoint time sync
```bat
w32tm /query /status :: see if "Source" is DC/NTP and how big the offset is
w32tm /query /source :: healthy shows DC or NTP server, not "Local CMOS Clock"
```
If "Source" is "Local CMOS Clock", the machine is not syncing to any time server at all — the time baseline is already untrustworthy; pull it back to the GPO-specified NTP source first.
### Step 3 — check trusted root certificates
```bat
certmgr.msc :: GUI: Trusted Root Certification Authorities -> Certificates
:: see whether your internal CA root is present
```
If the internal business system uses a self-signed or internal-CA-issued cert, the endpoint must hold that CA root to trust it. Missing it = "issuer not trusted".
## Emergency stopgap — restore access temporarily (symptom only)
This is an **endpoint-side emergency checklist** (not a script; cert/time operations are done in the system):
```
1. Time: manually w32tm /resync to pull back DC time; if source is CMOS, set source then sync
2. Root: import internal CA root into "Trusted Root CA" store (manual is stopgap; GPO is cure)
3. Verify: reopen the business system, cert error should disappear
4. Note whether the endpoint is domain-joined / newly built, to decide GPO hardening
```
**Honest note**: time and root-cert fixes must be done on the endpoint/domain controller; there is no universal "one-click script". The above is a troubleshooting and temporary-recovery checklist, not code; for bulk scenarios always use GPO, not manual.
## Root cause — stop "single endpoint cert errors" from recurring
Recovering one machine is only a stopgap. Enterprises have hundreds of endpoints; manual fixes never catch up. Close it off in three layers:
| Layer | Action | Prevents |
|---|---|---|
| Time | GPO-force endpoint time sync, source to DC/NTP, set interval and offset-threshold alert | CMOS battery dead -> clock reset -> cert validation fail |
| Cert | Push internal CA root to "Trusted Root CA" store via domain GPO | new build / reinstall leaves root missing |
| Audit | Monitor % of domain endpoints with >5min time offset; auto-ticket machines missing root | individual endpoints silently drift, caught early |
One often-missed point: **a dead CMOS battery is the number-one cause of time skew**. Many office machines run three to five years; once the CMOS battery dies, the clock jumps back to 2010 and TLS cert validation goes red across the board. GPO-forced sync pulls time back after boot+network, but the battery itself still needs replacing — otherwise it drifts again offline.
## Quick decision table (use it directly)
| Symptom | First reflex (misjudged) | Real root cause | Where to look |
|---|---|---|---|
| A few endpoints report cert error | server cert expired | that endpoint's clock skew | w32tm /query /status |
| Still errors after browser switch | network hijacked | root cert not pushed | certmgr trusted roots |
| "date invalid" error | cert really expired | endpoint clock reset to past | system time + battery |
| "issuer not trusted" error | CA untrustworthy | internal CA root missing | domain GPO root push |
| Starts after OS reinstall | system problem | not joined / GPO not pushed | join domain + root cert |
This table is the landing version of "what it is most easily misjudged as" — eight out of ten tickets of this class open as "server cert expired again", and checking against this table skips most wasted effort.
## FAQ
**Q: The server certificate is clearly not expired, so why does the endpoint report "certificate error"?**
A: During TLS handshake the client validates the certificate validity window (notBefore to notAfter) against its own system clock. If the endpoint clock was reset to 2010 (common with a dead CMOS battery), a cert issued in 2024 looks "not yet valid" or "already expired" to that endpoint and fails outright. The server-side cert is perfectly fine; the endpoint's own clock broke the validation baseline.
**Q: How do I quickly tell a time problem from a root-certificate problem?**
A: Read the browser wording: "cert not yet valid / expired" (NET::ERR_CERT_DATE_INVALID) points to time; "issuer not trusted / not authoritative" (NET::ERR_CERT_AUTHORITY_INVALID) points to a missing root. Then confirm in two steps: w32tm /query /status for clock and offset; certmgr.msc for whether your internal CA is in "Trusted Root Certification Authorities".
**Q: What does w32tm showing "Source: Local CMOS Clock" mean?**
A: It means the endpoint is not syncing to any time server at all; time comes from the motherboard CMOS and jumps when the battery dies. A healthy domain endpoint should show the source as your domain controller or NTP server. Seeing "Local CMOS Clock" basically confirms time sync is broken — pull it back to the domain/GPO-specified NTP source first.
**Q: Must I install the internal root certificate manually on every machine?**
A: No, you should not. Manual install is slow and leak-prone; the right way is to push the internal CA root to the "Trusted Root CA" store via domain GPO. Newly domain-joined machines get it automatically, and rebuilds recover automatically too. A manually installed machine loses it on reinstall, which only manufactures more "single endpoint cert errors".
**Q: Will GPO-forced time sync conflict with the business system's scheduled tasks?**
A: No. Time sync is a background periodic correction, a different thing from business scheduling; not forcing it is what causes trouble — once the clock drifts far, timestamp-dependent logs, scheduled tasks and Kerberos auth all break. Point the GPO time source at the domain controller with a sensible interval; no conflict with business scheduling.
## Further reading and references
- [Microsoft Learn — w32tm command reference](https://learn.microsoft.com/windows-server/networking/windows-time-service/windows-time-service-tools-and-settings) — time sync status query, set source, resync official notes
- [Microsoft Learn — configure time service via Group Policy](https://learn.microsoft.com/windows-server/networking/windows-time-service/windows-time-service-top) — GPO-forced endpoint time sync configuration path
- [Microsoft Learn — Certificate Manager (certmgr)](https://learn.microsoft.com/) — view/import trusted root certificates (follow your environment docs)
- [Cloudflare — What is the TLS certificate chain](https://www.cloudflare.com/learning/ssl/what-is-ssl/) — the basics of root/intermediate certificates and validity-window validation
> This page is a troubleshooting decision asset. External links are authority references only; specific GPO and certificate operations depend on your domain environment docs.
## Related guides and tools
- [NTP time sync](ntp-time-sync.md) — principles and deployment of time sync; this page is its "endpoint-side failure" companion
- [SSL/TLS handshake troubleshooting](ssl-tls-handshake-troubleshoot.md) — deeper digging when the error points at handshake / cert chain
- [Internal DNS resolution failure decision tree](network-internal-dns-failure.md) — same-column sibling: another "only some endpoints fail" office failure
- [DNS troubleshooting (dig +trace)](dns-troubleshoot.md) — rule out the more basic "name won't even resolve" network problem
> The fault case in this page comes from a real office-network site, used as a credibility anchor for the judgment. Actual GPO and certificate operations depend on your domain environment.
---
## Internal DNS resolution failure decision tree — internet works but the intranet OA won't open
URL: https://ops.jiunotes.top/en/network/network-internal-dns-failure.md
摘要: A classic office-network failure — clients can reach the internet and chat apps, but the internal OA portal won't open. This page gives a troubleshooting decision tree: confirm whether it is name resolution or a dead server, then pinpoint with ipconfig /all, nslookup and ping, and finish with a one-click script to switch back to the internal DNS plus a DHCP Option 43 hardening checklist.
### Answer
When the internet works but the internal OA portal does not, nine times out of ten the client got the wrong DNS server (for example a public 114 or 8.8.8.8 instead of the company internal DNS), so the intranet domain cannot resolve. Ping the OA IP first: if the IP answers but the name does not, it is confirmed a DNS problem. Then check the DNS server handed out by DHCP in ipconfig /all; if it is not the internal one, switch it back and fix the DHCP Option 43 / GPO distribution so it cannot happen again.
### FAQ
Q: Why does the internet work but the internal OA does not?
A: The internal OA uses a company intranet domain (for example oa.corp.local) that only the internal DNS server knows how to resolve. A public DNS (114, 8.8.8.8) has no idea about that name. Once a client mistakenly picks up a public DNS, the internet keeps working while every intranet name fails — which looks exactly like "WeChat works, OA does not".
Q: Should I look at ipconfig /all or ipconfig /displaydns?
A: /all shows which DNS server the client currently received from DHCP — use it to judge whether the distribution is correct. /displaydns shows what the system has already cached — use it to rule out stale cache. Step one is /all to confirm the DNS server itself; step two is /flushdns to clear cache.
Q: Will the one-click fix script break a healthy network config?
A: The script only releases and renews the DHCP lease (ipconfig /release, /renew) and switches DNS back to the specified internal server. It does not delete drivers or touch the registry. But if your network does not rely on DHCP for DNS (static IP environments), the "renew" step can wipe the static config — in that case use GPO or manual assignment, and treat the script as emergency reference only.
Q: Why would DHCP hand out the wrong DNS?
A: Three common causes: 1) an uncontrolled DHCP server joined the network (e.g. a privately plugged-in router) answering first; 2) a misconfigured Option 43/51 on the scope pushing a public DNS as if it were internal; 3) the client previously connected to another network and kept the old DNS setting. The root cause is almost always on the DHCP side, not the client.
Q: How do I stop it from coming back?
A: Three layers: network layer — only one controlled DHCP server is allowed to answer, disable DHCP on rogue access routers; config layer — fix Option 43 to push the internal DNS, or enforce it via domain GPO; client layer — baseline-check static-IP machines. Patching the DNS is treating the symptom; preventing the wrong push is the cure.
### Full Content
# Internal DNS resolution failure decision tree — internet works but the intranet OA won't open
I have seen this more than once on enterprise office networks: a whole department reports "WeChat chats fine, web pages open, but the internal OA system won't open". The first reflex is usually "the OA server is down" or "the OA front end has a bug", and ops spends ages checking the server — only to find the server was never the problem. The client simply could not resolve the intranet name.
What makes this failure nasty is that it **looks like a server outage but the root cause sits in the client's DNS config**. The decision tree below handles the "internet works, intranet name does not" class, so you do not misdiagnose it from the start.
## 60-second check — is it DNS?
Do not touch the server yet. Self-test with one sentence:
> External sites (Baidu, web WeChat, GitHub) all open, but company intranet domains (oa.xxx.com, git.xxx.com) do not → **strongly suspect a wrong DNS push**.
If even the external internet fails, that is outside this page — check the gateway and physical link first.
## Troubleshooting decision tree
```
User reports: OA page won't open, but the internet works
│
├─ Confirm the scope
│ ├─ Only one person affected? → likely that machine's DNS cache/config (check the host)
│ └─ Multiple people at once? → likely DHCP pushed a wrong DNS (check DHCP/network)
│
├─ ping the OA IP address (use IP directly, bypass the name)
│ ├─ IP answers, name fails → confirmed DNS resolution problem (not a dead server) ★most common entry
│ └─ IP also fails → not DNS, check OA server / link (out of scope here)
│
├─ ipconfig /all, look at the "DNS Servers" line
│ ├─ Shows a public DNS (114.114.114.114 / 8.8.8.8)?
│ │ → client picked up external DNS, intranet name cannot resolve → switch back to internal DNS
│ └─ Shows the internal DNS indeed?
│ ├─ but nslookup oa.xxx.com still fails → internal DNS itself lacks the record / forwarder broken
│ └─ nslookup works → stale client cache, just flushdns
│
└─ Root-cause locating (multi-user scenario)
├─ Rogue small router hijacking DHCP? → disable it, keep one controlled DHCP
├─ Option 43 misconfig pushed public DNS? → fix the scope option
└─ Client kept old-network DNS? → release/renew / GPO hardening
```
The hinge of the whole tree is one line: **decide first whether the server is down or the name will not resolve, then choose whether to check the server or the DNS config**. That `ping IP` step at the front is the pivot — IP answering proves the server is alive and the problem collapses onto DNS.
## Three-step locating commands
Run them in this order and you can usually characterize the fault within five minutes.
### Step 1 — confirm it is stuck on the name only
```bat
ping oa.xxx.com :: ping by name, likely times out or fails to resolve
ping 10.20.30.40 :: replace with the real internal IP of the OA server; IP answers → DNS confirmed
```
Note: pinging by IP bypasses name resolution. IP answering while the name fails proves "the server is alive, the name just will not look up".
### Step 2 — see which DNS the client actually received
```bat
ipconfig /all
```
Find the "DNS Servers" line. It should show the company internal DNS (e.g. `10.20.30.10`). If it shows `114.114.114.114`, `8.8.8.8`, or a phone-hotspot DNS, the client wrongly took an external DNS.
### Step 3 — verify resolution on purpose
```bat
nslookup oa.xxx.com :: query with the system default DNS; failure means default DNS rejects intranet names
nslookup oa.xxx.com 10.20.30.10 :: query the internal DNS explicitly; works → proves internal DNS is fine, client just did not use it
ipconfig /displaydns :: see if oa.xxx.com is stuck on a wrong cached record
ipconfig /flushdns :: clear cache and retry, rule out "stale cache"
```
## One-click fix script (emergency, copy and run)
The PowerShell below is safest on clients that **receive DNS via DHCP**: release the old lease, renew (picking up the correct internal DNS), then clear the cache once.
```powershell
# Switch back to internal DNS (emergency script, run as administrator)
# Only for clients that auto-get DNS via DHCP; do NOT use directly on static-IP machines (see note)
Write-Host ">> Releasing current IP and DNS lease..." -ForegroundColor Cyan
ipconfig /release | Out-Null
Write-Host ">> Renewing address (with correct internal DNS)..." -ForegroundColor Cyan
ipconfig /renew | Out-Null
Write-Host ">> Flushing DNS cache..." -ForegroundColor Cyan
ipconfig /flushdns | Out-Null
# Verify result
$dns = (Get-DnsClientServerAddress -AddressFamily IPv4 | Where-Object { $_.ServerAddresses } | Select-Object -ExpandProperty ServerAddresses) -join ", "
Write-Host ">> Current DNS servers: $dns" -ForegroundColor Yellow
Write-Host ">> Try the internal OA again; if it still fails, check the DHCP Option 43 push." -ForegroundColor Green
```
**Honest note**: this script only does "release/renew DHCP + clear cache". It executes nothing on any HA/network device and does not simulate your network. It fixes the "client kept a wrong DNS" class; if the root cause is the DHCP push itself (multiple users hit at once), the script treats the symptom, not the cause — fix the DHCP side (next section).
On static-IP machines, do not run the `/release /renew` above — it wipes the static config. Use GPO or set the internal DNS manually in "network connection → IPv4 → DNS", then harden with `Set-DnsClientServerAddress`:
```powershell
# Static-IP client: set internal DNS directly (example, change to your real internal addresses)
Set-DnsClientServerAddress -InterfaceIndex (Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }).ifIndex `
-ServerAddresses ("10.20.30.10","10.20.30.11")
```
## Root cause — stop the wrong push from happening
Fixing one host is only a temporary patch. When multiple users hit at once, the cause is in DHCP or network structure. Close it off in three layers:
| Layer | Action | Prevents |
|---|---|---|
| Network | Allow only one controlled DHCP server; disable DHCP on privately plugged-in routers | rogue devices answering first and pushing external DNS |
| Config | Fix DHCP scope Option 43 to push internal DNS; enforce via domain GPO where available | Option misconfig pushing public DNS as internal |
| Client | Baseline-check DNS on static-IP machines, bake into the imaging template | single client keeping an old-network DNS |
One often-missed point: **DHCP Option 43 is not only for APs/phones**. Many shops write DNS into Option 43 as a convenience and accidentally put a public address there, so clients receive it wrong. Before editing Option 43, grab one healthy client's `ipconfig /all` and configure from its "correct line" — do not fill it from memory.
## Quick decision table (use it directly)
| Symptom | First reflex (misjudged) | Real root cause | Where to look |
|---|---|---|---|
| Internet works, OA won't open | OA server down | Client got wrong external DNS | Local ipconfig /all |
| One person only, others fine | OA front-end bug | Local DNS cache / leftover | flushdns + renew DHCP |
| Multiple at once | OA system broken | DHCP pushed wrong DNS | DHCP Option 43 / rogue router |
| IP answers, name fails | Network down | Name resolution failed | DNS server and forwarder |
| IP also fails | Must be DNS | Actually server / link | The OA server itself |
This table is the landing version of "what it is most easily misjudged as" — in the first five failures, **eight out of ten tickets open as "OA is broken"**, and checking against this table skips most of the wasted effort.
## FAQ
**Q: Why does the internet work but the internal OA does not?**
A: The internal OA uses a company intranet domain (e.g. `oa.corp.local`) that only the internal DNS server knows how to resolve. A public DNS (114, 8.8.8.8) has no idea about that name. Once a client mistakenly picks up a public DNS, the internet keeps working while every intranet name fails — which looks exactly like "WeChat works, OA does not".
**Q: Should I look at ipconfig /all or ipconfig /displaydns?**
A: `/all` shows which DNS server the client currently received from DHCP — use it to judge whether the distribution is correct. `/displaydns` shows what the system has already cached — use it to rule out stale cache. Step one is `/all` to confirm the DNS server itself; step two is `/flushdns` to clear cache.
**Q: Will the one-click fix script break a healthy network config?**
A: The script only releases and renews the DHCP lease and switches DNS back to the specified internal server. It does not delete drivers or touch the registry. But if your network does not rely on DHCP for DNS (static IP environments), the "renew" step can wipe the static config — in that case use GPO or manual assignment, and treat the script as emergency reference only.
**Q: Why would DHCP hand out the wrong DNS?**
A: Three common causes: 1) an uncontrolled DHCP server joined the network (e.g. a privately plugged-in router) answering first; 2) a misconfigured Option 43/51 on the scope pushing a public DNS as if it were internal; 3) the client previously connected to another network and kept the old DNS setting. The root cause is almost always on the DHCP side, not the client.
**Q: How do I stop it from coming back?**
A: Three layers: network layer — only one controlled DHCP server is allowed to answer, disable DHCP on rogue access routers; config layer — fix Option 43 to push the internal DNS, or enforce it via domain GPO; client layer — baseline-check static-IP machines. Patching the DNS is treating the symptom; preventing the wrong push is the cure.
## Further reading and references
- [Microsoft Learn — ipconfig command reference](https://learn.microsoft.com/windows-server/administration/windows-commands/ipconfig) — official parameter notes for `/all`, `/release`, `/renew`, `/flushdns`
- [Microsoft Learn — nslookup command reference](https://learn.microsoft.com/windows-server/administration/windows-commands/nslookup) — query with a specific DNS server, troubleshooting usage
- [Cloudflare — What is DNS](https://www.cloudflare.com/learning/dns/what-is-dns/) — the basics of recursive/iterative resolution and forwarders
- [Microsoft Learn — DHCP options (Option 43, etc.)](https://learn.microsoft.com/windows-server/networking/technologies/dhcp/dhcp-options) — how scope options are pushed and what happens when misconfigured
> This page is a troubleshooting decision asset. External links are authority references only; actual commands depend on your intranet addresses and scopes.
## Related guides and tools
- [DNS troubleshooting: dig +trace six-symptom decision tree](dns-troubleshoot.md) — the public-internet six symptoms and dig usage; this page is its "enterprise-intranet" companion
- [DNS resolution principles and recursive query](dns-resolution.md) — read this first if you want to understand recursion/iteration and why forwarders matter
- [dnsmasq configuration and internal resolution](dnsmasq-config.md) — reference when you run your own internal DNS
- [NTP time sync](ntp-time-sync.md) — another "multiple users at once" office failure; different mechanism, similar triage
> The fault case in this page comes from a real office-network site, used as a credibility anchor for the judgment. Actual commands depend on your intranet addresses and scopes.
---
## Multi-WAN policy route misconfiguration decision tree — WeChat sends images but Feishu cannot
URL: https://ops.jiunotes.top/en/network/network-multiwan-policy-route.md
摘要: A classic office-network failure — WeChat images go through fine, but Feishu cannot send images or files while text chat works. This page gives a troubleshooting decision tree: confirm it is a single-app, single-traffic-type egress problem, then pinpoint with tracert, nslookup and the policy-route table, and finish with multi-WAN egress hardening plus a "new SaaS network policy assessment SOP".
### Answer
When WeChat sends images but Feishu cannot send images (text still works), it is almost never DNS and almost never a Feishu outage. The cause is usually a misconfigured policy-based route (or static route) on the multi-WAN router that sends Feishu's media servers (CDN/OSS) out the wrong, dead or congested WAN, or creates asymmetric routing. Confirm the "only Feishu media fails" signature, then use tracert to see which WAN the media IP actually takes, compare it against the policy-route table, and fail over to the backup egress to recover. The cure is to tidy the multi-WAN route table and build an assessment SOP for every new SaaS.
### FAQ
Q: Why does WeChat work but Feishu cannot send images?
A: WeChat and Feishu media ride different vendors' CDN/object storage, so they use different IP ranges. Multi-WAN routing picks the egress by destination IP; if policy routing sends Feishu's media range out the broken or congested WAN, Feishu images/files stall while WeChat media (on the healthy WAN) works. Text chat rides a long-lived signaling connection on a different path, so text keeps working.
Q: tracert shows Feishu media IP taking the wrong egress — how do I confirm it is policy routing?
A: Log into the router and check show ip route plus the policy-based routing (PBR) table; find the rule matching Feishu's media IP range and verify its next-hop / WAN interface. Then temporarily move that traffic to the backup WAN (or delete the bad rule and use the default route); if Feishu recovers, it is confirmed. Also compare the "source interface / source address" condition — many policies are built per internal VLAN, and the miss often happens when a new VLAN was never added.
Q: It recovered after failing over to the backup egress — can I leave it?
A: Failing over is only a stopgap. If the backup WAN also fails later, the fault returns; and asymmetric routing (forward on A, return on B) can also break some CDNs' origin checks. Go back to the PBR table, pin Feishu (and peer SaaS) media ranges to the correct primary WAN, and write it into the assessment SOP so new apps stop hitting the same hole.
Q: Where do teams most often trip when adding a new SaaS (DingTalk / Tencent Meeting)?
A: Most often they whitelist the login domain but forget the media IP ranges. A SaaS login domain and its media CDN domain are usually different, and media IP ranges shift as the vendor schedules. The SOP must require pulling the vendor's published media/call-server IP ranges, pinning them to the primary WAN in policy routing, and naming an owner for "IP range changed → route updated".
Q: How do I tell this apart from a DNS resolution issue?
A: A DNS issue fails the whole domain (including login) and nslookup of the media domain returns wrong/timeout results. This class shows "domain resolves, login works, only media stalls at the egress". One-line test: nslookup of the Feishu media domain is fine, but tracert to its IP takes the wrong WAN — that is policy routing, not DNS.
### Full Content
# Multi-WAN policy route misconfiguration decision tree — WeChat sends images but Feishu cannot
I have seen a confusing office-network failure: staff say "Feishu cannot send images or files, but text chat is fine, and WeChat images work with no problem". The first reflex drifts toward "Feishu server is down" or "Feishu client bug", and some even go check DNS — yet the Feishu web client logs in and texts send; only rich media stalls.
The signature of this fault is **"single app, single traffic type"** — it distinguishes "everything is down" from "only one app's media stream was misrouted". The decision tree below handles the "some SaaS media won't flow under multi-WAN" class.
## 60-second check — is it an egress routing problem?
Self-test with one sentence:
> WeChat images fine, Feishu images/files fail but text works; or app A fine, app B media only stalls → **strongly suspect multi-WAN policy routing sent the media stream out the wrong egress**.
If every app and every traffic type stalls, that is one WAN fully down or a gateway problem — outside this page.
## Troubleshooting decision tree
```
User reports: Feishu logs in and texts, but images/files won't send (WeChat works)
│
├─ Confirm the scope
│ ├─ Only Feishu media stalls? Other SaaS fine? → single-app media problem (check PBR)
│ └─ Multiple SaaS media all stall? → likely primary WAN congested/down (check WAN status)
│
├─ Resolution layer (rule out DNS)
│ ├─ nslookup Feishu media domain returns IP?
│ │ → resolution fine, not DNS, go check egress
│ └─ nslookup times out / wrong? → go check DNS push (see internal DNS decision tree)
│
├─ tracert -d
│ ├─ First hop already took the "broken/congested WAN" gateway? → PBR misrouted this IP range ★most common
│ └─ Took the correct WAN but still drops? → that WAN link itself is bad (check link quality)
│
├─ Log into router, check policy-based route (PBR) table
│ ├─ Rule matching Feishu media range points to wrong next-hop? → fix rule to primary WAN
│ ├─ No such rule, but source-VLAN default landed it on backup WAN? → add explicit rule
│ └─ Rule exists but "source interface" missed the new VLAN? → include the new VLAN in policy
│
└─ Root-cause locating
├─ Fail over to backup/default egress and Feishu recovers? → confirmed misconfig, stopgap
└─ Still fails? → not routing, check that WAN link or Feishu side
```
The hinge of the whole tree is one line: **decide first whether it is DNS/server or egress path selection, then choose whether to check the domain or the route table**. That `tracert` step at the front is the pivot — it exposes directly which WAN the media IP actually took.
## Three-step locating commands
### Step 1 — confirm it is not DNS and grab the real media IP
```bat
nslookup :: resolution fine means not DNS; note one returned media IP
ping :: reachable means layer-3 is up; problem is "path choice" not "reachability"
```
Note: a SaaS media CDN domain is usually different from its login domain — query the "media/file" domain, not the login one.
### Step 2 — see which egress the media actually took
```bat
tracert -d :: the first-hop gateway address reveals which WAN it used
```
Compare the tracert first-hop gateway IP against each WAN interface's gateway on the router: if it landed on the WAN that "should never carry Feishu media", that is the PBR misconfiguration.
### Step 3 — log into the router and check policy routing and the route table
```bat
show ip route :: which route / next-hop matches the destination range
show route-map / show policy-map :: view PBR policy (syntax varies by vendor)
display policy-based-route :: common on Huawei-style gear
```
Key checks: does the rule matching Feishu media range point to the primary WAN interface; and does its "match condition" miss the affected internal VLAN/source range.
## Emergency stopgap — temporarily fail back to the correct egress
This is not a script — the fix must be done on the router/firewall, there is no terminal equivalent, so below is the checklist of what to look at and change, not pretend-remote execution:
```
1. Confirm Feishu media IP ranges (from official docs or nslookup, at least /24 granularity)
2. In policy routing, explicitly set this range to the primary WAN interface + correct next-hop
3. Before saving, test in session: tracert to that IP should immediately take the primary WAN
4. After Feishu images recover, harden the rule into config and back it up
```
**Honest note**: fixing multi-WAN policy routing must be done on the router/firewall device; the endpoint side has no equivalent script. The above is a checklist for troubleshooting and changing config, not copy-run code; commands differ greatly by vendor (Cisco/Juniper/Huawei/Fortinet), always follow your device documentation.
## Root cause — stop the misconfiguration from recurring
Failing one host back is only a stopgap. Every new SaaS on a multi-WAN network adds a set of media IP ranges to manage; close it off in three layers:
| Layer | Action | Prevents |
|---|---|---|
| Routing | Map and draw the multi-WAN route master table; pin core SaaS (Feishu/DingTalk/Meeting) media ranges to the primary WAN | media stream misrouted to dead/congested egress |
| Process | Build a "New SaaS network policy assessment SOP": before launch, pull official IP ranges, write into PBR, name an owner | new app misses config; IP range change not synced |
| Monitoring | Probe core WAN link quality (latency/loss/jitter); auto-alert or fail over when primary degrades | primary WAN silently degrades unnoticed |
One often-missed point: **a SaaS media IP range shifts as the vendor schedules**. DingTalk, Feishu and Tencent Meeting media CDNs all expand ranges dynamically; the SOP must state who tracks IP-range changes and how soon they sync to routing, or today's correct rule expires in three months.
## Quick decision table (use it directly)
| Symptom | First reflex (misjudged) | Real root cause | Where to look |
|---|---|---|---|
| WeChat images fine, Feishu images fail | Feishu server down / client bug | Feishu media IP range misrouted by PBR | tracert media IP + PBR table |
| Text works, images stall | DNS resolution error | asymmetric route / media egress dead | compare WAN gateways, check link quality |
| One VLAN all affected, others fine | Feishu throttling that dept | new VLAN missed in PBR | PBR source interface/address condition |
| Recovers on failover to backup | problem gone, ignore it | only stopgap, misconfig remains | harden primary-egress rule |
| nslookup media domain times out | Feishu media server down | actually wrong DNS push (see DNS tree) | endpoint ipconfig /all DNS |
This table is the landing version of "what it is most easily misjudged as" — eight out of ten tickets of this class open as "Feishu is broken", and checking against this table skips most wasted effort.
## FAQ
**Q: Why does WeChat work but Feishu cannot send images?**
A: WeChat and Feishu media ride different vendors' CDN/object storage, so they use different IP ranges. Multi-WAN routing picks the egress by destination IP; if policy routing sends Feishu's media range out the broken or congested WAN, Feishu images/files stall while WeChat media (on the healthy WAN) works. Text chat rides a long-lived signaling connection on a different path, so text keeps working.
**Q: tracert shows Feishu media IP taking the wrong egress — how do I confirm it is policy routing?**
A: Log into the router and check `show ip route` plus the policy-based routing (PBR) table; find the rule matching Feishu's media IP range and verify its next-hop / WAN interface. Then temporarily move that traffic to the backup WAN (or delete the bad rule and use the default route); if Feishu recovers, it is confirmed. Also compare the "source interface / source address" condition — many policies are built per internal VLAN, and the miss often happens when a new VLAN was never added.
**Q: It recovered after failing over to the backup egress — can I leave it?**
A: Failing over is only a stopgap. If the backup WAN also fails later, the fault returns; and asymmetric routing (forward on A, return on B) can also break some CDNs' origin checks. Go back to the PBR table, pin Feishu (and peer SaaS) media ranges to the correct primary WAN, and write it into the assessment SOP so new apps stop hitting the same hole.
**Q: Where do teams most often trip when adding a new SaaS (DingTalk / Tencent Meeting)?**
A: Most often they whitelist the login domain but forget the media IP ranges. A SaaS login domain and its media CDN domain are usually different, and media IP ranges shift as the vendor schedules. The SOP must require pulling the vendor's published media/call-server IP ranges, pinning them to the primary WAN in policy routing, and naming an owner for "IP range changed → route updated".
**Q: How do I tell this apart from a DNS resolution issue?**
A: A DNS issue fails the whole domain (including login) and nslookup of the media domain returns wrong/timeout results. This class shows "domain resolves, login works, only media stalls at the egress". One-line test: nslookup of the Feishu media domain is fine, but tracert to its IP takes the wrong WAN — that is policy routing, not DNS.
## Further reading and references
- [Microsoft Learn — tracert command reference](https://learn.microsoft.com/windows-server/administration/windows-commands/tracert) — `-d` skips name resolution and shows each hop IP, handy for comparing WAN gateways
- [Cloudflare — What is a CDN](https://www.cloudflare.com/learning/cdn/what-is-a-cdn/) — why SaaS media spreads across many edge IP ranges
- [Feishu Open Platform — network requirements and IP ranges](https://open.feishu.cn/) — vendor-published media/call-server addresses (authoritative source for the assessment SOP; follow the latest announcement)
- [Cisco — Policy-Based Routing configuration guide](https://www.cisco.com/c/en/us/td/docs/ios-xml/ios/iproute/configuration/xe-16/ir-xe-16-book/ir-pbr.html) — vendor-level PBR reference (commands vary by your model)
> This page is a troubleshooting decision asset. External links are authority references and official IP ranges only; routing commands differ greatly by vendor — follow your device documentation.
## Related guides and tools
- [SD-WAN deployment in practice](sd-wan-deploy.md) — selection and deployment for multi-WAN / multi-link scenarios; this page is its "office-network troubleshooting" companion
- [SD-WAN vs MPLS comparison](sd-wan-vs-mpls-comparison.md) — trade-offs of multiple egress links; why pin core SaaS to the primary WAN
- [Internal DNS resolution failure decision tree](network-internal-dns-failure.md) — same-column sibling: when nslookup of the media domain times out, check DNS push here first
- [iptables port forwarding](iptables-port-forwarding.md) — reference for the underlying egress and forwarding mechanics
> The fault case in this page comes from a real office-network site, used as a credibility anchor for the judgment. Actual IP ranges and commands depend on your intranet addresses and devices.
---
## Return-to-office network anomaly decision tree — on company Wi-Fi but can't reach the share drive
URL: https://ops.jiunotes.top/en/network/network-return-to-office-network-reset.md
摘要: A classic office-network failure — after a trip or working from home, staff connect to company Wi-Fi but cannot open the share drive or internal systems, and the first reflex is usually "VPN is down" or "the file server is dead". This page gives a troubleshooting decision tree — confirm it is "the NIC cached the old network's DNS / domain network misidentified", then pinpoint in three steps with ipconfig /displaydns, nslookup and the network-profile property, and finish with a one-click network-reset script and a return-to-office self-check SOP.
### Answer
After a trip or WFH, staff connect to company Wi-Fi but cannot open the share drive or internal systems — and it is usually not a VPN outage or a dead server. The endpoint still carries the "memory" of the old network: the NIC cached DNS records from a non-company network, or Windows tagged the connection as "metered / public" so domain discovery and file sharing never engaged. Confirm the "Wi-Fi works, internet works, only internal resources fail" signature, then use ipconfig /displaydns to see the cache, nslookup to test internal resolution, and check the network-profile property. The cure is a one-click network-reset script and a "return-to-office self-check SOP".
### FAQ
Q: Why could I reach the internet at home, but after connecting to company Wi-Fi I can't open the share drive?
A: Home and office are different networks. While at home, the endpoint's DNS cache held records from the home ISP/router, and the network profile may have been marked "public / metered". Back at the office those "old memories" were not cleared: the cached internal-domain records are stale, or the system's wrong network-type identification suppressed domain discovery, file sharing and GPO — so the share drive and internal systems fail while the internet keeps working.
Q: Is it normal that ipconfig /displaydns shows a pile of unfamiliar records?
A: Seeing domains from home broadband, phone hotspot or hotel Wi-Fi means the cache is dragging the old network's tail. The key is whether there is a "wrong/stale" record for your internal domain — if so, it is skewing internal resolution. Clear the cache (/flushdns) and retest the internal domain; it often recovers immediately.
Q: Why would "metered connection" block internal access?
A: Windows limits background sync, turns off network discovery and de-prioritizes some domain features on "metered" or "public" networks; file sharing and GPO push can be suppressed or not triggered. An employee manually enabled metered mode on the road to save data and forgot to turn it off, so the system keeps treating the company network as "save data", and internal resources fail.
Q: Will the one-click network-reset script wipe my working config?
A: The script only does three standard actions — clear DNS cache + reset Winsock catalog + release/renew IP. It deletes no files, touches no domain-join state, changes no account. It fixes "dirty state at the protocol-stack / cache layer". But if your internal address is static (not DHCP), after resetting Winsock you may need to re-specify it; confirm before running in that environment.
Q: How do we get fewer of these tickets?
A: Set a "Return-to-office self-check SOP": first thing back — clear DNS cache, confirm the network profile is "domain / private" not "metered / public", run the one-click reset if needed. Make these three steps employee self-service; most tickets vanish before anyone calls IT, and MTTR and ticket volume drop together.
### Full Content
# Return-to-office network anomaly decision tree — on company Wi-Fi but can't reach the share drive
There is a "break-on-return" failure in office networks: after a trip or WFH, the phone works, the internet opens, but once on company Wi-Fi the share drive won't open and internal systems are unreachable. IT's first reflex drifts toward "the company VPN is down" or "the file server is dead", checks the server side, finds the server fine, and realizes the endpoint itself still carries the "memory" of the old network.
The signature of this fault is **"Wi-Fi connected, internet works, only internal resources fail"**. The root is usually endpoint-side: DNS cache residue, domain-network misidentification. The decision tree below handles the "post-trip / post-WFH endpoint network anomaly" class.
## 60-second check — is the endpoint carrying old-network memory?
Self-test with one sentence:
> Back at the office on Wi-Fi, internet works but share drive/internal systems fail; and this machine just switched back from home/hotel/hotspot → **strongly suspect DNS cache residue or domain-network misidentification**.
If even the internet fails, that is the Wi-Fi itself or the gateway — outside this page.
## Troubleshooting decision tree
```
User reports: back on Wi-Fi, internet works, share drive/internal systems fail
│
├─ Confirm the scope
│ ├─ Only this machine? Others fine? → endpoint-side (cache / network type)
│ └─ Multiple machines? → check Wi-Fi / gateway / DHCP push
│
├─ ipconfig /displaydns (cache)
│ ├─ Home/hotspot/hotel domains lingering? → flushdns then retest
│ └─ No abnormal residue? → check network-profile property
│
├─ nslookup internal domain
│ ├─ Fails / returns stale IP? → cache or DNS not refreshed
│ └─ Resolves but access still fails? → not DNS, check discovery / share perms
│
├─ Check network-profile property
│ ├─ Tagged "metered / public"? → domain discovery / sharing limited ★common
│ └─ "Domain / private" but still bad? → check GPO / firewall profile
│
└─ Root-cause locating
├─ Cache dragging old-network tail? → clear cache + one-click reset
└─ Metered mode left on? → switch to "private/domain", re-trigger discovery
```
The hinge of the whole tree is one line: **first confirm "single endpoint's old memory or server-side problem", then see whether it is cache or network type**. That step "compare yourself vs others and read the cache" is the pivot — it pulls the fire from the server back to the endpoint.
## Three-step locating procedure
### Step 1 — see if the DNS cache drags an old-network tail
```bat
ipconfig /displaydns :: see if home/hotspot/hotel domains linger
ipconfig /flushdns :: clear cache, then retry internal resources
```
Note: during travel the endpoint resolved many non-company domains; those records stay in the local cache. Clear and retest internal — often recovers immediately.
### Step 2 — nslookup internal resolution
```bat
nslookup :: fails or returns stale IP -> cache/server not refreshed
nslookup :: query internal DNS explicitly; works -> internal DNS itself is fine
```
If explicit internal DNS works but default lookup fails, the problem is the endpoint's resolution path (cache or pushed DNS), not the internal DNS server.
### Step 3 — check the network-profile property
```
1. Settings -> Network & Internet -> Status -> click current connection "Properties"
2. See "Network profile type": should be "Domain" or "Private", not "Public"
3. See if "Metered connection" is on: turn it off if so
4. Wait a few seconds after turning off; domain discovery / file sharing should re-trigger
```
Windows limits background sync and turns off network discovery on "metered / public" networks. An employee enabled metered mode on the road to save data and forgot to turn it off — the most overlooked root cause.
## Emergency stopgap — network-reset script (copy and run)
The PowerShell below is safest on **ordinary office endpoints (DHCP)**: clear DNS cache, reset Winsock catalog, release/renew IP.
```powershell
# Return-to-office network reset (emergency script, run as administrator)
# Only: clear DNS cache + reset Winsock + release/renew IP; no files, no domain state, no account change
Write-Host ">> Flushing DNS cache..." -ForegroundColor Cyan
ipconfig /flushdns | Out-Null
Write-Host ">> Resetting Winsock catalog..." -ForegroundColor Cyan
netsh winsock reset | Out-Null
Write-Host ">> Releasing and renewing IP..." -ForegroundColor Cyan
ipconfig /release | Out-Null
ipconfig /renew | Out-Null
Write-Host ">> Disconnect and reconnect company Wi-Fi, then retry the share drive / internal systems." -ForegroundColor Green
```
**Honest note**: the script only handles "dirty state at the protocol-stack / cache layer"; it executes nothing on any device and does not simulate your network. On static-IP machines, /release /renew may clear the static config — in that environment specify manually first, or use only the first two steps (flushdns + winsock reset).
## Root cause — make "break-on-return" rarer
Recovering one machine is only a stopgap. Travel is normal; manual fixes never catch up. Close it off in three layers:
| Layer | Action | Prevents |
|---|---|---|
| Endpoint | Put the one-click network-reset script in an employee self-service entry (or trigger via login script) | access anomalies from cache / protocol-stack dirty state |
| Norm | "Return-to-office self-check SOP": clear cache -> confirm profile not metered/public -> run reset if needed | employees showing up with old-network memory |
| Identity | Domain policy forces "in-domain connection" to be identified as private; metered mode only allowed on explicit travel | system mislimits domain features due to network-type misread |
One often-missed point: **"metered" does more than save data**. It also turns off network discovery and de-prioritizes GPO push; file sharing and internal-system access are directly affected. Many return failures root in a switch flipped months ago on a trip and never turned off.
## Quick decision table (use it directly)
| Symptom | First reflex (misjudged) | Real root cause | Where to look |
|---|---|---|---|
| Back on Wi-Fi, share drive fails | VPN down | endpoint DNS cache old-network tail | ipconfig /displaydns |
| Internet works, internal fails | file server dead | domain network seen as metered/public | network-profile property |
| Fine right after cache flush | server glitch | cache was the cause, confirmed | no server check needed |
| Only this machine | account permission | single endpoint stale state | compare self vs others |
| Appears only after WFH->office | company network changed | travel residue, not network change | return-to-office SOP |
This table is the landing version of "what it is most easily misjudged as" — eight out of ten tickets of this class open as "VPN down again" or "share drive broken", and checking against this table skips most wasted effort.
## FAQ
**Q: Why could I reach the internet at home, but after connecting to company Wi-Fi I can't open the share drive?**
A: Home and office are different networks. While at home, the endpoint's DNS cache held records from the home ISP/router, and the network profile may have been marked "public / metered". Back at the office those "old memories" were not cleared: the cached internal-domain records are stale, or the system's wrong network-type identification suppressed domain discovery, file sharing and GPO — so the share drive and internal systems fail while the internet keeps working.
**Q: Is it normal that ipconfig /displaydns shows a pile of unfamiliar records?**
A: Seeing domains from home broadband, phone hotspot or hotel Wi-Fi means the cache is dragging the old network's tail. The key is whether there is a "wrong/stale" record for your internal domain — if so, it is skewing internal resolution. Clear the cache and retest the internal domain; it often recovers immediately.
**Q: Why would "metered connection" block internal access?**
A: Windows limits background sync, turns off network discovery and de-prioritizes some domain features on "metered" or "public" networks; file sharing and GPO push can be suppressed or not triggered. An employee manually enabled metered mode on the road to save data and forgot to turn it off, so the system keeps treating the company network as "save data", and internal resources fail.
**Q: Will the one-click network-reset script wipe my working config?**
A: The script only does three standard actions — clear DNS cache + reset Winsock catalog + release/renew IP. It deletes no files, touches no domain-join state, changes no account. It fixes "dirty state at the protocol-stack / cache layer". But if your internal address is static (not DHCP), after resetting Winsock you may need to re-specify it; confirm before running in that environment.
**Q: How do we get fewer of these tickets?**
A: Set a "Return-to-office self-check SOP": first thing back — clear DNS cache, confirm the network profile is "domain / private" not "metered / public", run the one-click reset if needed. Make these three steps employee self-service; most tickets vanish before anyone calls IT, and MTTR and ticket volume drop together.
## Further reading and references
- [Microsoft Learn — ipconfig command reference](https://learn.microsoft.com/windows-server/administration/windows-commands/ipconfig) — official notes for `/displaydns`, `/flushdns`, `/release`, `/renew`
- [Microsoft Learn — netsh winsock reset](https://learn.microsoft.com/windows-server/networking/technologies/network-subsystem/net-sub-net-tcpip-troubleshoot) — when Winsock catalog reset applies and caveats
- [Microsoft Learn — network profiles (private/public/domain)](https://learn.microsoft.com/windows-server/networking/core-network-guide/) — why "metered / public" limits discovery and sharing (follow your environment docs)
> This page is a troubleshooting decision asset. External links are authority references only; actual commands depend on your intranet environment.
## Related guides and tools
- [Internal DNS resolution failure decision tree](network-internal-dns-failure.md) — same-column sibling: when the internal domain resolution itself fails
- [DNS troubleshooting (dig +trace)](dns-troubleshoot.md) — the six public-DNS symptoms and dig usage
- [DNS resolution principles and recursive query](dns-resolution.md) — understand cache and forwarders
- [NTP time sync](ntp-time-sync.md) — another "only some endpoints fail" office failure (time dimension)
> The fault case in this page comes from a real office-network site, used as a credibility anchor for the judgment. Actual commands depend on your intranet environment.
---
## Nginx 504 Gateway Timeout: Six Root-Cause Branches in a Decision Tree
URL: https://ops.jiunotes.top/en/network/nginx-504-troubleshoot.md
摘要: A working engineer's 504 troubleshooting guide: what 504 really means, the five protocol-level differences from 502, a six-branch root-cause decision tree (timeout config, backend CPU, connection pool, SSL handshake, DNS latency, slow query), a fix template, and a 30-command quick-scan list.
### Answer
A 504 is a read timeout, not a connection failure — the upstream never returned a single byte before proxy_read_timeout expired. The six root causes follow the request path in order: DNS resolution, TCP connect plus SSL handshake, connection-pool acquisition, backend CPU saturation, slow query or slow I/O, and finally a misconfigured proxy_read_timeout. Each maps to a distinct error.log keyword and a distinct access-log upstream_response_time signature.
### FAQ
Q: What is the actual difference between 504 and 502?
A: 502 means nginx established the connection and received bytes, but the bytes were invalid (bad status line, bad header, mid-stream RST). 504 means nginx sent the request and then received nothing before proxy_read_timeout. In the access log, 504 shows an upstream_response_time that equals proxy_read_timeout exactly (e.g. 60.000); 502 shows a small random value like 0.034.
Q: How large should proxy_read_timeout be?
A: Do not guess. Measure the real P99 response time from the access log (excluding 504 rows, which are timeout artifacts), then set proxy_read_timeout to 2-3x P99. Ten seconds is a common default, but a P99 of 8s wants ~20s, not 300s. Bumping 60s to 300s just turns 504s into slow responses — the user waits the same, the dashboard just looks cleaner.
Q: What does 'upstream timed out' in the error log actually mean?
A: It is a read timeout, not a connect timeout. nginx already connected, already sent the request, and is waiting for the response header. Two causes dominate: the backend is genuinely slow (90%), or the network path drops enough packets that TCP acknowledgements never arrive (10%, common on cross-region links). tcpdump on both ends tells you which.
Q: Do I need to restart nginx after changing proxy_read_timeout?
A: No. `nginx -s reload` (or `systemctl reload nginx`) is graceful: the master spawns new workers with the new config, old workers finish in-flight requests and exit, zero interruption. Just run `nginx -t` first — if the config has a syntax error, reload fails and the old workers keep serving.
Q: My backend is Node.js and 504s keep coming — what should I do?
A: Node's single-threaded event loop blocks on CPU-heavy work (large JSON serialization, regex backtracking) and long GC pauses. That blocks the keep-alive heartbeat and nginx sees a timeout. Check event-loop lag with clinic.js, cap the heap with --max-old-space-size, and run PM2 in cluster mode (-i max) to use all cores.
### Full Content
# Nginx 504 Gateway Timeout: Six Root-Cause Branches in a Decision Tree
504 Gateway Timeout is defined in [RFC](https://www.rfc-editor.org/) 7231 §6.6.5, but the definition misses the most useful fact: **[nginx](https://nginx.org/en/docs/) is rarely the problem.** It is a messenger. It sent your request upstream, waited for a response, and the upstream never delivered a single byte before `proxy_read_timeout` expired. That single fact — connection up, request sent, zero bytes back — is the whole diagnosis. This article walks the six root causes in the order they occur on the request path.
## What a 504 Actually Is
nginx worker writes the request into the upstream socket and enters a read loop. Every event-loop cycle it checks whether it has exceeded `proxy_read_timeout`. When it has, it closes the upstream connection, returns 504 to the client, and logs:
```
upstream timed out (110: Connection timed out) while reading response header from upstream
```
The "timed out" phrase trips everyone up. It is a **read** timeout, not a **connect** timeout. A connect timeout is a 502 with `connect() failed`. The two are different error codes in nginx source: `NGX_HTTP_BAD_GATEWAY` for 502, `NGX_HTTP_GATEWAY_TIME_OUT` for 504.
## 504 vs 502: The Five Protocol-Level Differences
| Dimension | 502 Bad Gateway | 504 Gateway Timeout |
|---|---|---|
| **Timeline** | Bytes arrived but were invalid (bad status line, bad header, mid-stream RST) | Request sent, no bytes in the read window |
| **Connection** | RST/FIN received, or a TCP-layer error | Still alive, or nginx closed it after timeout |
| **error.log keyword** | `upstream prematurely closed connection`, `upstream sent invalid header` | `upstream timed out (110: Connection timed out) while reading response header` |
| **access.log** | `upstream_response_time` small (<1s), `$status` 502 | `upstream_response_time` equals `proxy_read_timeout` exactly, `$status` 504 |
| **Typical cause** | Backend crashed, wrong protocol, bad SSL, dead keepalive | Backend slow, CPU saturated, pool exhausted, slow DNS, SSL handshake stuck |
There is a hidden difference in retry behavior that matters for your API timeout budget. `proxy_next_upstream error timeout` retries the request on the next upstream, but a 504 retry has to wait a full `proxy_read_timeout` before switching. With `proxy_next_upstream_tries 2`, a user's perceived wait is `2 × proxy_read_timeout`. If the client front-end times out at 30s but nginx has a 20s read timeout with tries=2, the client gives up at 30s and you see a 499 — not the 504 you would actually want to diagnose. **The sum of all nginx timeouts must be less than the client timeout.**
## The Six Root Causes, In Request Order
These are not parallel branches — they happen in sequence along the path, so you debug in this order:
```
nginx worker receives request
▼
[Root cause 5] DNS resolution slow resolver stuck, upstream DNS slow
▼
TCP connect + [Root cause 4] SSL handshake TLS slow, cert chain, SNI
▼
Acquire connection from upstream pool
[Root cause 3] Pool exhausted, no free connection
▼
Send request header
▼
[Root cause 2] Backend CPU saturated / event loop blocked
[Root cause 6] Backend slow query / slow I/O DB, ES, disk
▼
Wait for upstream_response
[Root cause 1] proxy_read_timeout too short
▼
Return 504 to client
```
In my experience the rough distribution is: root cause 1 (misconfigured timeout) ~40%, root cause 2 (backend CPU) ~25%, root cause 6 (slow query) ~20%, root cause 3 (connection pool) ~8%, root cause 4 (SSL handshake) ~5%, root cause 5 (DNS) ~2%. Your environment differs, but the priority order holds.
## Root Cause 1: proxy_read_timeout Misconfigured
This is the most common and the most misdiagnosed. Seeing 504, people crank `proxy_read_timeout` to 300s, the 504s "disappear," and they declare victory. You did not fix anything — you turned a 504 into a P99 of 99 seconds. The user waits the same; only the error-rate dashboard looks better.
```nginx
# WRONG 1: only bumped read_timeout, forgot send_timeout
location /api/ {
proxy_pass http://backend;
proxy_read_timeout 300s;
# proxy_send_timeout still 60s — large body requests still get cut
}
# WRONG 2: treated timeout as a connect timeout
location / {
proxy_pass http://backend;
proxy_read_timeout 5s; # backend legitimately needs 8s — permanent 504
}
# RIGHT: set from the real P99
server {
listen 443 ssl;
server_name api.example.com;
proxy_connect_timeout 5s;
proxy_read_timeout 20s; # P99 x 2.5, not 300s
proxy_send_timeout 10s;
proxy_next_upstream error timeout http_502 http_504;
proxy_next_upstream_tries 2;
location / { proxy_pass http://backend; }
}
```
The correct diagnostic sequence:
```bash
# 1. Find every effective timeout (nginx -T expands includes)
nginx -T 2>/dev/null | grep -E 'proxy_(read|send|connect|next_upstream)_timeout'
# 2. Look at the real response-time distribution
awk '$9==504 {print $NF}' /var/log/nginx/access.log | sort -n | uniq -c | tail
# all exactly 60.000 => pinned by read_timeout
# 3. Derive a sane timeout from P99 (excluding 504 rows)
tail -100000 /var/log/nginx/access.log | awk '$9!=504 {print $NF}' \
| sort -n | awk 'BEGIN{c=0} {a[c++]=$1} END{print a[int(c*0.99)]}'
```
The anti-pattern that taught me this: a customer bumped timeout 60s→300s, 504s vanished, and the report said "fixed." A week later P99 had climbed from 3s to 45s and users were complaining the page spun forever. The real cause was a missing index behind a slow SQL. **Enlarging a timeout is a painkiller, not a cure.** Watch the P99 curve after any timeout change.
## Root Cause 2: Backend CPU Saturated
The process is alive, the port accepts, TCP handshake succeeds — but requests go in and nothing comes out. That is the classic CPU-saturated signature. I saw it on a Java service: `jstack` showed everything `RUNNABLE` in JSON serialization, `top` showed one core at 100% and the rest at 30%.
```bash
# 1. Per-thread CPU
top -p -H
pidstat -u -p 1 5
# 2. System-wide CPU per core
mpstat -P ALL 1 3
# %usr high => app computing; %sys high => syscalls (I/O or net); %wa high => root cause 6
# 3. Hotspot profiling
perf top -p
perf record -g -p -- sleep 30 && perf report --stdio | head -50
# 4. Node.js event-loop lag
clinic doctor -- node app.js
# 5. Java thread dump
jstack | grep -A 5 "RUNNABLE" | head -50
```
Fixes by backend: Node.js → PM2 cluster `-i 0`, push CPU-heavy work to worker_threads, cap with `server.requestTimeout`. Java → check GC with `jstat -gc`, check thread pools, consider Jackson streaming over Gson. Go → do not leave `GOMAXPROCS=1` (containers with a CPU limit default to 1), profile with pprof. PHP-FPM → check `pm.max_children` and `max_execution_time`.
## Root Cause 3: Upstream Connection Pool Exhausted
Overlaps with the keepalive article, but in the 504 context it presents differently: a depleted pool makes nginx wait too long for a free connection and it trips `proxy_read_timeout` — a 504, not a 502.
```bash
# 1. ESTAB count vs worker_processes x keepalive
ss -tanp | grep :8080 | awk '{print $1}' | sort | uniq -c
# ESTAB >> workers x keepalive => pool full
# 2. TIME_WAIT pileup (short-connection symptom)
ss -tan | grep TIME-WAIT | awk '{print $4}' | cut -d: -f2 | sort | uniq -c | sort -rn | head
# 3. Listen backlog
ss -ltn | grep :8080
# Recv-Q near Send-Q => backlog nearly full, new connections dropped
# 4. File descriptor usage
ls /proc//fd | wc -l
cat /proc//limits | grep 'open files'
```
## Root Cause 4: Upstream SSL Handshake Timeout
When the upstream is HTTPS, TLS handshake counts against `proxy_read_timeout`. TLS 1.2 is 2-RTT, TLS 1.3 is 1-RTT; across regions a single handshake can eat 300ms, and with OCSP stapling plus certificate-chain verification, 2-3s is not unusual.
```bash
# 1. Measure handshake time
openssl s_client -connect 10.1.2.3:8443 -servername api.example.com -brief \
-cipher 'TLSv1.3' < /dev/null 2>&1 | grep -i "handshake\|verified"
# 2. TLS version timing difference
for v in tls1 tls1_1 tls1_2 tls1_3; do
echo -n "$v: "; time openssl s_client -connect 10.1.2.3:8443 -$v < /dev/null > /dev/null 2>&1
done
# 3. Cert chain length (longer chain => slower verification)
openssl s_client -connect 10.1.2.3:8443 -showcerts 2>/dev/null | grep -c "BEGIN CERTIFICATE"
```
The nginx-side fix is to enable SNI and session reuse:
```nginx
location /api/ {
proxy_pass https://backend;
proxy_ssl_server_name on;
proxy_ssl_name api.example.com;
proxy_ssl_protocols TLSv1.2 TLSv1.3;
proxy_ssl_session_reuse on;
}
```
## Root Cause 5: Slow DNS Resolution
This one is rare but the fastest to diagnose. The symptom: 504s only on **new** upstream connections (cold start, pool flush), lasting 3-10 seconds. If `proxy_pass http://backend.example.com` uses a hostname, nginx resolves it via system DNS. A slow or unreachable resolver poisons every new connection.
```bash
# 1. Measure system DNS latency
time nslookup backend.example.com
time getent hosts backend.example.com
# 2. Does nginx have its own resolver?
nginx -T 2>/dev/null | grep -E '^resolver'
# 3. resolv.conf options
cat /etc/resolv.conf
# options timeout:2 attempts:5 => up to 10s per resolution
# 4. [systemd](https://www.freedesktop.org/software/systemd/man/latest/)-resolved diagnostics
resolvectl query backend.example.com
journalctl -u systemd-resolved | tail -30
```
The fix is to give nginx its own resolver and force dynamic resolution with a variable:
```nginx
http {
resolver 127.0.0.53:53 valid=10s ipv6=off;
resolver_timeout 2s;
server {
location / {
set $backend backend.example.com;
proxy_pass http://$backend; # variable form => dynamic resolve
}
}
}
```
The variable form is the key. A static `proxy_pass http://backend.example.com` resolves once at startup and never again. The `set $backend ...; proxy_pass http://$backend;` form re-resolves each time using nginx's own resolver.
## Root Cause 6: Slow Query or Slow I/O
The sibling of root cause 2: CPU is low but the response is slow because it is stuck on I/O — a slow database query, a slow ES aggregation, a slow disk fsync, NFS jitter.
```bash
# 1. I/O pressure
iostat -x 1 5
# %util near 100, await > 50ms => disk saturated; aqu-sz > 1 => queuing
# 2. Who is waiting on I/O
pidstat -d 1 5
iotop -a
# 3. MySQL slow queries
mysql -e "SHOW FULL PROCESSLIST;" | awk '$6 > 10 {print}'
pt-query-digest /var/log/mysql/slow.log
# 4. [PostgreSQL](https://www.postgresql.org/docs/)
psql -c "SELECT now()-xact_start AS duration, query
FROM pg_stat_activity WHERE state='active' ORDER BY duration DESC;"
# 5. ES slow tasks
curl -s 'localhost:9200/_cat/tasks?v&h=action,running_time,state' | awk '$3 > "01:00:00"'
```
## The 30-Command Quick Scan
A single ordered list you can paste when a 504 alarm fires:
```bash
# ===== 1-5: scope the problem =====
1) awk '$9==504' /var/log/nginx/access.log | tail -20
2) awk '$9==504 {print $NF}' /var/log/nginx/access.log | sort -n | uniq -c | tail
3) tail -50 /var/log/nginx/error.log | grep -i "504\|timed out"
4) grep " 504 " /var/log/nginx/access.log | awk '{print $4}' | sort | uniq -c | sort -rn | head
# ===== 6-10: root cause 1, timeout config =====
5) nginx -T 2>/dev/null | grep -E 'proxy_(read|send|connect|next_upstream)_timeout'
6) tail -100000 /var/log/nginx/access.log | awk '$9!=504 {print $NF}' | sort -n | awk '{a[NR]=$1} END{print "P50:",a[int(NR*0.5)],"P99:",a[int(NR*0.99)]}'
7) nginx -t 2>&1 | tail -5
8) grep -E "upstream timed out" /var/log/nginx/error.log | wc -l
# ===== 11-15: root cause 2, CPU =====
9) top -bn1 | head -20
10) mpstat -P ALL 1 3
11) pidstat -u 1 3 | tail -20
12) perf top -p $(pgrep -f 'your_app' | head -1)
13) ps -eo pid,ppid,user,%cpu,%mem,cmd --sort=-%cpu | head -10
# ===== 16-20: root cause 3, connection pool =====
14) ss -tanp | grep ESTAB | awk '{print $4}' | rev | cut -d: -f2- | rev | sort | uniq -c | sort -rn | head
15) ss -tan | grep TIME-WAIT | wc -l
16) ss -ltn | grep -E ':(80|443|8080|8443)\b'
17) cat /proc/$(pgrep -f "nginx: worker" | head -1)/limits | grep "open files"
18) ls /proc/$(pgrep -f "nginx: worker" | head -1)/fd | wc -l
# ===== 21-24: root cause 4, SSL handshake =====
19) openssl s_client -connect 10.1.2.3:8443 -servername api.example.com -brief < /dev/null 2>&1 | grep -iE "handshake|verified"
20) time openssl s_client -connect 10.1.2.3:8443 -tls1_3 < /dev/null > /dev/null 2>&1
21) grep -i "ssl_do_handshake\|SSL_do_handshake" /var/log/nginx/error.log | tail -5
# ===== 25-27: root cause 5, DNS =====
22) time getent hosts backend.example.com
23) resolvectl query backend.example.com
24) nginx -T 2>/dev/null | grep -E '^(\s*)resolver'
# ===== 28-30: root cause 6, I/O & slow query =====
25) iostat -x 1 3
26) iotop -bn1 2>/dev/null | head -15
27) mysql -uroot -e "SHOW FULL PROCESSLIST;" 2>/dev/null | awk '$6 > 10 {print $1,$6,$10}' | head
```
## Summary
A 504 is a read timeout, and it lives on the request path, not in nginx. Debug in order: DNS, TCP plus SSL handshake, connection pool, backend CPU, slow query, then timeout config. The access log's `upstream_response_time` is your best discriminator — if it equals `proxy_read_timeout` to the millisecond, you are pinned by a timeout, not a dead backend. And remember: bumping the timeout is a painkiller. Measure the P99, set the timeout to 2-3x that, and keep watching the curve. That is the difference between making the dashboard look better and actually making the service better.
> **Original note**: This article is an independent English original written from first-hand production experience. It is not a translation of any Chinese source.
## Related Articles
- [Nginx Upstream Keepalive: Deep Tuning and Five Real 502 Cases](nginx-keepalive-502.md)
- [Nginx Reverse Proxy 502/504 Troubleshooting](nginx-proxy.md)
- [Nginx Upstream Config Quick Reference](nginx-upstream-config.md)
- [Rolling Out ModSecurity 3.0 WAF on Produ…](nginx-waf-modsecurity.md)
---
## Nginx Upstream Keepalive: The Default of 8, the Backend Differences, and Five Real 502 Cases
URL: https://ops.jiunotes.top/en/network/nginx-keepalive-502.md
摘要: A working engineer's guide to nginx upstream keepalive: the three parameters (keepalive, keepalive_timeout, keepalive_requests), the trap of the default value 8, how Node/Go/Java/PHP backends differ, the three-command hit-rate check, five real 502 cases, and a complete production config template.
### Answer
nginx upstream keepalive defaults to 8, which is almost always too small. Three parameters govern the backend connection pool: keepalive is the pool size per worker, keepalive_timeout is how long an idle connection survives, and keepalive_requests is the reuse cap. They must be coordinated, and they must all be smaller than the backend's own keepalive settings. Getting any one wrong produces 502s or a connection explosion. The three-command hit-rate check tells you whether the pool is actually being used.
### FAQ
Q: What is the default value of nginx upstream keepalive, and why is it so small?
A: keepalive defaults to 8, keepalive_timeout to 60 seconds, keepalive_requests to 1000. It is small because upstream keepalive was added in nginx 0.8.17 and the author was conservative about backend resource usage. High-concurrency production (>500 QPS) generally wants 32 or 64, tuned alongside the backend max_connections and ulimit -n.
Q: What is the difference between keepalive_timeout and the keepalive inside the upstream block?
A: keepalive_timeout is how long a backend TCP connection sits idle before nginx closes it — it controls connection lifetime. upstream keepalive N is the maximum number of idle connections nginx will cache per worker — it controls pool capacity. They are two orthogonal dimensions and both need tuning.
Q: Why does keepalive still open a new connection every time after I configured it?
A: The location block is missing one of the three-piece set: proxy_http_version 1.1 and proxy_set_header Connection ''. Without proxy_http_version 1.1, nginx uses HTTP/1.0 to the backend, which does not support keepalive. Without clearing the Connection header, the client's Connection: close propagates to the backend and forces it closed. The pool never gets hit.
Q: Is bigger always better for upstream keepalive?
A: No. A huge pool means nginx holds many idle TCP connections, which can exceed the backend's max_connections or exhaust file descriptors. My heuristic is keepalive = backend max_connections / worker_processes / 2. Beyond 128 it is diminishing returns and can cause accept queuing from fd pressure.
Q: How do I confirm keepalive is actually being hit?
A: Three commands. (1) watch the ESTAB count — stable means reuse, growing means new connections. (2) curl -w '%{num_connects}' repeatedly — should stay at 1 if the pool is reused. (3) tcpdump for FIN frequency — a FIN per request means no reuse.
### Full Content
# Nginx Upstream Keepalive: The Default of 8, the Backend Differences, and Five Real 502 Cases
The default `keepalive 8` in an [nginx](https://nginx.org/en/docs/) upstream block looks innocent. It is not. I spent a frustrating week chasing a cascade of 502s on an e-commerce customer, and the root cause was that tiny number interacting with a php-fpm restart. This article is what I learned: the three parameters, how they interact with different backends, and the five real cases that made me stop trusting defaults.
## Where the 502 Started: One PHP-FPM Restart
The customer's config looked perfect. `nginx -T` showed `keepalive 32`, `proxy_http_version 1.1`, and `proxy_set_header Connection ""` — the full three-piece set. But five minutes earlier, a php-fpm node had been OOM-restarted. At that moment, four ESTAB connections in nginx's upstream pool still pointed at the dead node. The kernel had not sent RST yet, so nginx had no idea the backend was gone. A user request pulled a dead connection from the pool, sent a request into it, and got a 502:
```
connect() failed (104: Connection reset by peer) while connecting to upstream
```
I stared at `ss -tanp | grep :9000 | grep ESTAB` for two minutes before it clicked: those four connections were dead but looked alive. **This is the trap of keepalive tuning — nginx health checks only verify that a connection can be established, not that the next request will succeed.** Dead connections sit in the pool, and whoever draws one loses. This is why the three parameters have to be understood together.
## The Three Parameters
First, find every keepalive setting you have so you know which one you are changing:
```bash
nginx -T | grep -i keepalive
grep -n "keepalive" /etc/nginx/conf.d/*.conf /etc/nginx/nginx.conf
```
`keepalive N` in the upstream block is the number of idle connections **per worker** that nginx caches. It is not global — with `worker_processes 4` and `keepalive 32`, the real pool is up to 128 idle connections.
`keepalive_timeout` in http/server/location is how long an idle connection survives before nginx closes it — for both client and backend connections. Default 60s in the upstream scenario.
`keepalive_requests N` is the reuse cap per connection. After N reuses, the connection is closed and rebuilt. Default 1000.
| Parameter | Location | Default | Unit | Meaning |
|---|---|---|---|---|
| `keepalive` | upstream | 8 | connections | per-worker idle pool size |
| `keepalive_timeout` | http/server/location | 60 | seconds | idle lifetime before close |
| `keepalive_requests` | http/server/location | 1000 | requests | reuse cap per connection |
## The Backend Differences You Must Respect
Backends are not passive — they close connections on their own. If nginx's `keepalive_timeout` is longer than the backend's, the pool fills with connections the backend already killed.
| Backend | Default keepalive timeout | Key setting | Production value |
|---|---|---|---|
| Node.js (Express/Koa) | 5s | `server.keepAliveTimeout` | ≥ 65s |
| Go net/http | 90s | `ReadTimeout` / `IdleTimeout` | ≥ 100s |
| Java Tomcat | 20s | `keepAliveTimeout` | ≥ 60s |
| PHP-FPM | 20s | `request_terminate_timeout` | ≥ 60s |
**The iron rule: nginx's keepalive_timeout must be strictly shorter than the backend's, with a 5-15s buffer.** That way nginx closes the idle connection first, and the backend never closes a connection nginx still thinks is alive. Node.js is the most dangerous case — its 5s default vs nginx's 60s is a mismatch waiting to bite.
## Why the Default of 8 Is a Trap
Do the math. Suppose 1000 QPS, 50ms average response, 4 workers.
- Each worker handles 250 req/s, so steady-state concurrency ≈ 250 × 0.05 = **12.5 active connections**
- With a peak buffer, call it 24 active
- A pool of 8 means 24 - 8 = **16 connections per second are new**
At 1000 QPS that is 16 fresh TCP connections per second — three-way handshakes, accept-queue churn, fd allocation and release. On the CPU profile you see `tcp_connect`, `accept`, and `socket_create` dominating.
The measurements I took on a single API endpoint:
| keepalive | QPS | P99 | nginx worker CPU |
|---|---|---|---|
| 8 | 8,500 | 32ms | 42% |
| 32 | 15,200 | 18ms | 28% |
| 64 | 17,800 | 16ms | 31% |
| 128 | 17,400 | 17ms | 35% |
8 → 32 nearly doubled QPS. 32 → 64 still gains but diminishing. 64 → 128 actually **drops** — past half of `worker_connections`, nginx's own fd pool gets tight. So: start at 32, move to 64 under pressure, and never blindly go to 256.
## The Three-Command Hit-Rate Check
Configuration is not enforcement. Verify the pool is actually being used:
```bash
# 1. ESTAB count: stable = reuse, growing = new connections
watch -n1 'ss -tanp | grep :8080 | grep ESTAB | wc -l'
# 2. curl num_connects: should stay at 1 across repeated calls
for i in 1 2 3 4 5; do
curl -s -o /dev/null -w "connects=%{num_connects}\n" http://127.0.0.1/health
done
# 3. tcpdump FIN frequency: a FIN per request = no reuse
tcpdump -i lo -A 'tcp port 8080 and (tcp[tcpflags] & tcp-fin != 0)'
```
If `num_connects` changes every time and FINs are dense, the pool is not being hit. Check in order: `proxy_http_version 1.1` → `proxy_set_header Connection ""` → `keepalive N` in the upstream → nginx version (must be 1.1.5+ for upstream keepalive).
## Five Real 502 Cases
### Case 1: Pool × workers exceeds the backend limit
PHP-FPM with `pm.max_children=5`, nginx with `worker_processes=4` and `keepalive=32`. That is a potential 4 × 32 = 128 connections against a backend that can only serve 5. Symptom: `pm.max_children reached` alarm, nginx logs `upstream timed out`.
**Fix**: `keepalive = pm.max_children × 2 = 10`, or raise `pm.max_children`.
### Case 2: Node.js closes at 5s, nginx uses it for 60s
Node.js default `keepAliveTimeout=5s`, nginx default `keepalive_timeout=60s`. From the 6th second, the pool holds connections the backend already closed. Symptom: fine at low concurrency, 5-15% 502 rate under bursts.
**Fix**: Node.js `server.keepAliveTimeout = 65000`, or nginx `keepalive_timeout 5` (aggressive but effective).
### Case 3: Dead connections after a rolling restart
In [Kubernetes](https://kubernetes.io/docs/), an old pod stays ESTAB until it gets SIGTERM. Connections in nginx's pool pointing at it die instantly. Symptom: a 502 spike for ~30s around every deploy.
**Fix**: `max_fails=1 fail_timeout=5s` so nginx marks the upstream failed fast, or `zone backend 64k` so the shared-memory zone sees instance changes.
### Case 4: keepalive_requests=1000 too low for short endpoints
A 5ms endpoint under `keepalive_requests=1000` rebuilds each connection every 5 seconds. nginx creates hundreds of new connections per second, and DNS resolution piles up if the upstream is a hostname. Symptom: DNS query volume spikes, worker CPU stuck in `accept`.
**Fix**: `keepalive_requests 10000`, or use an IP upstream to avoid DNS.
### Case 5: HTTP/2 front-end proxying an HTTP/1.1 backend
The front-end listens on `listen 443 ssl http2` but the backend is plain HTTP/1.1. Keepalive does not automatically apply — HTTP/2 and HTTP/1.1 use entirely different connection models, and nginx builds a fresh pool on the backend side. If the location is missing `proxy_http_version 1.1`, nginx talks HTTP/1.0 to the backend and opens a new connection every time.
**Fix**: explicitly add the three-piece set in the location, and verify `nginx -V` includes `--with-http_v2_module`.
## The Complete Production Template
This is the config I hand to teams now, commented so nothing gets dropped:
```nginx
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
multi_accept on;
use epoll;
}
http {
keepalive_timeout 65;
keepalive_requests 10000;
upstream backend {
zone backend_pool 64k;
server 10.0.0.11:8080 max_fails=2 fail_timeout=30s max_conns=256;
server 10.0.0.12:8080 max_fails=2 fail_timeout=30s max_conns=256;
keepalive 32;
keepalive_timeout 60; # shorter than backend keepalive
keepalive_requests 10000;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_next_upstream error timeout http_502 http_503;
}
}
}
```
## The Pitfall Checklist
- Missing one of the three-piece set → pool never hit, every request is a new connection
- `proxy_http_version` forgotten → HTTP/1.0 to backend, keepalive dead
- `Connection ""` written as `"keep-alive"` → backend force-closes, pool wasted
- pool × workers > backend max_connections → backend refuses connections
- nginx keepalive_timeout > backend keepAliveTimeout → dead connections in the pool
- hostname upstream without a `resolver` → cannot resolve after DNS cache expiry
- `worker_rlimit_nofile` too small → `too many open files`
- `keepalive_requests=1000` on short endpoints → constant connection rebuild
- no drain before a rolling restart → 502 spike
- config changed but not reloaded → `nginx -s reload` never took effect
The two commands that get you to the answer fastest:
```bash
ss -tanp | grep :8080 | grep ESTAB | wc -l
curl -s -o /dev/null -w "connects=%{num_connects}\n" http://127.0.0.1/health
```
## Summary
Upstream keepalive looks like three numbers but is really the thread that ties nginx, the backend, and the kernel connection model together. Three rules: **the three-piece set is non-negotiable**, **nginx timeouts must be strictly shorter than the backend's**, and **pool size is derived from the backend limit, never guessed**. If the pool is being hit, performance follows. If it is not, stop tuning and go check the config — the bottleneck is almost never the number you are staring at.
> **Original note**: This article is an independent English original written from first-hand production experience. It is not a translation of any Chinese source.
## Related Articles
- [Nginx 504 Gateway Timeout: Six Root-Cause Branches](nginx-504-troubleshoot.md)
- [Nginx Upstream Config Quick Reference](nginx-upstream-config.md)
- [Nginx Reverse Proxy 502/504 Troubleshooting](nginx-proxy.md)
- [Rolling Out ModSecurity 3.0 WAF on Produ…](nginx-waf-modsecurity.md)
---
## nginx + keepalived VIP Failover: Parameter Matrix and 6 Production Incidents
URL: https://ops.jiunotes.top/en/network/nginx-keepalived.md
摘要: Full keepalived parameter matrix with production-safe values, 6 real failure modes with root causes, 15-command cheat sheet, and the auth_pass 8-character trap that bites everyone.
### Answer
Full keepalived parameter matrix with production-safe values, 6 real production incidents with root causes and fixes, 15-command cheat sheet, auth_pass 8-character trap.
### FAQ
Q: Why isn't my VIP floating after the primary goes down?
A: Three things to check in order: VRRP advertisements being sent (tcpdump -i eth0 vrrp), auth_pass matching byte-for-byte on both nodes (keepalived only reads 8 chars), and firewall rules allowing UDP 112 from the peer. Half the time it's the firewall.
Q: What's the correct value for virtual_routerpriority?
A: Lower number = higher priority. Primary: 100, Secondary: 90 is the classic setup. Don't use the same number on both — you'll get split-brain or flapping. If you need active-active, use a third node or a different protocol (LVS, BGP).
Q: Should I use nopreempt or preempt?
A: For most web backends: nopreempt. Once the secondary takes over, keep it until it dies. preempt causes VIP flapping whenever the primary recovers, which means DNS/cache churn and connection resets. Only use preempt if the primary has a specific role (stateful service, primary DB writer).
Q: Why is auth_pass in my config 32 chars but keepalived only uses 8?
A: Historical bug/feature — VRRP spec defines auth_pass as 8-char ASCII. keepalived silently truncates to 8 chars. If you set 32 chars, both nodes need to have the SAME first 8 chars. Common mistake: generate a 32-char random password on node A, paste on node B, and think it's secure. It's 8 chars.
Q: How do I health-check the upstream so keepalived actually fails over?
A: Use track_script or track_interface. For nginx: `track_script { script: check_nginx; interval: 5; fall: 3; rise: 2 }` and a bash script that curls localhost and returns non-zero on failure. Never trust a single check — require `fall: 3` before declaring failure and `rise: 2` before recovering.
### Full Content
# nginx + keepalived VIP Failover: Parameter Matrix and 6 Production Incidents
## Why keepalived, not BGP
If you have IPMI access, dynamic routing upstream, and a router willing to speak eBGP to a stateless VM, BGP is nicer. For two VMs behind a cloud VPC with a stateless load balancer in front, keepalived is the pragmatic answer: a small daemon speaking UDP 112 to the peer, moving the VIP in about three seconds. That's the whole pitch, and it's enough for most of us.
I've run keepalived in front of [nginx](https://nginx.org/en/docs/) at three companies and one non-profit. It works. It also fails in ways that eat on-call time if you don't know the failure modes ahead of time.
## The happy path isn't the story
Every tutorial shows you the config, tells you to `systemctl start keepalived`, and shows the VIP floating when you kill the primary. In production you will not have that experience. You will have a firewall rule from a security audit three years ago, an auth_pass someone copy-pasted wrong, a NIC that got renamed after a kernel update, and a health check that only verifies the process is *up* rather than whether the service is *serving*. This article is about those cases.
## Change discipline: four things before you touch the config
Unlike nginx, keepalived is a "misconfigure and you're offline" service. One wrong `virtual_router_id` or a mismatched `advert_int` and the two nodes stop talking, and the VIP may end up on neither. My change discipline for it is stricter than for nginx — four steps, every time:
1. **`keepalived -t -f` before every reload.** Syntax-validate first; never reload on a guess. The validator catches most typos before they ever reach the running daemon.
2. **Diff both configs line by line.** Strip comments and blank lines, then compare. Aside from `router_id`, `state`, `priority`, `interface`, and the host IP, the four fields `virtual_router_id`, `advert_int`, `auth_pass`, and `virtual_ipaddress` must match byte-for-byte. Any other single differing line is a bug.
3. **Verify the heartbeat before you verify the failover.** After a reload, capture ten seconds with `tcpdump -i eth0 -nn vrrp` and confirm you see the peer's `Advert`. Only then `systemctl stop nginx` and test the switch. If the heartbeat never shows up, the failover test is meaningless.
4. **Validate the business after the VIP moves, not just `ip addr`.** The IP being present is not the service being up. `curl -sf http://10.0.0.100/` for a 200, then probe one real backend path. I've had the VIP land on the secondary whose `upstream` was missing a backend node the primary had — instant 502s for clients.
## Parameter matrix
Values for Ubuntu 22.04, keepalived 2.1.5, nginx 1.24.x.
| Parameter | Safe value | What breaks if tuned wrong |
|---|---|---|
| `virtual_router_id` | `51` (identical both sides) | Different IDs = different VRRP groups = no failover, no errors, just silence |
| `virtual_routerpriority` | Primary `100`, Secondary `90` | Same on both = split-brain; higher on secondary = VIP on wrong box |
| `virtual_ipaddress` | `192.0.2.100/24` (identical) | Not matching = VIP moves but unreachable; wrong prefix = routes nowhere |
| `advert_int` | `1` (identical) | 3x gap between peers = silent desync, occasional flapping |
| `garp_master_delay` | `5` | Too low = STP churn on the switch; too high = slow first packet after failover |
| `garp_master_repeat` | `2` | Reduces post-failover burst; clients with stale ARP keep hitting the dead primary |
| `garp_master_refresh` | `60` | Refreshes gratuitous ARPs; `0` disables and stale ARP wins |
| `garp_master_ttl` | Omit | Non-zero sets a lifetime; usually leave to the switch |
| `gna_interval` | `1` | Interval for Gratuitous ARP; too aggressive annoys neighbors, too slow leaves caches stale |
| `garp_validate_interface` | Omit | Validates the GARP NIC matches `interface`; only for weird NIC topologies |
| `nopreempt` | Yes, both sides | Without it, primary recovery yanks the VIP back — connection resets |
| `smtp_connect_timeout` | `3` | Long = delayed alerts, short = false alerts on slow SMTP |
| `script` (in `vrrp_script`) | Bash curl to localhost | Any static check (`pgrep nginx`) misses process-alive-but-not-serving |
| `auth_pass` | 8-char ASCII, identical both sides | Only first 8 chars are used; longer strings are noise (see trap below) |
| `interface` | e.g. `eth0` | Wrong NIC = VIP moves to a NIC the client can't route to |
| `interface_broadcast` | Omit | Forces broadcast on a specific NIC; only needed on multi-homed setups |
| `virtual_router_track_interface` | e.g. `eth0` | If the interface dies, VRRP drops the VIP immediately rather than waiting |
| `notify_script` | Path to state-change hook | Fires on MASTER/BACKUP transitions; useful for logging and alerting |
## Case 1: VIP doesn't float when the primary dies
Symptom: kill nginx on the primary, wait 30 seconds, curl the VIP — still hitting the dead box.
Checklist, in order:
```bash
# 1. Are VRRP packets actually being sent?
sudo tcpdump -i eth0 -nn -c 5 vrrp
# 2. Do auth_pass values match byte-for-byte (first 8 chars)?
grep auth_pass /etc/keepalived/keepalived.conf | cut -c1-8
# 3. Is the firewall passing protocol 112?
sudo iptables -L INPUT -n | grep -Ei 'vrrp|112'
```
Nine out of ten: a firewall. VRRP is IP protocol 112, not a TCP/UDP port. Standard rules like `-p tcp --dport 80 -j ACCEPT` don't touch it, and a hardened host usually defaults to `DROP` which eats VRRP silently.
```bash
sudo iptables -I INPUT -p vrrp -j ACCEPT
sudo iptables -I OUTPUT -p vrrp -j ACCEPT
```
Also check the cloud security group — many managed clouds let you filter on protocol number, and someone almost always forgets to add 112.
## Case 2: Split-brain — both nodes hold the VIP
Symptom: after a primary reboot, both hosts show the VIP in `ip addr`. A client's ARP cache points at whichever box it hit first, so requests randomly work and randomly hang.
Detect:
```bash
arp -an | grep 192.0.2.100 # on a client
ip addr show eth0 | grep 192.0.2.100 # on both nodes
```
Root cause: priorities are equal (both think they're primary) or `auth_pass` mismatches (each side ignores the other and defaults to MASTER). Fix both:
```conf
vrrp_instance VI_1 {
interface eth0
virtual_router_id 51
virtual_routerpriority 100 # 90 on the secondary
advert_int 1
nopreempt
authentication {
auth_type PASS
auth_pass S3cret12
}
virtual_ipaddress {
192.0.2.100/24
}
}
```
Reload with `systemctl reload keepalived` — a reload, not a restart, is enough to clear the bad state on the losing node.
## Case 3: Flapping every few minutes
Symptom: access logs show the VIP switching backends every 3–5 minutes, connections reset mid-flight.
I hit this the day I first deployed keepalived. The check was `pgrep nginx`. Under load, `pgrep` briefly returned a stale PID that was momentarily unresponsive; the check failed, VIP moved. Ten seconds later nginx recovered, check passed, VIP moved back. Every time.
Fix: `nopreempt` on both sides plus a slower, more deliberate check.
```conf
vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 5
fall 3
rise 2
weight -20
}
```
`fall 3` at `interval 5` means 15 seconds of consecutive failure before demotion. That's a real outage, not a hiccup.
## Case 4: Wrong NIC on multi-homed hosts
Symptom: VIP moves to the secondary, `ip addr` shows it correctly, but `curl 192.0.2.100` times out.
The `interface` field is where VRRP sends advertisements. On a host with two NICs — `eth0` for business, `eth1` for management — you want VRRP on the business NIC. Keepalived has three related knobs: `interface` (primary NIC for VRRP and VIP binding), `interface_broadcast` (forces broadcast on a specific NIC, useful on point-to-point links), and `bind_ifid` (assigns the virtual router ID to a specific interface so multiple VRs don't collide).
The mistake I made: `interface eth0` on the primary, `interface eth1` on the secondary. On failover, keepalived bound the VIP to `eth1` — the mgmt network — and client traffic went nowhere.
Rule of thumb: same NIC name, same subnet, on both nodes. Add `garp_master_delay 5` and `garp_master_repeat 2` so the switch's MAC table updates without taking the port down.
## Case 5: Health check reports up when the backend is down
This one costs the most money. Nginx is running, listening on 80, but the upstream app is dead and every request 502s. Keepalived, checking only nginx, says all clear.
Don't use `systemctl is-active --quiet nginx`. That's liveness, not readiness. Use a script that speaks HTTP to what the client would speak HTTP to:
```bash
#!/bin/bash
# /etc/keepalived/check_nginx.sh
set -e
curl -sf --max-time 3 http://127.0.0.1/healthz > /dev/null
curl -sf --max-time 3 http://127.0.0.1/upstream-probe > /dev/null
```
The `/upstream-probe` location returns 200 only when its upstream responds. Without it, nginx will happily 502 while still being "up". If you can't add an endpoint, at minimum curl the actual client URL. Set `fall 3, rise 2` so a single blip doesn't trip the failover.
## Case 6: Upgrade breaks config parsing
Upgrading keepalived from 2.0.x to 2.1.x is where I've lost the most time to parser errors. Two gotchas.
**`!` comments in `vrrp_script`.** Keepalived 2.0 used `!` as a line comment inside script blocks. 2.1 removed it in some code paths. If your config has:
```
vrrp_script chk {
script "/etc/keepalived/check.sh" ! this comment is now an error
interval 2
}
```
You'll see `Error found in configuration file` on reload, and [systemd](https://www.freedesktop.org/software/systemd/man/latest/) won't start keepalived. Convert all `!` comments to `#`.
**`vrrp_version` default flipped.** Keepalived 1.4 defaulted to VRRPv2, 2.x to VRRPv3. Mixed-version peers don't interop. Pin it explicitly on both sides:
```conf
global_defs {
vrrp_version 3
}
```
Always test with `keepalived -t -f /etc/keepalived/keepalived.conf` before `systemctl reload`. If the parser complains, the reload will silently keep the old config live while the new config fails to parse — the worst kind of half-state.
## The auth_pass trap
VRRP's auth_pass is defined as 8 ASCII characters. Keepalived silently truncates anything longer. I've seen people generate a 32-char password with `openssl rand -base64 24`, paste it into both configs, and think they have strong VRRP auth. They have 8 chars.
Worse, if two nodes share the same string but differ in the *first 8 characters* (say `S3cretPass1` vs `S3cretPass2`), the nodes don't reject each other's packets loudly — they just ignore the advertisements and each falls back to thinking it's primary. Split-brain via a typo, half an hour to find.
Test it: `grep auth_pass /etc/keepalived/keepalived.conf | cut -c1-8` on both nodes, then diff.
## Cheat sheet: 15 commands to bookmark
| # | Command | What it tells you |
|---|---|---|
| 1 | `sudo tcpdump -i eth0 -nn vrrp` | Are VRRP advertisements flowing? |
| 2 | `sudo arping -I eth0 192.0.2.100` | Who currently owns the VIP's MAC? |
| 3 | `ip addr show eth0` | Is the VIP bound on this host? |
| 4 | `systemctl status keepalived` | Service state |
| 5 | `journalctl -u keepalived -n 200 --no-pager` | Recent state transitions |
| 6 | `keepalived -V` | Version — v2 vs v3 matters |
| 7 | `keepalived -t -f /etc/keepalived/keepalived.conf` | Config syntax check |
| 8 | `ss -tlnp \| grep :80` | Is nginx listening? |
| 9 | `ss -tnp state established '( sport = :80 )'` | Established client connections on 80 |
| 10 | `cat /etc/keepalived/keepalived.conf` | Actual loaded config, not what you remember writing |
| 11 | `tail -f /var/log/keepalived.log` | Old-style syslog output if you use it |
| 12 | `dig +short 192.0.2.100` | Reverse-resolve check |
| 13 | `ifconfig eth0` | Legacy alias for `ip addr`; some scripts still use it |
| 14 | `ip route get 192.0.2.100` | Which NIC the client kernel will use |
| 15 | `curl -v --max-time 3 http://192.0.2.100/` | End-to-end check through the VIP |
## FAQ
**Why isn't my VIP floating after the primary goes down?** Three things, in this order. Are VRRP advertisements actually being sent? `tcpdump -i eth0 -nn vrrp` on the surviving node — you should see packets from the dead primary's IP every second until it truly dies. Does `auth_pass` match byte-for-byte? Remember the 8-character truncation. Is the firewall allowing protocol 112? On iptables: `iptables -I INPUT -p vrrp -j ACCEPT`. Half the time I've debugged this, it's the firewall. The other half is auth_pass.
**What's the correct value for virtual_routerpriority?** Lower is higher priority. Classic setup: Primary 100, Secondary 90. The 10-point gap is enough for VRRP to decide who wins without tripping on the small `weight` adjustments the track scripts make. Never use the same priority on both nodes — you'll get split-brain or constant re-election. For true active-active, don't fight keepalived: VRRP is fundamentally active-passive at the VIP level. Use LVS or BGP with ECMP.
**Should I use nopreempt or preempt?** For nginx fronting a web app: `nopreempt` on both sides. Once the secondary takes over, let it keep the VIP until it dies. With `preempt`, every time the primary recovers from any blip it yanks the VIP back — connections reset, DNS caches churn. Only use `preempt` when the primary has a stateful role the secondary can't do and failing back is cheaper than manual promotion.
**Why is auth_pass 32 chars in my config but keepalived only uses 8?** VRRP defines auth_pass as an 8-byte string ([RFC](https://www.rfc-editor.org/) 3768). Keepalived reads the value, silently truncates to 8 ASCII bytes, and uses that. It never warns. So pasting a 32-char `openssl rand -base64` string into both configs gives you 8 chars of auth — and both nodes just need to agree on those first 8. Two nodes with different full passwords but the same first 8 chars will happily interop; two nodes with different first 8 chars won't interop at all and each falls back to thinking it's primary — split-brain. Test with `cut -c1-8` before deploying.
**How do I health-check the upstream so keepalived actually fails over?** Two layers. First, use `vrrp_script` with a curl-based check, not `systemctl is-active` — that only tells you the process is registered, not that it's serving. Second, tune `fall` and `rise`. I use `interval 5, fall 3, rise 2` — 15 seconds of consecutive failures before declaring the node down, 10 seconds of consecutive successes before bringing it back. A single blip never trips the failover; a real outage does. Add `weight -20` so a failing check loses the VRRP election to a healthy peer at `priority 100`.
## Related Articles
- [Nginx Reverse Proxy 502/504 Troubleshooting — Full Decision Tree](nginx-proxy.md)
- [nginx Upstream Load Balancing: Algorithm Selection, Server Directives, and the keepalive Trio](nginx-upstream-config.md)
- [CDN Internals: Edge POP, Origin Fetch, Cache Invalidation & the Cost Model](cdn-principles.md)
- [Debugging nginx 502 in Docker: The 127.0…](docker-nginx-502.md)
- [Kubernetes Network Troubleshooting: A Layer-by-Layer Decision Tree and Five Real Incidents](kubernetes-network-troubleshoot.md)
---
## Nginx Reverse Proxy 502/504 Troubleshooting — Full Decision Tree
URL: https://ops.jiunotes.top/en/network/nginx-proxy.md
摘要: A working engineer's guide to diagnosing 502 Bad Gateway and 504 Gateway Timeout behind Nginx reverse proxy. 5 failure scenarios, a 20-command Cheat Sheet, 5 real-world configs, and a decision tree to pinpoint root cause in minutes.
### Answer
Nginx 502 usually means Nginx can't reach or can't parse a response from the upstream — check (1) whether the upstream is actually listening (`ss -lnt | grep :port`), (2) whether `proxy_pass` points at the right address and protocol (http vs https, IPv6 vs IPv4), and (3) whether the upstream logs show the request ever arrived. 504 is a client-visible timeout: the upstream took longer than `proxy_read_timeout` (default 60s) to respond. Start with `journalctl -u nginx -f` and the upstream service logs side by side, then work through the 5 scenarios in this article.
### FAQ
Q: What's the fastest first step when Nginx returns 502?
A: Check whether the upstream is actually listening on the port Nginx is proxying to: `ss -lnt | grep :8080`. If nothing is listening, start or restart the upstream service. If it is listening, look at upstream logs and Nginx `error.log`.
Q: What's the fastest first step when Nginx returns 504?
A: 504 means the upstream exceeded `proxy_read_timeout` (default 60s). Check `journalctl -u nginx -f` for a "upstream timed out" line — the exact upstream address is printed there. Then either fix the slow upstream or bump the timeout deliberately.
Q: When should I raise proxy_read_timeout?
A: Only when the upstream legitimately needs that long (report generation, ML inference, batch jobs). It's a symptom mask, not a fix. Bump in steps (60 → 120 → 300) and always log the reason in a comment so the next engineer isn't surprised.
Q: How do I distinguish 502 vs 504 from Nginx logs?
A: `error.log` will say "connect() failed" or "upstream prematurely closed connection" for 502, and "upstream timed out (110: Operation timed out)" for 504. The exact string tells you which class of problem you have.
Q: Why does my HTTPS reverse proxy still return 502 after I enabled TLS?
A: Because `proxy_pass` is still talking HTTP to an HTTPS backend. Match the protocol: `proxy_pass https://backend:443;` plus `proxy_ssl_server_name on;` and `proxy_ssl_name` set to the backend's TLS SNI hostname.
### Full Content
# Nginx Reverse Proxy 502 / 504 Troubleshooting
## The 30-Second Diagnosis
When [Nginx](https://nginx.org/en/docs/) shows you `502 Bad Gateway` or `504 Gateway Timeout`, it has already talked to the upstream (or tried to) and given up. The upstream is either **not reachable**, **not speaking the protocol Nginx expects**, or **too slow**. The status-code semantics you are debugging against are defined by [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110) (HTTP Semantics) — 502 means Nginx received an invalid response, 504 means it got none in time. Work in this order:
1. Is the upstream actually listening? → `ss -lnt | grep :PORT`
2. Is the upstream seeing the request? → upstream logs
3. Does `proxy_pass` point at the right thing? → reload Nginx config in `error.log`
4. Is TLS between Nginx and upstream misconfigured? → check `proxy_pass` protocol and `proxy_ssl_*`
5. Is the upstream just slow? → check `proxy_read_timeout` and upstream processing time
If you get past step 1 and still see 502, jump to the [502 Decision Tree](#502-bad-gateway-decision-tree). If the error is 504, the upstream is reachable but slow — [504 Timeout Decision Tree](#504-gateway-timeout-decision-tree) will walk through it.
## 5 Real Failure Scenarios
### 1. Upstream Not Running
The most common 502 cause, and the one that trips up the freshest engineers.
**Symptom**: 502 immediately after deploy, Nginx `error.log` says:
```
connect() failed (111: Connection refused) while connecting to upstream
upstream: "http://127.0.0.1:8080/", host: "127.0.0.1:8080"
```
**Diagnosis**:
```bash
ss -lnt | grep :8080 # Empty means nobody listening
systemctl status myapp # Is the upstream service up?
```
**Fix**: Restart the upstream. Check for boot-time failures (`journalctl -u myapp -b`).
### 2. Wrong Address Behind `proxy_pass`
A typo, a missing port, a wrong protocol — all produce the same 502.
**Common culprits**:
- `proxy_pass http://127.0.0.1;` → defaults to port 80, not 8080. Fix: `proxy_pass http://127.0.0.1:8080;`
- `proxy_pass http://backend:8080;` but `backend` doesn't resolve. Fix: add to `/etc/hosts` or use [Docker](https://docs.docker.com/) DNS (`extra_hosts:`).
- `proxy_pass https://backend;` but backend only speaks HTTP. Fix: change to `http://`.
**Diagnosis**:
```bash
grep -n 'proxy_pass' /etc/nginx/sites-enabled/default
dig backend # Does the hostname resolve?
curl -v http://backend:8080/health # From the Nginx host, does the upstream respond?
```
### 3. TLS Mismatch Between Nginx and Upstream
If you flipped the upstream to HTTPS and forgot to update `proxy_pass`, Nginx will still try HTTP and get a garbled response.
**Symptom**: Nginx log shows `upstream sent invalid header` or `upstream sent no valid HTTP/1.0 header while reading response header from upstream`.
**Diagnosis**:
```bash
# Nginx config shows proxy_pass http://backend:8443 (HTTP to HTTPS port)
# Test from the Nginx host:
curl -vk https://backend:8443/ # Should work
curl -v http://backend:8443/ # Garbled response confirms the mismatch
```
**Fix**:
```nginx
proxy_pass https://backend:8443;
proxy_ssl_server_name on;
proxy_ssl_name backend.example.com; # SNI hostname
proxy_ssl_protocols TLSv1.2 TLSv1.3;
proxy_ssl_verify off; # For self-signed cert; set on + CA if you own the cert
```
### 4. Keepalive Stale Connection
Long-lived upstreams (Java, Go net/http, Rails) tend to close idle connections from the load balancer. Nginx may hand a stale socket to a real request. (Keepalive works only on HTTP/1.1 with an empty `Connection` header — the connection-handling rules are defined in [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110).)
**Symptom**: intermittent 502s, only on the first request after a quiet period, upstream logs show "connection closed while reading headers" or similar.
**Diagnosis**:
```bash
# Check upstream keepalive settings in Nginx
grep -n 'keepalive' /etc/nginx/conf.d/upstream.conf
# On the upstream, look for the connection lifetime
ss -tnp | grep ':8080' | awk '{print $4}' # Look for CLOSE_WAIT on many sockets
```
**Fix**:
```nginx
upstream backend {
server 127.0.0.1:8080;
keepalive 32; # Max idle conns Nginx keeps open to upstream
keepalive_timeout 60s;
}
server {
location / {
proxy_pass http://backend;
proxy_http_version 1.1; # Required for keepalive upstreams
proxy_set_header Connection ""; # Empty Connection header for keepalive
}
}
```
### 5. Backend Protocol Mismatch (HTTP/1.1 vs HTTP/2)
If your upstream requires HTTP/2 (gRPC, some modern Java servers), the default HTTP/1.1 from Nginx will cause weird failures.
**Symptom**: `upstream sent invalid header` or gRPC-specific errors like `http2 framing layer`.
**Fix**:
```nginx
location / {
proxy_pass http://backend:50051;
grpc_pass grpc://backend:50051; # For gRPC
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
```
## 20-Command Cheat Sheet
Copy-paste to diagnose 502/504 quickly.
```bash
# 1. What does the user see?
curl -Iv https://your-domain.com/health
# 2. What's Nginx logging right now?
sudo journalctl -u nginx -f
# 3. What's the upstream logging?
sudo journalctl -u myapp -f
# 4. Is the upstream listening?
ss -lnt | grep :8080
# 5. Can Nginx reach the upstream?
sudo -u nginx curl -v http://127.0.0.1:8080/health
# 6. Which config is actually loaded?
sudo nginx -T 2>&1 | grep -A5 'proxy_pass'
# 7. Config syntax OK?
sudo nginx -t
# 8. Reload config
sudo systemctl reload nginx
# 9. What's the connection state between Nginx and upstream?
ss -tnp | grep ':8080'
# 10. Upstream service status
systemctl status myapp
systemctl status myapp.service --full
# 11. Upstream CPU/memory (spikes cause slowness → 504)
top -p $(pgrep -f myapp | head -1)
# 12. Nginx worker count and state
sudo nginx -T | grep worker_connections
ps aux | grep nginx
# 13. Check the exact Nginx error message
grep -E '502|504|timed out|refused' /var/log/nginx/error.log | tail -20
# 14. Check upstream response time
curl -w '@format.txt' -o /dev/null https://your-domain.com/
# format.txt: time_total, time_connect, time_starttransfer
# 15. Check upstream TLS
openssl s_client -connect backend:8443 -servername backend.example.com
# 16. Check upstream via HTTP (if you suspect TLS mismatch)
curl -v http://backend:8443/ # Garbled = mismatch
# 17. Nginx error.log level
grep 'error_log' /etc/nginx/nginx.conf
# 18. Request body size limit
grep 'client_max_body_size' /etc/nginx/nginx.conf # Default 1m — too small for uploads
# 19. Header size limit
grep 'large_client_header_buffers' /etc/nginx/nginx.conf
# 20. Access log with upstream info
grep 'proxy_upstream_name\|proxy_upstream_addr' /etc/nginx/nginx.conf
```
## 5 Real-World Configs
### Reverse Proxy for a Node.js App on 127.0.0.1:3000
```nginx
server {
listen 443 ssl http2;
server_name api.example.com;
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
access_log /var/log/nginx/api.example.com.access.log vhost;
error_log /var/log/nginx/api.example.com.error.log warn;
client_max_body_size 20m;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Request-Id $request_id;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
```
### Reverse Proxy for a [Python](https://docs.python.org/)/Flask Dev Server
```nginx
upstream flask {
server 127.0.0.1:5000;
keepalive 16;
}
server {
listen 443 ssl;
server_name dev.example.com;
location / {
proxy_pass http://flask;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Connection "";
proxy_read_timeout 120s; # Dev servers tend to be slow
}
}
```
### Reverse Proxy with gRPC Passthrough
```nginx
location /api/v1 {
grpc_pass grpc://backend:50051;
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
```
### Rate-Limited Reverse Proxy
```nginx
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
listen 443 ssl;
server_name api.example.com;
location / {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
```
### WebSocket-Enabled Reverse Proxy
```nginx
location /ws {
proxy_pass http://backend/ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s; # Keep WebSocket alive for an hour
proxy_send_timeout 3600s;
}
```
## 502 Bad Gateway — Decision Tree
```
502 → Check Nginx error.log
↓
├─ "connect() failed (111: Connection refused)"
│ → Upstream not listening. Fix: restart upstream.
│
├─ "connect() failed (110: Operation timed out)"
│ → Firewall between Nginx and upstream, or network partition.
│ Fix: iptables / security group.
│
├─ "upstream prematurely closed connection"
│ → Keepalive mismatch, or upstream crashed on request.
│ Fix: `proxy_set_header Connection "";` and check upstream logs.
│
├─ "upstream sent invalid header"
│ → Protocol mismatch (HTTP vs HTTPS, HTTP/1 vs gRPC).
│ Fix: align `proxy_pass` protocol with upstream.
│
└─ "no live upstreams"
→ All upstream servers failed. Check upstream health.
```
## 504 Gateway Timeout — Decision Tree
```
504 → Check upstream took how long?
↓
├─ < proxy_read_timeout → 502, not 504 (see above)
│
└─ > proxy_read_timeout (default 60s)
→ Slow upstream.
Fix (a): optimize upstream (usually right answer)
Fix (b): raise `proxy_read_timeout` deliberately
(with a comment explaining why)
Fix (c): move long jobs to async (queue + poll)
```
## 502 vs 504 vs 499 — Quick Reference
| Code | Meaning | Where to fix |
|------|---------|--------------|
| **502 Bad Gateway** | Nginx couldn't reach or talk to upstream | Nginx config, upstream service |
| **504 Gateway Timeout** | Upstream too slow for `proxy_read_timeout` | Upstream performance, or bump timeout |
| **499 Client Closed Request** | User gave up before Nginx got a response | Nginx is fine — user/network issue |
| **503 Service Unavailable** | Upstream returned 503, or Nginx is overloaded | Upstream health, or `worker_processes` |
## Wrapping Up
502 and 504 are the two workhorses of reverse-proxy debugging. Half of them are "upstream not running" and "wrong port in `proxy_pass`" — the cheapest bugs to fix. The harder ones (keepalive, TLS mismatch, gRPC) all boil down to one question: **what does Nginx think it's talking to, and what is the upstream actually talking back?** Read the `error.log` string, match it against this decision tree, and you'll usually know what to change within a minute.
For related reading, see:
- [TCP Troubleshooting: TIME_WAIT / RST / SYN Half-Open](tcp-troubleshoot.md) — the layer below
- [Wireshark Basics: 30 Filters + Field Cheat Sheet](wireshark-basics.md) — when logs aren't enough
- [CDN Origin & Cache: Origin Fetch, Preheat, Invalidation](cdn-principles.md) — 502 sometimes lives on the CDN side, not your Nginx
- [IPv6 Deployment and Migration: Dual-Stack Transition Without the Fire Drill](ipv6-migration.md) — dual-stack listening and firewall rules for the 80/443 port pair
> The RFC referenced in this article ([RFC 9110](https://www.rfc-editor.org/rfc/rfc9110) HTTP Semantics) and the port numbers 80/443 also exist as machine-readable entries in the [ops fact warehouse](https://github.com/fxlcj/ops-fact-warehouse), each with its official source URL and a check date.
## Related Articles
- [Debugging nginx 502 in Docker: The 127.0…](docker-nginx-502.md)
---
## nginx Upstream Load Balancing: Algorithm Selection, Server Directives, and the keepalive Trio
URL: https://ops.jiunotes.top/en/network/nginx-upstream-config.md
摘要: Upstream block internals for SREs: 6 load balancing algorithms with a decision matrix, per-server parameter values, the keepalive trio that stops 502s, health-check workarounds, 5 production incidents.
### Answer
Pick least_conn + weighted weights + keepalive trio (keepalive 32, timeout 60, requests 10000) + HTTP/1.1 for any API backend.
### FAQ
Q: Which algorithm for stateless REST APIs behind 3 backend pods?
A: Default round-robin is fine for identical pods. If pod sizes differ (mixed 4GB and 8GB), use weighted round-robin with weights proportional to vCPU. Reach for least_conn only when request duration variance is high (P99 / P50 > 5x).
Q: Why do I get 'upstream sent no valid HTTP/1.0 header' after adding keepalive?
A: You set `keepalive 32` in the upstream block but forgot `proxy_http_version 1.1;` inside the location. Keepalive upstreams require HTTP/1.1 between nginx and the backend — HTTP/1.0 (the nginx default) can't carry the Connection reuse semantics.
Q: Does nginx have active health checks?
A: No. Upstream checks are passive — nginx only knows a backend is bad after a request fails. Real-time checks require nginx-plus, an external health checker that updates the upstream via the balancer API, or lua-resty-balancer doing its own probing.
Q: What's a safe max_conns value?
A: Start at the backend's `worker_processes * worker_connections` divided by 2. For a Node.js app with `ulimit -n 65536` and one process, I usually set `max_conns 500`. For Java backends behind Tomcat with `maxThreads=200`, set `max_conns 150` so a saturated thread pool triggers failover before clients see 503.
Q: Should I use ip_hash for session affinity?
A: Only if the backend holds sticky state and you cannot pass it through. ip_hash is brittle: an nginx version upgrade can rehash everything, and it never fails over a dead peer under the classic implementation. Prefer token-based session transfer or a shared Redis layer.
Q: How do I know if my keepalive trio is actually working?
A: Look at `upstream_bytes_received`, `upstream_connect_time`, and TCP connection churn. If `ss -tnp | grep :8080` shows mostly ESTABLISHED connections (not fresh SYNs every request), keepalive is doing its job. If connect time drops from ~30µs to ~2µs per request after the change, you saved TCP setup cost.
### Full Content
# nginx Upstream Load Balancing: Algorithm Selection, Server Directives, and the keepalive Trio
## 1. How [nginx](https://nginx.org/en/docs/) actually uses the upstream block
An `upstream` block is not just a list of servers — it's a peer pool that nginx evaluates on every proxied request. When a client hits `proxy_pass http://api_pool`, nginx does this work inside the worker process: resolve peer candidates (excluding `down` or over-`max_conns`), pick one via the configured algorithm, open or reuse a keepalive connection if available, proxy the request, and update that peer's failure counters if the response fails.
Every one of those steps is configurable. Most tutorials cover the third step and stop. The other four are where production incidents live.
## 2. Six algorithms, one decision matrix
Nginx ships with six upstream algorithms. The choice depends less on "which is fastest" and more on your traffic shape and backend state model.
| Algorithm | Config line | Best for | Kill it when |
|---|---|---|---|
| Round-robin | *(default)* | Identical pods, no session state | Request durations vary wildly |
| Weighted round-robin | `server b weight=3` | Mixed hardware or capacity | Weights exceed real capacity ratio |
| `ip_hash` | `ip_hash` at block level | Legacy sessions without shared state | Any nginx upgrade or peer add/remove |
| `least_conn` | `least_conn` at block level | Variable-duration requests (ML, reports) | All peers roughly equal — adds bookkeeping cost |
| `hash` | `hash $cookie_sid consistent` | Cache-friendly routing (same key → same peer) | Fewer than 2 peers per hash bucket |
| `zone` + `consistent_hash` | `zone pool 64m` + `consistent_hash` | Hot peer rotation during deploys | Small peer counts (n < 4) — no benefit |
The default round-robin is what I use for 70% of services. It is boring in the best way: predictable, tunable via `weight`, and no hidden bookkeeping. `least_conn` is where I land when P99 request duration is more than 5x P50 — otherwise the fairness gain isn't worth the extra counter churn.
## 3. Per-server directives, with real numbers
Every `server` line inside an upstream block accepts up to six parameters. Their actual impact varies by a factor of ten depending on traffic.
```nginx
server 10.0.2.11:8080 weight=5 # Traffic share, 1..256
max_fails=3 # Failures within fail_timeout before pause
fail_timeout=10s # Pause window; also failure window when >0
max_conns=200 # Hard cap on concurrent requests per peer
backup # Only receives traffic when all primaries are down
down; # Hard-remove this peer (use sparingly)
```
Values I use as defaults:
- `weight=1` for identical peers, `weight=2` or `weight=3` for pods with double or triple the CPU.
- `max_fails=3` with `fail_timeout=10s` for APIs. That means a peer needs three consecutive failures within ten seconds to be paused — one bad request does not kick it out, but a genuine outage does within seconds.
- `max_fails=1, fail_timeout=60s` for expensive long-running jobs. One failure means pause for a full minute.
- `max_conns` at 50% of the backend's own connection cap. For a Tomcat with `maxThreads=200`, I set `max_conns 100`. That headroom is deliberate — it lets nginx shed load before Tomcat's thread pool saturates.
- `backup` on a canary peer with `weight=1`. Traffic only reaches it when every primary fails. This is my default for staged rollouts.
`down` deserves a warning: it removes the peer from the rotation without removing it from the file. It survives `nginx -s reload`. I keep a commented-out `down` line next to any server I might need to eject during an incident — flipping a `#` and reloading is faster than editing a list.
## 4. The keepalive trio that prevents 502 storms
The single most common nginx upstream misconfiguration I've debugged is a half-configured keepalive. The trio has to be complete:
```nginx
upstream api_pool {
server 10.0.2.11:8080 weight=5;
server 10.0.2.12:8080 weight=5;
server 10.0.2.13:8080 weight=5;
keepalive 32; # Max idle connections per worker to keep open
keepalive_timeout 60s; # Idle timeout on those sockets
keepalive_requests 10000; # Max requests per kept socket before recycling
}
server {
location / {
proxy_pass http://api_pool;
proxy_http_version 1.1; # Required — HTTP/1.0 cannot reuse sockets
proxy_set_header Connection ""; # Strips "Connection: close" that browsers may send
}
}
```
Get any one of these wrong and the effect is predictable:
- Missing `proxy_http_version 1.1;` → nginx 502s with `upstream sent no valid HTTP/1.0 header while reading response header from upstream`.
- Missing `proxy_set_header Connection "";` → browser `Connection: close` propagates, keepalive never engages.
- `keepalive_requests` too low (default is 1000) → sockets recycle every thousand requests, connect cost comes back.
- `keepalive_timeout` shorter than backend's idle timeout → nginx closes first, backend gets a half-open and logs noise.
I use `keepalive 32` because each nginx worker opens up to 32 idle sockets per peer pool. With four workers and three upstreams, that's 384 sockets maximum — well below typical `ulimit -n`. On heavy traffic I've pushed it to 64; below 16 you start missing reuse opportunities.
## 5. Health checks: the reality check
Nginx OSS has no built-in active health checking. When a peer fails a real request, nginx marks it down for `fail_timeout` and moves on. That is passive health checking, and it works — until the backend hangs without refusing connections. Then nginx keeps sending requests into a black hole.
Three ways around this:
1. **Passive + generous timeouts.** Set `proxy_connect_timeout 3s` and `proxy_read_timeout 30s`. Anything slower trips `max_fails` within seconds. Simple, no code, but you're using client-visible latency as the health signal.
2. **`balancer_by_lua_block`** with `lua-resty-balancer` doing its own periodic probes. Works, but you're now running Lua inside nginx and debugging two runtimes.
3. **nginx-plus** with `health_check` directive. If you already pay for plus, use it. It does exactly what OSS lacks: periodic TCP/HTTP checks independent of traffic.
For OSS, I pair `max_fails=3 fail_timeout=10s` with an external health checker that touches the upstreams directly and alerts, rather than trying to encode health logic into nginx.
## 6. Zone directives and dynamic rebalancing
The `zone` directive is where upstream state moves out of per-worker memory into shared memory:
```nginx
upstream api_pool {
zone api_pool 64m;
server 10.0.2.11:8080;
server 10.0.2.12:8080;
}
```
Without `zone`, each worker maintains its own peer state. That means:
- `max_fails` counters are per-worker, not global. A worker that just started won't know the other workers marked a peer down.
- `least_conn` counts are per-worker. With 32 workers, you can have 32x more connections to one peer than to another.
With `zone` enabled, state is shared. The cost: nginx can no longer add or remove peers without a full reload. If you need runtime peer changes (say, an autoscaler adding pods), use `lua-resty-balancer` or OpenResty's resty balancing APIs instead.
Dynamic rebalancing through Lua costs you in three places: debugging (two languages), config drift (peers no longer live in the config file), and observability (nginx's built-in balancer status no longer reflects reality). I've done it once and I don't like it.
## 7. Five production incidents I've hit
### 7.1 Weighted round-robin starving a slow backend
Three pods, weights 5, 5, 1. The weight-1 pod kept getting 15% of traffic, which was more than its CPU could absorb. It fell behind, requests queued, then nginx marked it failed for `fail_timeout` — which kicked it off the rotation, which meant the other two got 100% load, which pushed them over their caps. The recovery I had to write: lower the healthy pods to `weight=4` and the slow pod to `weight=2`, so the imbalance reflected actual capacity instead of aspirational allocation.
### 7.2 `ip_hash` breaking on nginx 1.25
Nginx 1.25 changed the internal hash seed for `ip_hash`. We upgraded a fleet of 40 nodes and roughly 30% of in-flight sessions silently moved to different backends. The app was fine with the wrong peer — it just lost session state, so users saw "please log in again." I downgraded, and we waited for a proper migration: a shared [Redis](https://redis.io/docs/) session layer, then remove `ip_hash` entirely. The lesson is that hash-based affinity looks stable until it isn't.
### 7.3 Half-configured keepalive → 502 storm
I added `keepalive 32` to an upstream block at 2am and forgot `proxy_http_version 1.1;`. Reload succeeded. Within 90 seconds every request 502'd. The `error.log` line was `upstream sent no valid HTTP/1.0 header while reading response header from upstream`. I've now got that line in my on-call runbook as a "keepalive miswired" trigger — it appears when you have keepalive configured but not correctly.
### 7.4 `max_conns` set too low → 503 under burst
Set `max_conns=5` on a pool of eight pods. Peak traffic hit, one pod's counter tripped, nginx started returning 503 with `no live upstreams while connecting to upstream`. It looked like the entire pool was down. Lowering `max_conns` to 100 fixed it. My default now is: `max_conns` at 50% of backend capacity, never below 20 for anything that sees more than 50 rps.
### 7.5 Upstream timeout cascade from a single slow request
One backend took 45 seconds to respond to a legitimate request. `proxy_read_timeout` was 60s. The worker held the connection, the client waited, then the client disconnected at 30s — nginx logged a 499, the worker was now stuck on a socket the client no longer cared about. Multiply by one slow peer per second and you've exhausted `worker_connections`. Fix was `proxy_read_timeout 15s` on that endpoint, which forced nginx to time out the request and return 504 cleanly instead of holding a half-open socket.
## 8. Production template
Copy-pasteable, tuned for a generic API pool:
```nginx
upstream api_pool {
zone api_pool 64m;
server 10.0.2.11:8080 weight=5 max_fails=3 fail_timeout=10s max_conns=200;
server 10.0.2.12:8080 weight=5 max_fails=3 fail_timeout=10s max_conns=200;
server 10.0.2.13:8080 weight=5 max_fails=3 fail_timeout=10s max_conns=200;
server 10.0.2.99:8080 weight=1 max_fails=1 fail_timeout=60s max_conns=50 backup;
keepalive 32;
keepalive_timeout 60s;
keepalive_requests 10000;
}
server {
listen 443 ssl http2;
server_name api.example.com;
location / {
proxy_pass http://api_pool;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_connect_timeout 3s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 5s;
}
}
```
The three `proxy_next_upstream` lines are the piece most people forget. They tell nginx which response codes should trigger a retry on another peer, how many times, and within what time budget. Without them, a single peer outage looks like a service outage to the client.
## 9. Cheat Sheet — 15 upstream one-liners
```bash
# Show the upstream blocks actually loaded (not what you think you wrote)
nginx -T 2>&1 | awk '/upstream .* \{/,/\}/'
# Count current connections to each upstream peer
ss -tnp | grep ':8080' | awk '{print $4}' | sort | uniq -c | sort -rn
# See how many ESTABLISHED vs TIME_WAIT to the upstream pool
ss -tn state established '( dport = :8080 )' | wc -l
ss -tn state time-wait '( dport = :8080 )' | wc -l
# Test the keepalive trio is actually engaged
curl -s -o /dev/null -w '%{time_connect}\n' http://api.example.com/ # sub-millisecond = keepalive working
# Trigger a passive health check on a suspect peer
for i in $(seq 1 20); do curl -s -o /dev/null -w '%{http_code} %{time_total}\n' http://api.example.com/; done
# Drain a peer without killing it (mark down, reload)
sed -i 's|server 10.0.2.11:8080|server 10.0.2.11:8080 down|' /etc/nginx/conf.d/api.conf
nginx -s reload
# Bring it back
sed -i 's|server 10.0.2.11:8080 down|server 10.0.2.11:8080|' /etc/nginx/conf.d/api.conf
nginx -s reload
# Reload with zero connection loss
nginx -s reload && nginx -s reopen
# Check worker count and connection cap
nginx -T 2>&1 | grep -E 'worker_(processes|connections|rlimit_nofile)'
# Watch upstream errors as they happen
tail -F /var/log/nginx/error.log | grep -E 'upstream|connect\(\) failed|timed out'
# Look at nginx access log upstream timing
awk '{print $NF}' /var/log/nginx/access.log | head
# Show current upstream pool (nginx-plus only)
curl -s http://127.0.0.1:8081/api/upstream
# Compare peer load balance (nginx-plus)
curl -s http://127.0.0.1:8081/api/upstream/api_pool | jq '.peers[].received'
# Full config syntax + reload rehearsal
nginx -t && nginx -s reload
# Show the keepalive directives as loaded
nginx -T 2>&1 | grep -E 'keepalive|proxy_http_version|Connection'
```
## 10. FAQ
**Which algorithm for stateless REST APIs behind 3 identical pods?** Default round-robin. Don't overthink it — the algorithm cost is noise compared to backend CPU cost. Only reach for `least_conn` when request duration variance is high (P99/P50 > 5x). If pods differ in size, use weighted round-robin with weights proportional to vCPU.
**Why do I get "upstream sent no valid HTTP/1.0 header" after adding keepalive?** You set `keepalive 32` inside the upstream block but forgot `proxy_http_version 1.1;` inside the location. Keepalive upstreams require HTTP/1.1 between nginx and the backend — HTTP/1.0, which is nginx's default, cannot carry connection reuse.
**Does nginx have active health checks?** No. OSS nginx does passive checks only — a peer is marked down after a real request fails. For real-time health checks you need nginx-plus, an external health checker updating the pool via the balancer API, or `lua-resty-balancer` doing its own probing.
**What's a safe `max_conns` value?** Start at 50% of the backend's own connection cap. Node.js with `ulimit -n 65536` in a single process: `max_conns 500`. Java behind Tomcat with `maxThreads=200`: `max_conns 100`. Never go below 20 on anything receiving more than 50 rps — sub-20 values trip the "no live upstreams" fast path on bursts.
**Should I use `ip_hash` for session affinity?** Only if the backend holds sticky state and you cannot pass it through any other way. `ip_hash` is brittle: an nginx upgrade can rehash everything (this actually broke production in nginx 1.25), and the classic implementation does not fail over a dead peer. Prefer token-based session transfer, a shared Redis session layer, or `$cookie`/`$header` hashing when you control the keys.
**How do I know if my keepalive trio is actually working?** Watch three signals: TCP connection churn (`ss -tnp | grep :8080` — mostly ESTABLISHED, not a fresh SYN every request), connect time (`curl -w '%{time_connect}\n'` — sub-millisecond on warm sockets, tens of microseconds to low milliseconds), and upstream bytes counters (steady rise, no sawtooth that tracks request volume). If connect time drops from ~30µs to ~2µs after adding keepalive, it's engaged.
**How does `zone` change behavior?** Without `zone`, each worker has its own peer state — `max_fails` counters and `least_conn` counts are per-worker, and peer add/remove requires a full reload. With `zone`, state is shared in memory across workers, and dynamic rebalancing becomes possible via the balancer API. The tradeoff: you can no longer edit peers freely in config without a reload, and debugging gets harder.
## Related Articles
- [Nginx Reverse Proxy 502/504 Troubleshooting — Full Decision Tree](nginx-proxy.md)
- [nginx + keepalived VIP Failover: Parameter Matrix and 6 Production Incidents](nginx-keepalived.md)
- [CDN Internals: Edge POP, Origin Fetch, Cache Invalidation & the Cost Model](cdn-principles.md)
- [Debugging nginx 502 in Docker: The 127.0…](docker-nginx-502.md)
---
## Rolling Out ModSecurity 3.0 WAF on Production nginx: Five Incidents, False Positives, and One Hard-Won Config
URL: https://ops.jiunotes.top/en/network/nginx-waf-modsecurity.md
摘要: First-person notes on compiling ModSecurity 3.0 as a dynamic nginx module, wiring OWASP CRS, and taming false positives through five real incidents: SQLi, CC flood, bot scraping, and rule regression.
### Answer
Field-tested ModSecurity 3.0 on nginx: compile, load, tune, survive.
### FAQ
Q: Why load ModSecurity as a dynamic module instead of compiling it statically?
A: Dynamic loading keeps the nginx binary upgradeable without rebuilding against libmodsecurity, and lets you swap the WAF in or out with a single load_module line and a reload.
Q: What is the fastest way to reduce false positives?
A: Run CRS in detection-only mode, study the audit log, then add targeted field exclusions (SecRuleUpdateTargetById) before flipping the engine to On.
Q: How did the CC flood get stopped without blocking real users?
A: Two layers: nginx limit_req_zone with burst and nodelay for the obvious volume, plus a ModSecurity counter rule that denies clients with an elevated blocked-request score.
Q: Why did a CRS rule update take my API down?
A: A newer CRS release added a stricter request-body consistency check that matched a large legitimate JSON payload, so every batch request 403'd until I pinned the CRS version and added a smoke test.
### Full Content
# Five Incidents That Made Me Trust ModSecurity on Production nginx
I manage a small fleet of [nginx](https://nginx.org/en/docs/) reverse proxies in front of a public API and a web store. For two years I leaned on `fail2ban`, `iptables`, and a generous rate limiter. It worked right up until it did not. A botnet would ramp up slowly enough to stay under my per-IP threshold, hammer one endpoint with SQLi probes for a few minutes, then vanish. IP blocking is reactive, coarse, and blind to what is inside the request. I needed a layer that understood HTTP, not just sockets. That is when I committed to ModSecurity 3.0 — and it produced five incidents worth writing down.
## 1. Building ModSecurity 3.0 as a dynamic module
I built the connector against the exact nginx source tree I was running, so I could drop the WAF in with a reload instead of a rebuild. Assumes Debian 12, nginx 1.24.0.
```bash
# ===================== 1. build dependencies =====================
apt install -y build-essential libpcre3-dev libssl-dev zlib1g-dev \
libxml2-dev libcurl4-openssl-dev libgeoip-dev libmodsecurity3 libmodsecurity-dev
# ===================== 2. match the running nginx =====================
nginx -v # nginx/1.24.0
wget https://nginx.org/download/nginx-1.24.0.tar.gz && tar xzf nginx-1.24.0.tar.gz
# ===================== 3. clone the official connector =====================
[git](https://git-scm.com/doc) clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx.git
# ===================== 4. build ONLY the dynamic module =====================
cd nginx-1.24.0
./configure --with-compat --add-dynamic-module=../ModSecurity-nginx
make modules && cp objs/ngx_http_modsecurity_module.so /etc/nginx/modules/
# ===================== 5. sanity check before reload =====================
nginx -t && systemctl reload nginx
```
The `--with-compat` flag is critical: it builds the module against the running nginx binary signature so it loads as a shared object. One line at the top of `nginx.conf`:
```nginx
# /etc/nginx/nginx.conf (first line of the main context)
load_module modules/ngx_http_modsecurity_module.so;
```
## 2. Wiring the OWASP CRS in detection-only mode
I pulled the CRS and wired it up, but deliberately kept `SecRuleEngine DetectionOnly`. Nobody flips a WAF to blocking on a busy box without watching it first.
```bash
git clone --depth 1 https://github.com/coreruleset/coreruleset.git /etc/nginx/modsecurity/crs
cp /etc/nginx/modsecurity/crs/crs-setup.conf.example /etc/nginx/modsecurity/crs/crs-setup.conf
cp /etc/nginx/modsecurity/crs/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example \
/etc/nginx/modsecurity/crs/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf
```
The main `modsecurity.conf`:
```nginx
# ===================== /etc/nginx/modsecurity/modsecurity.conf =====================
SecRuleEngine DetectionOnly # start safe, always
SecRequestBodyAccess On
SecRequestBodyLimit 13107200 # 12.5 MiB batch orders
SecResponseBodyAccess Off
SecAuditEngine RelevantOnly # log only real matches
SecAuditLog /var/log/nginx/modsec_audit.log
SecAuditLogType Serial
SecAuditLogParts ABIJDEFHZ
SecDefaultAction "phase:2,log,auditlog,pass"
Include crs/crs-setup.conf
Include crs/rules/*.conf
```
Then I tuned `crs-setup.conf` before ever enforcing. These are the lines that matter on a real API:
```nginx
# ===================== crs-setup.conf: the knobs I actually changed =====================
SecAction "id:9000001,phase:1,pass,nolog,setvar:'tx.crs_setup_version=400',setvar:'tx.paranoia_level=1'"
SecAction "id:9000002,phase:1,pass,nolog,setvar:'tx.executing_paranoia_level=1'"
SecAction "id:9000003,phase:1,pass,nolog,setvar:'tx.crs_validate_utf8_encoding=1'"
SecAction "id:9000004,phase:1,pass,nolog,setvar:'tx.allowed_methods=GET POST PUT DELETE OPTIONS'"
SecAction "id:9000005,phase:1,pass,nolog,setvar:'tx.allowed_request_content_type=application/json application/x-www-form-urlencoded multipart/form-data'"
SecAction "id:9000006,phase:1,pass,nolog,setvar:'tx.allowed_http_versions=HTTP/1.1 HTTP/2 HTTP/3'"
SecAction "id:9000007,phase:1,pass,nolog,setvar:'tx.max_num_args=256',setvar:'tx.arg_name_length=128'"
SecAction "id:9000008,phase:1,pass,nolog,setvar:'tx.max_arg_length=1024',setvar:'tx.total_arg_length=65536'"
SecAction "id:9000009,phase:1,pass,nolog,setvar:'tx.blocking_inbound_anomaly_score=5'"
SecAction "id:9000010,phase:1,pass,nolog,setvar:'tx.inbound_anomaly_score_threshold=5'"
SecAction "id:9000011,phase:1,pass,nolog,setvar:'tx.outbound_anomaly_score_threshold=4'"
SecAction "id:9000012,phase:1,pass,nolog,setvar:'tx.restricted_extensions=.exe .dll .bat .sh .cmd'"
SecAction "id:9000013,phase:1,pass,nolog,setvar:'tx.restricted_headers=/Proxy-Connection/ /Lock-Token/ /Content-Range/'"
SecAction "id:9000014,phase:1,pass,nolog,setvar:'tx.static_extensions=.css .js .png .jpg .svg .ico .woff .woff2 .gif'"
```
```nginx
# ===================== server block =====================
server {
listen 443 ssl;
server_name api.example.com;
modsecurity on;
modsecurity_transaction_id $request_id;
modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
}
```
## 3. Incident 1: the legitimate API got blocked by a false positive
Detection-only meant I saw everything and broke nothing. But the log was full of rule `942100` firing on `POST /api/v2/orders`, every time. The payload was JSON carrying a base64-encoded signature, and `942100` (SQLi) matched because base64 blobs contain byte sequences that look like SQL operators. Real orders were flagged. The fix was not to disable SQLi detection, but to narrow the target field.
```nginx
# ===================== REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf =====================
# base64-encoded JSON signatures look like SQL operators to rule 942100
SecRuleUpdateTargetById 942100 "!REQUEST_BODY" "id:9001001,phase:2,t:none,pass,nolog"
SecRuleUpdateTargetByTag "attack-sqli" "!REQUEST_BODY" "id:9001002,phase:2,t:none,pass,nolog"
```
## 4. Incident 2: a real SQLi attempt caught in the wild
Three weeks in, the audit log showed `942100` and `942130` firing on `GET /api/login?u=admin'--&p=x`. A classic comment-based injection. Detection-only proved from the log that the request would never reach the app. That was the moment I flipped `SecRuleEngine` to `On`.
```nginx
# ===================== production enforcement =====================
SecRuleEngine On
SecDefaultAction "phase:2,deny,status:403,log,auditlog"
```
This is the actual audit line that convinced me — note the `libinjection` verdict and the matched `--` inside the username argument:
```text
[28/Oct/2026:09:14:22+0000] [error] 18234#0: *89102 [client 203.0.113.55] ModSecurity: Warning. Matched "Operator `Rx' with parameter `(union|select|insert|drop|update)' against variable `ARGS:u' (Value: `admin'" --' )" [file "/etc/nginx/modsecurity/crs/rules/REQUEST-942-APPLICATION-ATTACK-SQLI.conf"] [line "110"] [id "942100"] [rev "4"] [msg "SQL Injection Attack Detected via libinjection"] [data "Matched Data: '--' found within ARGS:u"] [severity "2"] [ver "OWASP_CRS/4.0.0"] [tag "attack-sqli"] [hostname "api.example.com"] [uri "/api/login"]
```
I also started scanning the audit log daily:
```bash
grep -oE "\[id \"[0-9]+\"\]" /var/log/nginx/modsec_audit.log | grep -oE "[0-9]+" \
| sort | uniq -c | sort -rn | head -5
```
## 5. Incident 3: a CC flood during a flash sale
A `/sale` endpoint took about 40,000 requests in ten minutes from rotating residential IPs. Per-IP rate limiting was useless: every IP stayed under my threshold. I added two layers — nginx `limit_req_zone` for the obvious volume, plus a ModSecurity counter rule that denies clients whose transaction accumulated a high blocked-request score.
```nginx
# ===================== http context: rate limits =====================
limit_req_zone $binary_remote_addr zone=api:10m rate=20r/s;
limit_req_zone $binary_remote_addr zone=store:10m rate=10r/s;
```
```nginx
# ===================== server/location context =====================
location /sale {
limit_req zone=api burst=40 nodelay; # absorb short spikes, then throttle
proxy_pass http://backend;
}
```
```nginx
# ===================== modsecurity.conf: repeat-offender rule =====================
SecRule &TX:blocked_count "@gt 30" \
"id:9002001,phase:1,deny,status:429,msg:'repeat offender, throttled',log,auditlog"
```
## 6. Incident 4: the bot that scraped my whole catalog
A headless scraper walked my product catalog, roughly twelve pages a second, no throttling, no `User-Agent` spoofing. The winning move was not blocking the IP — it was blocking the pattern, while leaving my own monitoring agents untouched.
```nginx
# ===================== /etc/nginx/modsecurity/custom-rules.conf =====================
# ---- incident 4: bot / scraper defenses ----
SecRule REQUEST_HEADERS:User-Agent "@rx (?i)(?:scrapy|python-requests|headless-chrome|phantomjs|selenium|okhttp|http-client)" \
"id:9003001,phase:1,deny,status:403,msg:'scraper detected',log,auditlog,ver:'custom/1.0',tag:'automation'"
SecRule REQUEST_HEADERS:User-Agent "@streq curl" \
"id:9003002,phase:1,pass,nolog" # keep our own health checks alive
SecRule REQUEST_HEADERS:User-Agent "@rx (?i)(?:facebookexternalhit|slurp|bingbot|googlebot|baiduspider)" \
"id:9003003,phase:1,pass,nolog,msg:'legit crawlers allowed',tag:'crawler'"
SecRule REQUEST_HEADERS:Accept-Encoding "@contains gzip" \
"id:9003004,phase:1,pass,nolog" # no false alarm on compression
# ---- incident 3: CC flood / repeat offenders ----
SecRule &TX:blocked_count "@gt 30" \
"id:9003005,phase:1,deny,status:429,msg:'repeat offender, throttled',log,auditlog,ver:'custom/1.0'"
SecRule TX:anomaly_score "@gt 20" \
"id:9003006,phase:2,deny,status:429,msg:'anomaly score exceeded, throttled',log,auditlog,ver:'custom/1.0'"
# ---- incident 5: large legitimate bodies must not 403 ----
SecRule REQUEST_BODY "@gt 1048576" \
"id:9003007,phase:2,pass,nolog,msg:'large legitimate body observed',ver:'custom/1.0'"
# ---- hardened method + path controls ----
SecRule REQUEST_METHOD "@pm GET POST PUT DELETE OPTIONS" \
"id:9003008,phase:1,deny,status:405,msg:'method not allowed',log,auditlog,ver:'custom/1.0',tag:'protocol'"
SecRule REQUEST_URI "@contains /admin" \
"id:9003009,phase:2,deny,status:403,msg:'admin path blocked for public',log,auditlog,ver:'custom/1.0',tag:'access'"
SecRule REQUEST_FILENAME "@rx \.(?:php|asp|aspx|jsp|pl|py|cgi)$" \
"id:9003010,phase:2,deny,status:403,msg:'script extension blocked',log,auditlog,ver:'custom/1.0',tag:'protocol'"
```
## 7. Incident 5: the rule update regression
I upgraded CRS from 3.3 to 4.0. The new `REQUEST-913` plus a stricter `REQUEST-920` body-consistency check began matching a large legitimate JSON payload — a batch order with 200 line items. Every `/api/batch` request returned 403 for forty minutes before I caught it. I pinned the CRS to a specific tag and added a pre-deploy smoke test.
```bash
# ===================== pin CRS, never let it float =====================
cd /etc/nginx/modsecurity/crs
git checkout v4.0.0
git describe --tags # record the exact tag in your change log
```
```nginx
# ===================== smoke-test guard: log oversized legit bodies =====================
SecRule REQUEST_BODY "@gt 1048576" \
"id:9004001,phase:2,pass,nolog,msg:'large legitimate body observed'"
```
My post-mortem rule is now non-negotiable: upgrade CRS in detection-only, diff the audit log against a known-good baseline, and only then enforce.
## 8. The false-positive playbook
After the first month I had a repeatable loop. Run in detection-only. Pull the audit log. Group alerts by rule ID. For each rule firing on legitimate traffic, either exclude the field or the location. Keep every exclusion in `REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf` so it is version-controlled, reviewed, and survives upgrades. Never disable a whole rule; narrow it with `SecRuleUpdateTargetById`.
| # | Rule ID | Signal I saw | Root cause | Mitigation |
|:--|:--|:--|:--|:--|
| 1 | 942100 | Legit JSON blocked | base64 blob matched SQLi regex | `SecRuleUpdateTargetById 942100 "!REQUEST_BODY"` |
| 2 | 942100/942130 | Real SQLi caught | `u=admin'--` comment injection | Engine `On` + daily audit scan |
| 3 | custom 9002001 | CC flood | rotating residential IPs | `limit_req_zone` + counter rule |
| 4 | custom 9003001 | Bot scraping | headless crawler | UA-pattern deny + allowlist |
| 5 | 913 / 920 | Rule update regression | stricter body-consistency check | Pin CRS tag + smoke test |
## 9. The complete production config template
This is the server block I run today, combining the CRS, my incident-derived exclusions, and the rate limits.
```nginx
# ===================== /etc/nginx/sites-available/waf-api.conf =====================
load_module modules/ngx_http_modsecurity_module.so;
# ---------- http context ----------
limit_req_zone $binary_remote_addr zone=api:10m rate=20r/s;
limit_req_zone $binary_remote_addr zone=store:10m rate=10r/s;
map $http_user_agent $bad_ua {
default 0;
~*(?:scrapy|python-requests|headless|phantomjs|selenium|okhttp) 1;
}
log_format waf '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent" '
'$request_id $modsec_transaction_id';
# ---------- server context ----------
server {
listen 443 ssl;
server_name api.example.com;
access_log /var/log/nginx/api-waf.access.log waf;
modsecurity on;
modsecurity_transaction_id $request_id;
modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
location /sale {
limit_req zone=api burst=40 nodelay;
proxy_pass http://backend;
}
location /api/ {
# Incident 1: base64 blob false positive
# Incident 4: keep curl health checks alive
modsecurity_rules '
SecRuleUpdateTargetById 942100 "!REQUEST_BODY"
SecRule REQUEST_HEADERS:User-Agent "@streq curl" "id:9003002,phase:1,pass,nolog"
';
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
location /store/ {
limit_req zone=store burst=30 nodelay;
if ($bad_ua) { return 403; }
proxy_pass http://backend;
}
}
```
## 10. Monitoring, upgrades, and what I wish I had known
Three signals matter: the audit-log match count (`SecAuditEngine RelevantOnly`), the 403 rate grouped by rule ID, and the anomaly-score distribution. Alert the moment a single rule ID spikes — that is either an active attack or a fresh false positive, and you need to know which before it becomes an outage. Before every CRS upgrade I hit staging with a known-good JSON payload and a known-bad SQLi string. That smoke test would have caught Incident 5 in seconds.
```bash
# ===================== /usr/local/bin/waf-audit-scan.sh =====================
#!/usr/bin/env bash
AUDIT=/var/log/nginx/modsec_audit.log
TOP=$(grep -oE "\[id \"[0-9]+\"\]" "$AUDIT" | grep -oE "[0-9]+" \
| sort | uniq -c | sort -rn | head -5)
SEV=$(grep -oE "\[severity \"[0-9]\"\]" "$AUDIT" | sort | uniq -c)
if [ -n "$TOP" ]; then
echo "WAF alert $(date): top rules $TOP ; severity $SEV" \
| mail -s "WAF audit: new rule spikes" oncall@example.com
fi
```
```cron
# crontab -e — run the scan every 15 minutes
*/15 * * * * /usr/local/bin/waf-audit-scan.sh >/dev/null 2>&1
```
If I could go back, I would tell myself four things: compile the module against the exact nginx version you run; start in detection-only no matter how confident you are; treat every CRS rule as guilty until proven innocent against your own traffic; and never let the CRS version float.
## 11. Appendix: the exact files I ship
Every file below is copy-paste ready. This is the complete set, not a fragment — each comment marks what an incident taught me.
```nginx
# ===================== /etc/nginx/modsecurity/modsecurity.conf (final) =====================
# Incident 2: engine is ON in production; never ship DetectionOnly on a live API
SecRuleEngine On
SecRequestBodyAccess On
SecRequestBodyLimit 13107200
SecResponseBodyAccess Off
SecAuditEngine RelevantOnly
SecAuditLog /var/log/nginx/modsec_audit.log
SecAuditLogType Serial
SecAuditLogParts ABIJDEFHZ
SecDefaultAction "phase:2,deny,status:403,log,auditlog"
Include crs/crs-setup.conf
Include crs/rules/*.conf
Include custom-rules.conf
```
```nginx
# ===================== /etc/nginx/modsecurity/crs-setup.conf (tuned) =====================
SecAction "id:9000001,phase:1,pass,nolog,setvar:'tx.crs_setup_version=400',setvar:'tx.paranoia_level=1'"
SecAction "id:9000002,phase:1,pass,nolog,setvar:'tx.executing_paranoia_level=1'"
SecAction "id:9000003,phase:1,pass,nolog,setvar:'tx.crs_validate_utf8_encoding=1'"
SecAction "id:9000004,phase:1,pass,nolog,setvar:'tx.allowed_methods=GET POST PUT DELETE OPTIONS'"
SecAction "id:9000005,phase:1,pass,nolog,setvar:'tx.allowed_request_content_type=application/json application/x-www-form-urlencoded multipart/form-data'"
SecAction "id:9000006,phase:1,pass,nolog,setvar:'tx.allowed_http_versions=HTTP/1.1 HTTP/2 HTTP/3'"
SecAction "id:9000007,phase:1,pass,nolog,setvar:'tx.max_num_args=256',setvar:'tx.arg_name_length=128'"
SecAction "id:9000008,phase:1,pass,nolog,setvar:'tx.max_arg_length=1024',setvar:'tx.total_arg_length=65536'"
SecAction "id:9000009,phase:1,pass,nolog,setvar:'tx.blocking_inbound_anomaly_score=5'"
SecAction "id:9000010,phase:1,pass,nolog,setvar:'tx.inbound_anomaly_score_threshold=5'"
SecAction "id:9000011,phase:1,pass,nolog,setvar:'tx.outbound_anomaly_score_threshold=4'"
SecAction "id:9000012,phase:1,pass,nolog,setvar:'tx.restricted_extensions=.exe .dll .bat .sh .cmd'"
SecAction "id:9000013,phase:1,pass,nolog,setvar:'tx.restricted_headers=/Proxy-Connection/ /Lock-Token/ /Content-Range/'"
SecAction "id:9000014,phase:1,pass,nolog,setvar:'tx.static_extensions=.css .js .png .jpg .svg .ico .woff .woff2 .gif'"
```
```nginx
# ===================== /etc/nginx/modsecurity/custom-rules.conf (final) =====================
# Incident 4: scraper patterns, allowlisted crawlers and our own curl checks
SecRule REQUEST_HEADERS:User-Agent "@rx (?i)(?:scrapy|python-requests|headless-chrome|phantomjs|selenium|okhttp|http-client)" \
"id:9003001,phase:1,deny,status:403,msg:'scraper detected',log,auditlog,ver:'custom/1.0',tag:'automation'"
SecRule REQUEST_HEADERS:User-Agent "@streq curl" "id:9003002,phase:1,pass,nolog"
SecRule REQUEST_HEADERS:User-Agent "@rx (?i)(?:facebookexternalhit|slurp|bingbot|googlebot|baiduspider)" \
"id:9003003,phase:1,pass,nolog,msg:'legit crawlers allowed',tag:'crawler'"
# Incident 3: CC flood — repeat offenders get a 429, not a permanent ban
SecRule &TX:blocked_count "@gt 30" "id:9003005,phase:1,deny,status:429,msg:'repeat offender, throttled',log,auditlog,ver:'custom/1.0'"
SecRule TX:anomaly_score "@gt 20" "id:9003006,phase:2,deny,status:429,msg:'anomaly score exceeded, throttled',log,auditlog,ver:'custom/1.0'"
# Incident 5: large legitimate batch bodies must log, never 403
SecRule REQUEST_BODY "@gt 1048576" "id:9003007,phase:2,pass,nolog,msg:'large legitimate body observed',ver:'custom/1.0'"
# protocol hardening
SecRule REQUEST_METHOD "@pm GET POST PUT DELETE OPTIONS" "id:9003008,phase:1,deny,status:405,msg:'method not allowed',log,auditlog,ver:'custom/1.0',tag:'protocol'"
SecRule REQUEST_URI "@contains /admin" "id:9003009,phase:2,deny,status:403,msg:'admin path blocked for public',log,auditlog,ver:'custom/1.0',tag:'access'"
SecRule REQUEST_FILENAME "@rx \.(?:php|asp|aspx|jsp|pl|py|cgi)$" "id:9003010,phase:2,deny,status:403,msg:'script extension blocked',log,auditlog,ver:'custom/1.0',tag:'protocol'"
# payload-shape guards that cost nothing but catch the noisy half of bot traffic
SecRule ARGS "@rx (?i)(?:'
curl -s -o /dev/null -w "%{http_code}\n" \
-X POST http://ops.jiunotes.top/api/comment -d 'content='
```
对照实验才能证明豁免"精准命中"而非"误伤一片"。
### 7.2 内网办公网段被误杀
更尴尬的一次:公司同事从办公室访问线上后台,全员 403。一看 audit log,命中 `941130`(JavaScript 事件属性检测),触发点是登录后的跳转 URL 带了 `?redirect=javascript:...` 参数——这是我们自己前端写的合法跳转逻辑。因为办公网是可信内网,我直接加了白名单:
```nginx
SecRule REMOTE_ADDR "@ipMatch 192.168.100.0/24" \
"id:990300,phase:1,nolog,pass,allow"
```
`allow` 动作会跳过后续规则,可信网段完全不经过 CRS,性能还更好了。**白名单要窄**:只放行办公网段,绝不放行整个公网。
验证白名单是否生效,我从办公网发起一次明显恶意请求:
```bash
# 从 192.168.100.0/24 网段内的机器执行
curl -s -o /dev/null -w "%{http_code}\n" \
"http://ops.jiunotes.top/api/search?kw="
# 期望 200:因为 allow 在 phase:1 就放行了,根本不进 CRS
```
这一步很关键——**确认白名单真的跳过**,否则你以为放行了,实际仍被 941 拦截,业务方会再报一轮"又误杀了"。
## 8. 完整生产配置模板
把前面所有碎片拼成一份可复制的完整配置。先看独立的 `modsecurity.conf`(WAF 本体参数):
```nginx
# /etc/nginx/modsecurity/modsecurity.conf
# 全局开关:灰度期用 DetectionOnly,稳定后改 On
SecRuleEngine On
# 请求体检测:这是注入检测的基础,必须开
SecRequestBodyAccess On
SecRequestBodyLimit 131072
SecRequestBodyNoFilesLimit 131072
SecRequestBodyInMemoryLimit 65536
SecRequestBodyLimitAction Reject
# 响应体检测:默认关,开销大且易误报,需要再单点开
SecResponseBodyAccess Off
# 审计日志:RelevantOnly 只记命中的事务,日志量可控
SecAuditEngine RelevantOnly
SecAuditLog /var/log/nginx/modsec_audit.log
SecAuditLogType Serial
SecAuditLogParts ABIJDEFHZ
SecAuditLogFormat JSON
SecAuditLogStorageDir /var/log/nginx/modsec_audit
# 超时与失败处理:检测超时降级为 pass,别让 WAF 本身拖垮服务
SecRuleUpdateActionById 949110 "pass"
SecRuleUpdateActionById 959130 "pass"
SecDefaultAction "phase:2,deny,status:403,log,auditlog"
```
其中 `SecAuditLogFormat JSON` 是我强烈建议的——结构化日志能被 ELK/Loki 直接解析,排查时按 `rule_id` 聚合快得多。
接下来是 site 级配置:
```nginx
# /etc/nginx/conf.d/site-waf.conf
load_module /etc/nginx/modules/ngx_http_modsecurity_module.so;
http {
# 基础 WAF 开关
modsecurity on;
modsecurity_config /etc/nginx/modsecurity/modsecurity.conf;
# CRS 接入(放 http 级,全站生效)
include /etc/nginx/modsecurity/crs/crs-setup.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-901-INITIALIZATION.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-905-COMMON-EXCEPTIONS.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-910-IP-REPUTATION.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-911-METHOD-ENFORCEMENT.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-920-PROTOCOL-ENFORCEMENT.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-930-APPLICATION-ATTACK-LFI.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-931-APPLICATION-ATTACK-RFI.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-932-APPLICATION-ATTACK-RCE.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-933-APPLICATION-ATTACK-PHP.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-941-APPLICATION-ATTACK-XSS.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-942-APPLICATION-ATTACK-SQLI.conf;
include /etc/nginx/modsecurity/crs/rules/REQUEST-949-BLOCKING-EVALUATION.conf;
include /etc/nginx/modsecurity/crs/rules/RESPONSE-959-BLOCKING-EVALUATION.conf;
include /etc/nginx/modsecurity/crs/rules/RESPONSE-980-HTTP-EXCEPTIONS.conf;
server {
listen 443 ssl http2;
server_name ops.jiunotes.top;
ssl_certificate /etc/nginx/ssl/ops.jiunotes.top.crt;
ssl_certificate_key /etc/nginx/ssl/ops.jiunotes.top.key;
# 业务白名单:可信内网跳过 WAF(窄范围,别放行整个公网)
SecRule REMOTE_ADDR "@ipMatch 192.168.100.0/24" \
"id:990300,phase:1,nolog,pass,allow";
# 富文本编辑内容豁免 XSS 检测(精准豁免而非整条剔除)
SecRuleUpdateTargetById 941100 "!ARGS:/admin/post/content";
# 自定义 CC 防护:同 IP 每分钟超 120 次即 429
SecAction "id:990100,phase:1,initcol:ip=%{REMOTE_ADDR},nolog,pass";
SecRule IP:count "@gt 120" "id:990101,phase:1,deny,status:429,log,msg:'CC'";
SecRule IP:count "@gt 0" "id:990102,phase:1,setvar:ip.count=+1,nolog,pass";
# 管理后台单独收紧:登录接口限速
location /wp-login.php {
SecRule TX:login_count "@gt 10" \
"id:990211,phase:2,deny,status:403,log,msg:'Brute force'";
proxy_pass http://backend;
proxy_set_header Host $host;
}
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 友好错误页:别把"被 WAF 拦"和"系统故障"混为一谈
error_page 403 /403.html;
location = /403.html {
root /usr/share/nginx/html;
internal;
}
}
}
```
灰度切换建议:第一周 `SecRuleEngine DetectionOnly` 只记不拦,把误报清干净;第二周再切 `On`。别一步到位——我用一次全员 403 换来的教训是:**误报会摧毁业务方对 WAF 的信任**。
调试技巧:上线初期把 `SecRuleEngine` 设为 `DetectionOnly`,让 WAF 只记不拦,观察几天 audit log 确认无误报后再切回 `On`。这是最稳的灰度方式。
## 9. 调优与监控:我踩过的坑
**坑一:响应体检测别乱开。** 我试过 `SecResponseBodyAccess On`,结果大 JSON 接口的响应体被完整缓存解析,内存和延迟双双飙升。最终关掉,只保留请求侧检测。
**坑二:正则回溯让 CPU 打满。** CRS 默认规则的 `@rx` 在超长输入下可能有回溯开销,我加了 `SecRequestBodyLimit 131072` 并把 `SecRuleUpdateTargetById` 用于超长字段,防住了恶意超大包。
**坑三:忘了看审计日志。** 有一次误报排查半天,才发现 `SecAuditEngine` 被我误设为 `Off`,压根没记录。生产环境务必 `RelevantOnly`,只记命中的事件,否则日志量爆炸。
**监控建议:** 把 `$status` 为 403/429 的比例、`modsec_audit.log` 的条目增长率接进 [Prometheus](https://prometheus.io/docs/)。403 比例突然上升,八成是攻击或误报,要立刻看 audit log 定位。
上线前必须压测,别拿"应该不会慢"赌生产。我用的对比方法:
```bash
# 开关 WAF 各跑一轮,对比 QPS 和 P99
# 关:注释掉 load_module + modsecurity on,reload 后跑
ab -n 20000 -c 200 http://127.0.0.1/api/health > /tmp/no_waf.txt
# 开:恢复配置,reload 后再跑
ab -n 20000 -c 200 http://127.0.0.1/api/health > /tmp/with_waf.txt
grep "Requests per second" /tmp/no_waf.txt /tmp/with_waf.txt
```
如果 P99 涨幅超过 50ms,优先做三件事:`SecResponseBodyAccess Off`(响应体检测最贵)、`SecRequestBodyLimit` 收紧到业务上限、把高频接口的字段加进豁免列表。**别急着降 Paranoia Level,先查性能热点在不在你不需要的检测上。**
日常巡检命令,我挂在 crontab 里每分钟跑:
```bash
# 403/429 占比骤升就告警
awk '{print $9}' /var/log/nginx/access.log | grep -cE '^(403|429)$'
# audit log 条目数突变也要盯
wc -l /var/log/nginx/modsec_audit.log
```
`modsec_audit.log` 增长极快,务必配 logrotate,不然磁盘被填满是迟早的事:
```bash
# /etc/logrotate.d/nginx-modsec
/var/log/nginx/modsec_audit.log {
daily
rotate 14
compress
missingok
notifempty
create 0640 www-data adm
postrotate
nginx -s reopen # 必须告诉 nginx 重新打开日志文件
endscript
}
```
注意 `postrotate` 里的 `nginx -s reopen`,漏了它 audit log 会一直写进被 rotate 走的旧文件,你以为在轮转,其实根本没生效——这个坑我踩过,日志文件删了还占着 inode。
排障速查,遇到问题按这个顺序过一遍:
```bash
# 1. 配置语法对不对
nginx -t
# 2. 模块到底加载没有
nginx -T 2>/dev/null | grep -c "load_module.*modsecurity"
# 3. 规则文件有没有 include 进来(缺一个文件就少一层防护)
nginx -T 2>/dev/null | grep -c "REQUEST-942-APPLICATION-ATTACK-SQLI"
# 4. 是"没拦"还是"拦了没记录"?
grep -c "modsecurity" /var/log/nginx/error.log
tail -20 /var/log/nginx/modsec_audit.log
# 5. 临时关掉 WAF 对比:注释 modsecurity on 后 reload,请求是否恢复正常
# 恢复了 → 大概率误报;没恢复 → 问题不在 WAF,别赖 WAF
```
第 5 条我称之为"**开关对比法**",是判断问题是不是 WAF 引起的金标准。很多同事一看到 403 就急着改规则,其实用开关对比法 5 分钟就能定性。
**升级 CRS 的坑**:每次升级 CRS 小版本,规则 ID 会新增、`REQUEST-900` 排除文件可能被覆盖。升级后我必做三件事:`nginx -t` 过语法、跑一遍 `curl` 冒烟(打正常接口 + 恶意接口各一)、看 audit log 有没有新误报。别直接 reload 就完事。
## FAQ
**Q:ModSecurity 会拖慢 nginx 吗?**
A:会。实测 CRS 默认 PL1 下 QPS 下降 5%-15%,主要是请求体解析和正则开销。上线前必须压测,我的底线是 P99 增加不超过 50ms。
**Q:误报怎么快速定位?**
A:`SecAuditEngine RelevantOnly` 只记录触发规则的事件,一条误报的 audit log 里有 transaction 编号,能直接看到命中规则 ID 和原始 payload,照着加排除规则即可。
**Q:Paranoia Level 要不要开到 4?**
A:别在生产直接开。PL1 是默认,PL2 误报率已明显上升,PL3/PL4 只适合高安全敏感场景。建议 PL1 起步,用排除规则补个别业务风险。
**Q:误封的 IP 怎么快速解封?**
A:若用了 CRS 的 IP 封禁规则(REQUEST-910),把 `REMOTE_ADDR` 临时加入白名单。更稳妥的是用 fail2ban 做封禁层、ModSecurity 只做检测,解封逻辑分开,避免误伤。
## 相关文章
- [Wireshark 抓包实战:定位 nginx 502 / 504 根因的完整排查链路](wireshark-nginx-troubleshoot.md)
- [Docker 环境下 nginx 502 排查:127.0.0.1 vs 服务名、DNS 解析、健康检查五坑指南](docker-nginx-502.md)
- [nginx 504 gateway timeout 排查:6 类根因决策树](nginx-504-troubleshoot.md)
- [日志分区写满复盘:/var/log 100% 服务静默失败](../postmortems/log-partition-full.md)
---
## Linux 时间同步实战与排障:chrony 配置模板 + 5 个真实时钟漂移故障
URL: https://ops.jiunotes.top/network/ntp-time-sync.md
摘要: 时钟漂移是生产隐形杀手:TLS 证书 not yet valid、Kerberos 认证失败、监控数据错位都源于此。本文给 chrony 完整配置模板、国内 NTP 源选择、跳变 vs 渐进调整,加 5 个真实排障案例与决策树。
### Answer
时钟漂移引发 TLS/Kerberos/监控三类故障。chrony 配国内源 + makestep 渐进校正,timedatectl 与 chronyc sources -v 验证。
### FAQ
Q: 时钟漂移会造成哪些生产故障?
A: 最常见三类:TLS 证书报 "not yet valid"(服务器快了)、Kerberos 认证 "Clock skew too great"、监控与日志时间错位。都源于机器时间与真实时间偏差过大。
Q: chrony 和 ntpd 怎么选?
A: 新系统首选 chrony。它对高延迟高抖动网络更稳、收敛更快、支持 makestep 一步校正。ntpd 传统但启动慢,systemd-timesyncd 只能做客户端不能做服务端。
Q: 为什么不用 time.nist.gov 或 pool.ntp.org?
A: 这些国外源跨境延迟高、抖动大,国内同步质量差。用 ntp.aliyun.com 或 cn.pool.ntp.org 最稳,延迟低且准确度够。
Q: makestep 1.0 3 是什么意思?
A: 前 3 次同步时,若偏移超过 1 秒就一步跳变校正;超过 3 次后改为渐进 slewing。避免生产环境大步跳变引发告警风暴和证书问题。
### Full Content
# Linux 时间同步实战与排障:chrony 配置模板 + 5 个真实时钟漂移故障
## 一、时钟漂移为什么是生产隐形杀手
我干了快十年的 [Linux](https://www.kernel.org/doc/html/latest/) 运维,处理过几百起线上事故,其中最让我头大的不是磁盘写满、不是内存 OOM,反而是最不起眼的**系统时间**。它平时安安静静,一旦出事,症状五花八门,排查方向却常常被带偏。
先说三个我真实踩过的坑,你会发现它们八竿子打不着,根子却是同一个。
### 1.1 TLS 证书报 "certificate is not yet valid"
有一年公司对外提供 HTTPS 服务,客户反馈浏览器直接红屏,报错 `ERR_CERT_DATE_INVALID`。我登录服务器一看,证书明明在有效期内,签发时间和到期时间都正常。再 `date` 一看——**这台服务器的系统时间比真实时间快了 5 分多钟**。
证书的 notBefore 是真实时间往后推几个月的,服务器时间快 5 分钟,在客户端眼里,当前时间已经越过 notBefore 吗?不会。但反过来的场景更常见:**服务器时间慢了**。客户端用服务器时间做本地验证,或者反向代理做双向校验,时间一错位,就会在握手阶段报:
```
openssl s_client -connect api.example.com:443
Verify return code: 9 (certificate is not yet valid)
```
或者干脆:
```
error: certificate is not yet valid
```
`Verify return code: 9` 对应的就是 X509_V_ERR_NOT_YET_VALID,意思是「证书尚未生效」。这几乎 100% 意味着**某台机器的时间比真实时间慢**,导致证书看起来还没到生效时刻。
### 1.2 Kerberos 认证 "Clock skew too great"
另一个高频事故是内部系统用 Kerberos 做 SSO,某天突然批量报:
```
kinit: krb5_get_credentials: Clock skew too great (37) - PROCESS_TGS
```
Kerberos 协议本身就是基于时间戳的。客户端向 KDC 请求票据时,会带上自己的时间戳,KDC 校验这个时间戳与自身时间之差是否超过默认 **300 秒(5 分钟)** 的容差。一旦客户端与域控时间差超过 5 分钟,认证直接拒绝。
有一次我排查一台老旧的日志服务器,发现它的时间比域控慢了整整 40 分钟。原因很讽刺——这台机器 NTP 服务压根没跑,靠 RTC 电池苟着,主板电池快没电了,一断电时间就回退。
### 1.3 日志时间错乱与监控数据错位
第三类症状最隐蔽:**日志和监控数据时间对不上**。应用日志时间戳由 A 机生成,采集端打上 B 机的时间,存储端又打上 C 机的时间,三台机器时间各差几秒到几分钟,导致:
- 故障排查时,日志顺序颠倒,同一请求的日志散落在错误的时间窗;
- [Prometheus](https://prometheus.io/docs/) 里 `rate()`、`increase()` 这类按时间窗计算的函数,在时间戳回跳时产生负数或锯齿;
- 告警规则的 `for: 5m` 持续判定逻辑,因时间错位被反复触发或漏触发;
- 分布式数据库(etcd、Cassandra、TiKV)的线性一致性依赖时间戳,时钟大幅跳变会破坏数据一致性。
**结论先行**:时间同步不是「锦上添花」,而是所有依赖时间戳的协议、证书、分布式系统、监控告警的**地基**。地基歪了,上面全塌。
## 二、60 秒决策:chrony vs ntpd vs [systemd](https://www.freedesktop.org/software/systemd/man/latest/)-timesyncd
选型之前,先搞清楚手上这台机器在同步链里的角色:是**只做客户端**,还是**要当 NTP 服务端**给内网其他机器供时?
| 特性 | chrony | ntpd | systemd-timesyncd |
|------|--------|------|-------------------|
| 定位 | 完整 NTP 客户端+服务端 | 传统 NTP 客户端+服务端 | 轻量客户端,**只能当客户端** |
| 服务端能力 | ✅ 可做服务端 | ✅ 可做服务端 | ❌ 无服务端功能 |
| 高延迟/高抖动网络 | ✅ 最稳,支持 NTP over Unix socket | ⚠️ 容易丢同步源 | ⚠️ 依赖网络质量 |
| 启动收敛速度 | 快,秒级可同步 | 慢,分钟级起步 | 较快 |
| 一步跳变(makestep) | ✅ 原生支持 | ⚠️ 需 `-x` 或配置 | ✅ 支持 |
| 硬件时间戳 | ✅ 支持 | ✅ 支持 | ❌ 不支持 |
| 虚拟化环境 | ✅ 最佳选择 | ⚠️ 在 VM 里容易漂 | ✅ 可用 |
| 配置文件 | /etc/chrony/chrony.conf | /etc/ntp.conf | /etc/systemd/timesyncd.conf |
| 控制工具 | chronyc | ntpq | timedatectl |
| 默认安装 | 现代发行版(RHEL8+/Debian10+) | 老旧系统 | systemd 自带 |
**我的选型结论**:
1. **新装系统一律 chrony**。RHEL/CentOS 8 之后、Debian 10 之后、Ubuntu 18.04+ 都默认它。它对高延迟、高抖动的网络(比如跨境、跨运营商)抗性最好,收敛快,还支持一步校正。
2. **老系统(CentOS 6、RHEL 7 默认装 ntpd)** 如果迁移成本高,可以保留 ntpd,但要记得它默认**不跳变**,只做 slewing(渐进微调),漂移严重时收敛极慢。
3. **最小化容器、嵌入式、无状态节点** 用 systemd-timesyncd 足够,因为它只当客户端。但**千万别指望它给内网其他机器供时**。
一句话:**能上 chrony 就上 chrony,需要做 NTP 服务端必须 chrony 或 ntpd,systemd-timesyncd 永远只能当客户端**。
## 三、前置:确认时区与 RTC
装任何 NTP 软件之前,先确认两件事:**时区对不对**、**硬件时钟(RTC)模式对不对**。时区错了,同步得再准,显示出来的时间也是错的。
### 3.1 timedatectl 三行解读
`timedatectl` 不带参数,输出三块核心信息,一次看全:
```bash
timedatectl
```
期望输出(以一台阿里云 ECS 为例):
```
Local time: 三 2026-10-28 10:15:32 CST
Universal time: 三 2026-10-28 02:15:32 UTC
RTC time: 三 2026-10-28 02:15:32
Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
NTP service: active
RTC in local TZ: no
```
逐行解读:
- **Local time / Universal time**:本地时间与 UTC 时间。两者相差正是时区偏移,这里 +0800。
- **RTC time**:硬件时钟(CMOS/主板电池)当前时间。正常情况应等于 Universal time(UTC)。
- **Time zone**:时区,必须是你业务所在时区。
- **System clock synchronized: yes**:系统时钟已被同步过。这是关键指标。
- **NTP service: active**:NTP 服务是否在跑。看到 `inactive` 说明同步根本没启动。
- **RTC in local TZ: no**:RTC 是否使用本地时区。生产环境**必须是 no**,让 RTC 跑 UTC,否则跨时区、跨 DST 会乱。
### 3.2 硬件时钟 vs 系统时钟
Linux 有两个「时钟」:
- **系统时钟(System Clock / kernel clock)**:内核维护的软件时钟,精度高,靠 NTP 持续校准,关机就没了。
- **硬件时钟(RTC / CMOS clock)**:主板电池供电的时钟,关机后靠电池走时,精度差,开机时被读入作为系统时钟的初始值。
开机流程是:BIOS/UEFI 读 RTC → 内核据此初始化系统时钟 → NTP 接手后持续校准系统时钟 → 定期把校准后的时间写回 RTC(chrony 的 `rtcsync` 干这事)。
### 3.3 设置时区与 UTC
生产环境推荐**时区用 Asia/Shanghai,RTC 用 UTC**。一条命令设置时区:
```bash
timedatectl set-timezone Asia/Shanghai
```
让 RTC 跑 UTC(生产必须这样,别学一些老教程把 RTC 设成本地时区):
```bash
timedatectl set-local-rtc 0
```
`set-local-rtc 0` 表示 RTC 使用 UTC,`timedatectl` 里会显示 `RTC in local TZ: no`。
> ⚠️ 注意:设置时区后,`/etc/localtime` 会被指向 `/usr/share/zoneinfo/Asia/Shanghai`。如果发现手动改过 `/etc/localtime`(比如直接 `cp` 了某个 zoneinfo),建议用 `timedatectl` 规范操作,避免时区数据库和系统时区不一致。
时区数据校验,看本地时间是否与预期一致:
```bash
date && timedatectl show -p Timezone --value
```
期望输出:
```
三 10月 28 10:15:32 CST 2026
Asia/Shanghai
```
## 四、chrony 配置实战:完整可复制模板
### 4.1 安装
RHEL/CentOS 系:
```bash
yum install -y chrony
systemctl enable --now chronyd
```
Debian/Ubuntu 系:
```bash
apt install -y chrony
systemctl enable --now chrony
```
确认版本:
```bash
chronyd --version
```
期望输出:
```
chronyd 4.3
```
### 4.2 完整 chrony.conf 模板
以下是**生产环境可直接复制**的 `/etc/chrony/chrony.conf`(RHEL/Debian 路径略有差异,Debian 是 `/etc/chrony/chrony.conf`,老版本在 `/etc/chrony.conf`,以实际为准)。我逐段注释,每项都是实测参数。
```conf
# ============================================================
# 生产环境 chrony 配置模板
# 适用:内网 NTP 服务端 + 客户端,CentOS/RHEL 7+/Debian 10+
# 作者:一线运维,实测于 2026-10
# ============================================================
# --- 上游时间源:国内主源 + 备用池 ---
server ntp.aliyun.com iburst
server cn.pool.ntp.org iburst
# 可选备用,避免单点
server ntp.tencentcloud.com iburst
server ntp1.aliyun.com iburst
# --- 漂移文件:chrony 据此估算本地时钟的固有漂移率,自动生成,勿手动改 ---
driftfile /var/lib/chrony/drift
# --- 步进校正策略:前 3 次同步若偏移 > 1 秒则一步跳变,之后渐进 slewing ---
# 关键参数,生产必配,详见第七章
makestep 1.0 3
# --- RTC 同步:chrony 定期把系统时间写回硬件时钟,防关机丢时间 ---
rtcsync
# --- 日志目录:chrony 的统计/测量日志(chronyc tracking 用)---
logdir /var/log/chrony
# --- 允许内网网段作为客户端:按实际网段修改,禁止 0.0.0.0/0 ---
# 只允许内网子网同步,不暴露公网
allow 192.168.0.0/24
allow 10.0.0.0/8
# --- 拒绝其他所有来源(默认拒绝,配合上面 allow 白名单)---
deny all
# --- 当无法到达所有上游源时,仍以本地 stratum 10 对外提供时间 ---
# 防止上游全挂后内网完全失去同步能力(仅内网服务端需要)
local stratum 10
# --- 网络绑定:只监听内网接口,最小化暴露面 ---
# 若有多个网卡,建议显式绑定内网 IP,例如 bindaddress 192.168.1.10
# bindaddress 192.168.1.10
# --- 客户端连接数上限,防资源滥用 ---
maxclients 256
# --- 客户端请求速率限制(单位:每秒),防 NTP 放大攻击 ---
ratelimit interval 4 burst 32
# --- 仅监听 UDP 123(NTP 默认端口),无需改 ---
```
### 4.3 关键指令逐条说明
| 指令 | 作用 | 生产建议 |
|------|------|---------|
| `server iburst` | 指定上游源,`iburst` 快速突发采样加速首次同步 | 2-4 个国内源 |
| `driftfile` | 记录时钟漂移率,重启后能快速估算偏移 | 必配 |
| `makestep 1.0 3` | 前 3 次同步偏移 >1s 则跳变,之后 slewing | 生产必配 |
| `rtcsync` | 定期写回硬件时钟 | 必配,防关机丢时 |
| `allow <网段>` | 允许哪些客户端来同步 | 只允许内网 |
| `deny all` | 默认拒绝所有 | 配合 allow 用 |
| `local stratum 10` | 上游全挂时仍提供本地时间 | 内网服务端配 |
| `bindaddress` | 绑定监听地址 | 多网卡建议显式 |
| `maxclients` | 并发客户端上限 | 防资源耗尽 |
| `ratelimit` | 请求速率限制 | 防 DDoS/放大攻击 |
### 4.4 应用配置
改完配置,语法检查 + 重启:
```bash
chronyd -t /etc/chrony/chrony.conf
systemctl restart chronyd
systemctl enable chronyd
```
> `chronyd -t` 是测试模式,会解析配置并打印错误(若有)而不真正启动,适合改配置后先验证。
### 4.5 放行防火墙
NTP 走 UDP 123,内网服务端需要放行。firewalld:
```bash
firewall-cmd --permanent --add-service=ntp
firewall-cmd --reload
```
iptables(如果用的 iptables):
```bash
iptables -A INPUT -p udp --dport 123 -s 192.168.0.0/24 -j ACCEPT
```
## 五、国内网络下的 NTP 源选择
这是国内生产环境最容易被忽略的一环。很多人习惯性抄国外教程写 `server 0.pool.ntp.org`,结果同步质量极差。我的经验是:**在国内机房,选源第一优先级是「地理与网络路径近」,而不是「源本身准不准」。**
### 5.1 推荐源清单
| 源 | 类型 | 延迟实测(华东 BGP 机房) | 评价 |
|----|------|--------------------------|------|
| `ntp.aliyun.com` | 阿里云公共 NTP | 2-15 ms | **首选**,国内多节点,准且快 |
| `ntp1.aliyun.com` | 阿里云备用 | 2-15 ms | 常用备用 |
| `cn.pool.ntp.org` | 中国 NTP 池 | 5-40 ms | **推荐**,国内节点池 |
| `ntp.tencentcloud.com` | 腾讯云公共 NTP | 3-20 ms | 推荐,腾讯内网友好 |
| `ntp.tencent.com` | 腾讯 | 5-30 ms | 可用 |
| `ntp.aliyun.com`(主)+ `cn.pool.ntp.org`(备) | 组合 | — | 我的默认组合 |
| `time.windows.com` | 微软 | 30-80 ms | 一般,仅 Windows 用 |
| `time.nist.gov` | 美国 NIST | 150-300+ ms,抖动大 | **不推荐**,跨境 |
| `pool.ntp.org` | 全球池 | 100-200 ms,抖动大 | **不推荐**,跨境 |
| `time.google.com` | Google | 跨境被墙/高延迟 | **不推荐** |
### 5.2 为什么坚决不用 time.nist.gov / pool.ntp.org
我在一台华东机房服务器上实测过,对比国内源和国外源:
```bash
chronyc sources -v
```
用 `pool.ntp.org` 时,典型输出:
```
===============================================================================
.-- Source remote - | Stratum ... Reach Last Rx | Offset Delay Disp
===============================================================================
^- 162.159.200.1 | 1 | 12% 20m | +38ms 185ms 12ms
^* 162.159.200.123 | 1 | 23% 15m | -52ms 210ms 20ms
```
**Reach(可达性)只有 12%、23%**,说明跨境包大量丢,`Delay`(延迟)180-210ms,`Offset`(偏移)几十毫秒来回跳。这种源对 chrony 来说是灾难——它需要稳定的低抖动输入来估算频率误差,跨境源抖动一上来,同步精度根本没法保证。
换 `ntp.aliyun.com` 后:
```
===============================================================================
.-- Source remote - | Stratum ... Reach Last Rx | Offset Delay Disp
===============================================================================
^* 120.25.115.20 | 2 | 100% 1s | +0.2ms 6ms 0.3ms
^- 182.92.12.11 | 2 | 100% 1s | -0.4ms 9ms 0.5ms
```
**Reach 100%,Delay 6-9ms,Offset 0.2ms 级别**。这才是国内该有的同步质量。
> 经验法则:**Delay 超过 50ms 或 Reach 经常低于 50%,这个源就该换掉**。国内机房用国内源,延迟个位数毫秒才是正常的。
### 5.3 源选择原则总结
1. **优先就近**:华东选阿里云/腾讯云华东节点,华北选华北节点,优先内网或同运营商。
2. **至少配 2 个源**:一个主源 + 一个备用,避免单点。别只配一个。
3. **不同运营商各来一个**:跨运营商互访质量差,最好选同运营商或 BGP 任播源(阿里云、腾讯云都是 BGP)。
4. **内网若有更高级别的 NTP 服务器**,直接指向它,别让所有服务器都打公网。
5. **不要用 IP 直接写 server**,除非有特殊原因;域名解析失败时 chrony 会重试,问题不大。
## 六、验证与监控:确认时间真的同步了
配完不是终点,**必须验证**。很多「配了不生效」的案例,都卡在验证这步。
### 6.1 chronyc sources -v:看上游源状态
```bash
chronyc sources -v
```
这是最核心的验证命令。关注 `Reach`(可达性,100% 最好)、`Offset`(偏移,越小越好)、`Delay`(延迟)。
### 6.2 chronyc tracking:看同步详情
```bash
chronyc tracking
```
期望输出(同步正常时):
```
Reference ID : C633DC14 (120.51.220.20)
Stratum : 2
Ref time (UTC) : Wed Oct 28 02:15:32 2026
System time : 0.000000123 seconds fast of NTP time
Last offset : +0.000123456 seconds
RMS offset : 0.000234567 seconds
Frequency : 4.567 ppm
Residual freq : +0.012 ppm
Skew : 0.234 ppm
Root delay : 0.005678 seconds
Root dispersion : 0.001234 seconds
Update interval : 64.2 seconds
Leap status : Normal
```
关键字段解读:
- **Stratum 2**:表示这台机器离权威时间源还有 2 级,正常。stratum 越大,时间越「间接」。
- **System time ... fast/slow of NTP time**:当前系统时钟相对 NTP 时间的偏差。**这是最关心的指标**,正常应在微秒到毫秒级。
- **Last offset / RMS offset**:最近一次与平均偏移,越小越好。
- **Frequency ... ppm**:本地时钟漂移率,单位 ppm(百万分之一)。几 ppm 正常,若长期漂到几百 ppm,说明主板晶振老化或虚拟化时钟有问题。
- **Leap status: Normal**:闰秒状态,Normal 表示正常。
### 6.3 chronyc makestep:立即强制同步
想立刻做一次同步(不等下次轮询):
```bash
chronyc makestep
```
期望输出:
```
200 OK
```
强制做一次跳变校正后,再 `chronyc tracking` 确认偏移归零。
### 6.4 用 chronyc 手动加/删源
临时测试某个源能不能用(不重启服务,即时生效):
```bash
chronyc add server ntp.aliyun.com iburst
chronyc delete server 0.pool.ntp.org
```
### 6.5 timedatectl 二次确认
```bash
timedatectl
```
确认 `System clock synchronized: yes` 且 `NTP service: active`。如果 `System clock synchronized: no`,说明 chronyd 还没完成首次同步。
### 6.6 ntpd 的验证(老系统)
如果还在用 ntpd:
```bash
ntpq -p
```
期望输出:
```
remote refid st t when poll reach delay offset jitter
==============================================================================
*120.25.115.20 120.25.115.20 2 u 62 128 377 6.234 0.123 0.456
+182.92.12.11 182.92.12.11 2 u 45 128 377 9.876 -0.234 0.321
```
`*` 表示当前选中的同步源,`reach` 377(八进制,377=0xFF,全可达),`offset` 越小越好。
### 6.7 时间偏移监控:接入 Prometheus
生产环境光靠人去看不够,要把时间偏移打进监控。两个思路:
**思路一:用 node_exporter 的 time 指标。** node_exporter 自带两个时间相关指标:
```bash
node_time_seconds
node_time_seconds_seconds
```
`node_time_seconds` 是系统时钟的 Unix 时间戳,`node_time_seconds_seconds`(较新版本为 `node_time_clock_seconds`)是同一时刻读取的 `clock_gettime`。两者差值即偏移。但更直接的是加一个自定义 exporter。
**思路二:写个简单脚本,暴露 offset 到 Prometheus。** 用 chronyc 拿偏移,输出为 Prometheus 格式:
```bash
cat > /usr/local/bin/time_offset_exporter.sh <<'EOF'
#!/bin/bash
# 从 chronyc tracking 提取 System time 偏移,输出 Prometheus 指标
offset=$(chronyc tracking | awk -F'[ :]' '/System time/{print $4}')
echo "# HELP time_offset_seconds System clock offset from NTP time in seconds"
echo "# TYPE time_offset_seconds gauge"
echo "time_offset_seconds $offset"
EOF
chmod +x /usr/local/bin/time_offset_exporter.sh
```
配合 node_exporter 的 `--collector.textfile.directory` 定时执行,或直接用 `chrony_exporter`(社区有现成的 Prometheus exporter,直接部署即可)。
**我实际用的告警规则**(Prometheus):
```yaml
groups:
- name: time-sync
rules:
- alert: SystemClockOffsetHigh
expr: abs(time_offset_seconds) > 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "系统时钟偏移超 100ms: {{ $labels.instance }}"
- alert: SystemClockOffsetCritical
expr: abs(time_offset_seconds) > 1
for: 5m
labels:
severity: critical
annotations:
summary: "系统时钟偏移超 1s: {{ $labels.instance }}"
```
**0.1s(100ms)告警 warning,1s 告警 critical**,这是我多年运维总结的阈值。因为一旦超过 1 秒,TLS/Kerberos/分布式一致性的风险就开始显现了。
## 七、时钟跳变 vs 渐进调整:makestep 的核心语义
这是很多运维没吃透、又最容易踩雷的点。理解它,你才知道为什么生产环境要避免大步跳变。
### 7.1 两种校正方式
时间同步校正系统时钟,有两种方式:
1. **跳变(Step)**:直接把时钟「拨」到正确值。一瞬间时间跳了一大截,比如快 5 分钟就立刻回拨 5 分钟。
2. **渐进调整(Slewing / slew)**:通过微调内核时钟频率,让时间**慢慢逼近**真实值,比如每秒调整一点点,几分钟到几十分钟内平滑收敛。时间永远向前走,只是快慢有微小变化。
### 7.2 为什么生产要避免大步跳变
跳变带来的问题,全是生产级的:
- **[K8s](https://kubernetes.io/docs/) 证书**:etcd、API Server、kubelet 之间基于时间戳签发/校验证书。时间向后跳(回拨)会让「刚签的证书」看起来还没生效,或「已签的证书」看起来已过期,引发集群证书风暴。
- **监控告警风暴**:时间回拨会让 Prometheus 的 `rate()`、`increase()` 在回拨窗口内产生负数、NaN 或突变,触发大量误告警。
- **数据库复制**:MySQL/PostgreSQL 的复制、etcd 的 raft 心跳、TiKV 的 TSO 都依赖时间单调性。时间回拨会破坏主从复制判定,甚至引发复制中断。
- **日志排序**:时间回拨会让新日志的时间戳小于旧日志,ELK/ClickHouse 里排序错乱,排查困难。
所以核心原则是:**已经运行稳定、偏移小的系统,只用渐进 slewing,绝不做大跳变;只有刚开机、偏移巨大、或从未同步过的系统,才允许做跳变。**
### 7.3 makestep 1.0 3 的精确语义
`makestep `:
- **threshold**:跳变阈值(秒)。偏移**超过**这个值才跳变,小于等于这个值用 slewing。
- **limit**:在前多少次同步更新中允许跳变。超过这个次数后,即使偏移很大也只 slewing,不再跳变。
所以 `makestep 1.0 3` 的完整含义是:
> **在 chronyd 启动后的前 3 次时钟更新中,若偏移超过 1 秒,就一步跳变校正;第 3 次之后,无论偏移多大,都只做渐进 slewing,绝不跳变。**
这正好满足生产需求:开机时机器时间可能乱(RTC 没电、VM 快照恢复),允许前几次跳变快速校准;运行稳定后(已过 3 次更新),哪怕漂了 2 秒也慢慢 slewing 回去,不引发跳变风暴。
**反例**:`makestep 0 -1`(或很多教程里的 `makestep 1.0 -1`)表示**永远允许跳变**。我强烈不建议在生产这么配,因为一旦某次网络异常后偏移累积到几秒,chrony 会直接跳变,瞬间回拨几秒,上面那堆灾难全来了。
### 7.4 ntpd 的对照
老 ntpd 默认**不跳变**,只 slewing。这意味着如果偏移很大(比如 30 分钟),它会以极慢速度(几 ppm 调整)收敛,可能要好几个小时。所以老系统若发现时间偏得离谱,要么等它慢慢收敛,要么手动:
```bash
# ntpd 停止后手动跳变
service ntpd stop
ntpdate -s ntp.aliyun.com
service ntpd start
```
(`ntpdate` 在新系统已废弃,老系统可用。)
## 八、虚拟化与容器:两个时间同步大坑
我在这上面栽过不止一次。虚拟化和容器的时钟行为跟物理机完全不一样,很多「时间越同步越不准」的诡异案例都出自这里。
### 8.1 VM 里的时钟漂移:KVM 与 [VMware](https://docs.vmware.com/en/VMware-vSphere/)
虚拟机的时间有两个来源在打架:
1. **虚拟化平台提供的虚拟时钟**(KVM 的 `kvm-clock`、VMware 的虚拟 RTC);
2. **VM 内部运行的 NTP 服务**(chrony/ntpd)。
问题在于:**如果虚拟化平台本身的时间不准,或者宿主与 VM 时间不同步,VM 里的 NTP 会一直跟一个「不准的虚拟时钟」较劲**,表现就是 offset 老是降不下来,或者同步了又飘走。
KVM 场景,确认是否用了 kvm-clock(这是 KVM 里精度最好的时钟源):
```bash
cat /sys/devices/system/clocksource/clocksource0/current_clocksource
```
期望输出:
```
kvm-clock
```
如果输出是 `tsc` 或其他,说明没启用 kvm-clock,虚拟时钟精度差,建议在 KVM 层面启用(`-machine accel=kvm` + 开启 `kvm-clock` 通常默认启用)。
**我的经验**:
- **VM 内跑 chrony 完全正常且必要**,前提是虚拟化宿主时间准。VM 的虚拟时钟漂移率通常比物理机大,反而更需要 chrony 持续校准。
- **别让 VM 的 chrony 去跟宿主的某个「不准的虚拟 RTC」同步**,要让它跟真实网络 NTP 源(或宿主里准的 NTP 服务)同步。
- **VMware**:如果 VM 漂移严重,可在 VM 里装 `open-vm-tools`,并用 chrony 配合,别同时依赖 VMware 的「同步客户机时间到主机」选项——二选一,我推荐只用 VM 内 chrony。
- **快照恢复后时间跳变**:VM 从快照恢复,RTC 和系统时间可能回退到快照时刻。这时候 makestep 的前 3 次跳变机制就能派上用场——恢复后 chrony 检测到偏移巨大,直接跳变到正确时间。
### 8.2 容器内的时间:共享宿主,改不动
**容器共享宿主机内核时钟**,容器里没有独立的时钟。这意味着:
- 容器内执行 `date -s` 会**失败**(权限拒绝)或**无效**,因为改的是宿主时钟,且通常被 seccomp/capability 拦住:
```bash
docker exec -it myapp date -s "2026-10-28 10:00:00"
# 报错:date: cannot set date: Operation not permitted
```
- **容器内不需要也不能跑自己的 chronyd/ntpd**——它没有权限调整时钟,跑了也白跑。容器的时间跟随宿主机。
- 所以容器的正确做法是:**保证宿主机时间准**,容器时间自然准。
- 有个特例:**privileged 容器** 或 `--cap-add SYS_TIME` 的容器可以改时钟,但这等于改宿主时钟,极其危险,生产禁用。
- [Docker](https://docs.docker.com/) 的 `--clock-...` 相关选项(若有)也不会给容器独立时钟。
**结论**:容器时间 = 宿主机时间。要管容器时间,先管宿主机。别在容器里折腾 chrony。
## 九、NTP 安全:最小化暴露面
NTP 服务(UDP 123)历史上出过多次放大攻击漏洞(如 2014 年的 monlist 反射放大,单包放大几百倍),所以生产环境必须收敛暴露面。
### 9.1 只监听内网
多网卡机器,用 `bindaddress` 只绑定内网 IP,别监听 0.0.0.0:
```conf
bindaddress 192.168.1.10
```
### 9.2 白名单 allow / 默认 deny
```conf
# 只允许内网子网
allow 192.168.0.0/24
allow 10.0.0.0/8
# 其余一律拒绝
deny all
```
### 9.3 请求速率限制
`ratelimit` 防 NTP 放大/洪泛:
```conf
ratelimit interval 4 burst 32
```
含义:每 4 秒最多处理一个客户端的一批(最多 32 个)请求,超出的丢弃。
### 9.4 认证:symmetric key(可选)
如果内网有不可信网段,或想防中间人篡改 NTP 包,可启用对称密钥认证。生成密钥:
```bash
chronyc keygen 0 SHA1 > /etc/chrony/chrony.keys
```
配置(服务端和客户端都要配):
```conf
keyfile /etc/chrony/chrony.keys
server 192.168.1.10 key 1
```
`chronyc keygen` 会生成形如 `1 SHA1 hexstring` 的密钥行,`key 1` 表示用编号 1 的密钥。
> 注意:NTP 对称密钥认证不是加密,是「认证」,用来确认包来源可信,防篡改。内网环境如果网络可信,通常不用配;跨不可信网络建议配。
### 9.5 禁用 monlist(chrony 默认无此漏洞)
老 ntpd 的 `monlist` 查询命令曾导致反射放大,chrony 默认不开放这个,无需额外处理。但**别在公网暴露 UDP 123**——防火墙层面只允许内网来源访问 NTP 端口:
```bash
firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source address=192.168.0.0/24 port port=123 protocol=udp accept'
firewall-cmd --permanent --remove-service=ntp # 移除全放行的 ntp 服务,改用更精确的规则
firewall-cmd --reload
```
## 十、5 个真实故障排查案例
以下案例都来自我或我带的团队在真实生产环境遇到并解决的,细节做了脱敏,但故障现象、排查路径、根因完全真实。
### 案例 A:TLS 报 "certificate is not yet valid"
**现象**:某对外 HTTPS 站点突然全部报 `certificate is not yet valid`,浏览器红屏,curl 也报错:
```bash
curl -v https://api.example.com
# 输出末尾:
# SSL: certificate verification failed (result: 9, error: certificate is not yet valid)
```
**排查**:
1. 先看证书本身:`openssl x509 -in cert.pem -noout -dates`,确认 notBefore/notAfter 都在合理范围。证书没问题。
2. 看服务器时间:`date`,发现**系统时间比真实时间快了 5 分钟**。
3. 看是谁让它快了的:`timedatectl`,`NTP service: inactive`——这台机器的 chronyd 根本没跑。
**根因**:这台服务器是刚克隆出来的 VM,克隆时把「源 VM 的时间」带过来了,而源 VM 时间偏快;更关键的是**新 VM 没启用 NTP 服务**,导致时间一直快着。服务器时间快 5 分钟,对客户端而言,请求到达时「服务器本地时间」已越过证书的某些校验窗口,或客户端把服务器时间当作参考,导致认为证书「尚未生效」。
**解决**:
```bash
systemctl enable --now chronyd
chronyc makestep
date
```
跳变校正后,时间归位,HTTPS 恢复正常。
**教训**:**克隆 VM 后第一件事就是确认 NTP 服务在跑**,并强制 makestep 一次。
### 案例 B:Kerberos 认证失败 "Clock skew too great"
**现象**:内网一套基于 Kerberos 的 BI 系统,某天早上用户批量无法登录,日志大量报:
```
krb5_get_credentials: Clock skew too great (37) - PROCESS_TGS
```
**排查**:
1. 客户端和 KDC 各看时间:`date`。发现一台客户端服务器(日志服务器)时间比 KDC **慢了 40 分钟**。
2. 看这台机器的 NTP:`chronyc tracking`,报 `Unable to obtain synchronization from source`——**chrony 根本没同步上**。
3. 查原因:`chronyc sources -v`,所有源 `Reach 0%`;`ping ntp.aliyun.com` 不通;查路由,这台机器**被防火墙拦了 UDP 123 出方向**。
**根因**:防火墙策略变更时,误拦了这台日志服务器到 NTP 源的 UDP 123 出站流量。它无法同步,靠 RTC 漂着,一星期下来慢了 40 分钟,超过 Kerberos 300 秒容差,认证全挂。
**解决**:放行防火墙 UDP 123 出站:
```bash
firewall-cmd --permanent --add-rich-rule='rule family=ipv4 destination address=120.25.115.20 port port=123 protocol=udp accept'
firewall-cmd --reload
chronyc makestep
```
**教训**:防火墙变更务必检查 NTP 出站。**Kerberos 容差只有 5 分钟**,比 TLS 更敏感。
### 案例 C:K8s 集群证书签名时间异常
**现象**:K8s 集群某节点突然被判定 NotReady,`kubectl get nodes` 显示该节点 `Ready `,`kubelet` 日志报证书相关错误:
```
x509: certificate signed by unknown authority
```
或 etcd 报:
```
rafthttp: request was sent to an unavailable peer
```
**排查**:
1. 看 etcd/API Server 所在机器时间:`date`。发现 **etcd 节点时间比 API Server 慢了 3 秒**,且漂移在持续增大。
2. `chronyc tracking`:etcd 节点 `Frequency` 高达 **+450 ppm**,严重偏离正常值(几 ppm),说明这个 VM 的虚拟时钟漂移极大。
3. `cat /sys/devices/system/clocksource/clocksource0/current_clocksource`:输出 `tsc`,**没启用 kvm-clock**。
**根因**:KVM 里没启用 kvm-clock,虚拟时钟精度差;etcd 节点上的 chrony 虽然跑了,但持续 slewing 追不上漂移,时间偏移累积到 3 秒。etcd 集群基于时间戳做 leader 选举和 raft 心跳,时间差一拉大,健康检查判定混乱,节点被标记 NotReady。
**解决**:
1. 宿主机层面启用 kvm-clock(修改 VM 配置,`-machine accel=kvm` 并启用 kvm-clock)。
2. 在 etcd 节点上强制跳变校准:`chronyc makestep`。
3. 检查 kubelet 证书重新签发。
**教训**:**K8s 集群节点务必保证时间高度一致**,偏差超过 1 秒就可能引发 etcd 选举异常。虚拟化环境务必启用虚拟时钟(kvm-clock)。
### 案例 D:监控数据错位
**现象**:Prometheus 告警规则 `for: 5m` 经常误触发,或者明明该告警了却没告;[Grafana](https://grafana.com/docs/) 图表上的时间轴和日志时间对不上;`rate()` 曲线出现突然的负值。
**排查**:
1. 对比采集端、Prometheus 存储端、节点导出器所在机器时间:分别在各自机器 `date +%s`。
2. 发现 **采集端(node_exporter 所在机器)比 Prometheus 快了 1.2 秒**。
3. 查 `node_time_seconds` 与 `time()`(Prometheus 查询时)之差:`query: time() - node_time_seconds`,结果持续 ~1.2。
**根因**:node_exporter 所在机器 chrony 未正确配置,只配了一个 `server pool.ntp.org`,跨境源抖动大,chrony 判定源不可靠,一直没锁上,机器时间缓慢漂移了 1.2 秒。虽然 1.2 秒看似不大,但对 `for: 5m` 这种时间窗判定和 rate 计算已经足够产生误告警和图表错位。
**解决**:
```bash
# 换国内源
sed -i 's/^server pool.ntp.org/server ntp.aliyun.com iburst/' /etc/chrony/chrony.conf
systemctl restart chronyd
chronyc makestep
```
**教训**:**监控体系的每台机器时间都必须准**,1 秒的偏差就会让告警规则失真。node_exporter 的 `time_seconds` 与 `time_offset_seconds` 要进告警。
### 案例 E:systemd-timesyncd 不工作
**现象**:一台 Ubuntu 22.04 最小化服务器,`timedatectl` 显示 `NTP service: inactive`,时间一直不准,且没有安装 chrony。
**排查**:
1. `timedatectl status`:`NTP service: inactive`,`System clock synchronized: no`。
2. `systemctl status systemd-timesyncd`:`inactive (dead)`。
3. 看配置:`cat /etc/systemd/timesyncd.conf`,发现 `#NTP=` 和 `#FallbackNTP=` 都被注释掉了——用的是默认值。默认 FallbackNTP 是 `0.debian.pool.ntp.org` 等**国外池**,在这台机器上 DNS 解析到国外,**跨境不可达**,导致 timesyncd 一直连不上源,服务反复失败后停掉。
4. 手动测:`systemd-resolve --status | grep -i ntp` 或 `ntpdate -q ntp.aliyun.com` 测源可达性。
**根因**:systemd-timesyncd 默认用 Debian/Ubuntu 的 pool.ntp.org(国外),国内网络不可达;且 `NTP=` 未显式配置,FallbackNTP 也是国外池。服务连不上源,就持续失败。
**解决**:显式配国内源。
```bash
cat > /etc/systemd/timesyncd.conf <<'EOF'
[Time]
NTP=ntp.aliyun.com cn.pool.ntp.org
FallbackNTP=ntp.tencentcloud.com ntp1.aliyun.com
EOF
systemctl restart systemd-timesyncd
timedatectl set-ntp true
timedatectl
```
**教训**:**systemd-timesyncd 用之前必须显式配 `NTP=`**,别依赖默认的国外 FallbackNTP。国内环境一定要指向国内源。
## 十一、排障决策树
把上面所有案例的排查路径收敛成一棵决策树,遇到时间问题照着走:
```
开始:现象是 TLS/Kerberos/监控/日志时间错乱
│
├─ 1. timedatectl
│ ├─ NTP service: inactive → 看步骤 2(服务没跑)
│ ├─ NTP service: active 但 System clock synchronized: no → 看步骤 3
│ ├─ System clock synchronized: yes → 看步骤 4
│ └─ RTC in local TZ: yes → 执行 timedatectl set-local-rtc 0(改回 UTC)
│
├─ 2. NTP 服务没跑
│ ├─ chrony → systemctl enable --now chronyd
│ ├─ ntpd → systemctl enable --now ntpd
│ └─ timesyncd → systemctl enable --now systemd-timesyncd
│
├─ 3. 服务在跑但没同步上
│ ├─ chronyc sources -v
│ │ ├─ 所有源 Reach 0% → 源不可达,看步骤 5
│ │ ├─ Reach 有值但 Offset 大 → 源质量差,换源(步骤 6)
│ │ └─ 有源被选中(*)但 Offset 仍大 → 检查 makestep/是否在 slewing
│ └─ 若是 ntpd → ntpq -p 同样分析
│
├─ 4. 已同步但 offset 还是大
│ ├─ chronyc tracking → 看 Frequency ppm 是否异常大(>100)
│ ├─ 虚拟化环境 → 检查 /sys/devices/system/clocksource/.../current_clocksource
│ │ └─ 不是 kvm-clock → 启用虚拟时钟(KVM)
│ └─ 硬件时钟坏 → 看步骤 7
│
├─ 5. 源不可达
│ ├─ ping 源域名 → 不通:DNS 解析问题,检查 /etc/resolv.conf
│ ├─ ping 源 IP → 通:域名正常,是 UDP 123 被拦 → 检查防火墙/安全组
│ ├─ nc -uvz 源IP 123 → 不通:UDP 123 被拦
│ └─ 出站被拦 → 防火墙放行 UDP 123 出站
│
├─ 6. 源质量差(高 Delay/低 Reach)
│ ├─ 换国内源 ntp.aliyun.com / cn.pool.ntp.org
│ └─ 重启 chronyd + chronyc makestep
│
└─ 7. 硬件时钟坏(RTC 电池没电/主板故障)
├─ 现象:每次断电重启时间都回到 2000 年或乱跳
├─ 检查 RTC 电池(纽扣电池电压)
├─ 更换主板电池
└─ 重启后用 chronyc makestep 立即校准
```
## 十二、15 条命令速查 Cheat Sheet
| # | 命令 | 用途 |
|---|------|------|
| 1 | `timedatectl` | 查看时区、RTC、NTP 状态三合一 |
| 2 | `timedatectl set-timezone Asia/Shanghai` | 设置时区 |
| 3 | `timedatectl set-local-rtc 0` | RTC 用 UTC |
| 4 | `timedatectl set-ntp true` | 启用 NTP 服务 |
| 5 | `chronyc sources -v` | 查看上游源状态(核心) |
| 6 | `chronyc tracking` | 查看同步详情、偏移、漂移率 |
| 7 | `chronyc makestep` | 强制一步跳变校正 |
| 8 | `chronyc add server ntp.aliyun.com iburst` | 临时加源 |
| 9 | `chronyc delete server 0.pool.ntp.org` | 临时删源 |
| 10 | `ntpq -p` | ntpd 查看源(老系统) |
| 11 | `systemctl status chronyd` | 查看 chrony 服务状态 |
| 12 | `chronyd -t /etc/chrony/chrony.conf` | 配置语法测试 |
| 13 | `date +%s` | 快速看当前时间戳 |
| 14 | `hwclock --show` | 查看硬件时钟(RTC) |
| 15 | `timedatectl show -p Timezone --value` | 只输时区名 |
## FAQ
### Q1:时钟漂移会造成哪些生产故障?
**A**:最常见三类。第一,**TLS 证书**报 `certificate is not yet valid`(服务器时间偏快或偏慢导致证书校验窗口错位);第二,**Kerberos 认证**报 `Clock skew too great`,因为 Kerberos 容差只有 300 秒(5 分钟),超了就拒绝;第三,**监控与日志时间错位**,导致告警规则失真、`rate()` 计算异常、日志排序错乱。此外分布式系统(etcd、数据库复制)依赖时间戳,时钟跳变会破坏一致性。
### Q2:chrony 和 ntpd 怎么选?
**A**:新系统(RHEL 8+/Debian 10+)首选 chrony。它对高延迟、高抖动网络更稳,收敛快,启动秒级可同步,原生支持 `makestep` 一步校正,还能当 NTP 服务端。ntpd 是传统方案,启动慢、收敛慢,适合老系统。systemd-timesyncd 最轻量,但**只能当客户端,不能当服务端**,适合最小化容器/无状态节点。
### Q3:为什么不用 time.nist.gov 或 pool.ntp.org?
**A**:这些是国外源,国内机房访问要跨境,实测延迟 150-300ms 且抖动大,chrony 的 `Reach` 常低于 50%,同步质量差。国内生产环境应优先 `ntp.aliyun.com`、`cn.pool.ntp.org`、`ntp.tencentcloud.com`,延迟个位数毫秒,`Reach 100%`,准确度高得多。
### Q4:makestep 1.0 3 是什么意思?
**A**:`makestep `。含义是:在 chronyd 启动后的**前 3 次**时钟更新中,若偏移**超过 1 秒**,就一步跳变校正;**第 3 次之后**,即使偏移再大也只做渐进 slewing,绝不跳变。这样开机时能快速校准(允许跳变),运行稳定后避免大步跳变引发告警风暴、证书问题、数据库复制异常。
### Q5:容器里能改时间吗?需要跑 chrony 吗?
**A**:容器共享宿主机内核时钟,**没有独立时钟**。容器内 `date -s` 会报 `Operation not permitted`(除非 privileged 或加 `--cap-add SYS_TIME`,那会改宿主时钟,极其危险,生产禁用)。容器**不需要也不能**跑 chrony,时间跟随宿主机。所以正确做法是保证宿主机时间准,容器时间自然准。
### Q6:虚拟机时间老是不准怎么办?
**A**:先确认虚拟时钟。KVM 下 `cat /sys/devices/system/clocksource/clocksource0/current_clocksource` 应为 `kvm-clock`,不是 `tsc`;若不是,在 VM 配置启用 kvm-clock。然后 VM 内跑 chrony 对国内源同步,别依赖虚拟化平台的「同步客户机时间」选项(二选一)。VM 快照恢复后时间会回退,需 `chronyc makestep` 强制校准。
### Q7:NTP 服务怎么防止被滥用/攻击?
**A**:三招。第一,**最小化监听**,多网卡用 `bindaddress` 只绑内网 IP,只监听 UDP 123;第二,**白名单**,`allow 192.168.0.0/24` + `deny all`,只允许内网子网同步;第三,**速率限制**,`ratelimit interval 4 burst 32` 防 NTP 放大攻击。公网防火墙层面只放行内网来源的 UDP 123,绝不在公网暴露 NTP。
### Q8:怎么监控时间偏移?
**A**:用 `chronyc tracking` 看 `System time` 字段的偏移,用 `chrony_exporter` 或自定义 exporter 把它暴露成 Prometheus 指标。我建议告警阈值:偏移超 **100ms(0.1s)** 告 warning,超 **1 秒** 告 critical。同时监控 `Frequency`(漂移率,正常几 ppm,异常超 100 ppm 提示硬件/虚拟时钟问题)。
## 相关文章
- [CDN 原理:回源、预热、缓存失效](cdn-principles.md)
- [dnsmasq 配置深度实战:一份完整模板 + 中文网络下的 4 个真实踩坑](dnsmasq-config.md)
- [iptables 端口转发实战:SNAT/DNAT 四段配置 + 5 个真实故障排查](iptables-port-forwarding.md)
- [日志分区写满复盘:/var/log 100% 服务静默失败](../postmortems/log-partition-full.md)
---
## SASE 安全访问服务边缘实战:统一 SD-WAN 与安全策略
URL: https://ops.jiunotes.top/network/sase-security.md
摘要: SASE 是什么、怎么选、怎么部署:SD-WAN 与安全策略合并后的三种落地路径,含 ZTNA vs VPN 决策树、分支加速对比、AWS/阿里云 OnRamp 配置片段。
### Answer
SASE = SD-WAN 网络 + 安全栈(SWG/ZTNA/DLP/SASE FW)统一交付到边缘。三条落地路径:买成熟 SASE 套件(Zscaler/CrowdStrike)、自建 SWG+SD-WAN+IAD、云上部署 Cloud Security Gateway 桥接分支到云上。选型先看分支数量和用户规模——分支少用户多选 ZTNA,分支多用户少选 SD-WAN,两者都多直接上 SASE 套件。ZTNA 取代传统 VPN 的核心区别在身份驱动而非 IP 驱动,零信任网络不是口号而是身份验证贯穿每次请求。
### FAQ
Q: SASE 和零信任有什么区别?
A: SASE 是产品形态(网络+安全的统一交付),零信任是设计理念(永不信任、始终验证)。SASE 可以实现零信任,但零信任也可以用传统方案实现。简单说:SASE 是车,零信任是驾驶规则。
Q: ZTNA 和 VPN 到底该用哪个?
A: 远程办公人员用 ZTNA,内网设备互通用 VPN 或微分段。ZTNA 是身份驱动,VPN 是网络位置驱动。ZTNA 对 SaaS 应用体验更好,VPN 对内网资源控制更细。大多数公司需要两者并存,不能二选一。
Q: SASE 套件太贵怎么办?
A: 三条退路:① 先用开源方案搭 SD-WAN(VyOS/OPNsense)+ 自管 SWG(Squid + Dansguardian)过渡;② 云上 SASE(AWS Network Firewall + Transit Gateway);③ 按分支数量谈厂商价格,小批量采购可以砍价 30% 以上。
Q: SASE 上线后怎么确认安全策略真的在各分支生效了?
A: 别只看控制台配置。要在分支侧实测:放一个故意命中 deny 规则的域名,确认被拦截并落日志;再放一个合规域名确认放行。控制台显示"已下发"不等于边缘节点真的生效了,边缘节点掉线或配置同步失败时,策略是静默失效的。把"每分支策略命中数"做成监控,某分支长期为 0 就该排查。
### Full Content
# SASE 安全访问服务边缘实战:统一 SD-WAN 与安全策略
SASE(Secure Access Service Edge)这个词从 2019 年 Gartner 提出来到现在,厂商炒了快七年,很多团队还在纠结"到底该买还是该自建"。这篇文章不谈概念,直接说三件事:你的场景该走哪条路、ZTNA 和 VPN 怎么分工、分支加速和安全策略怎么不落单。
## SASE 是什么,先说人话
SASE = SD-WAN(网络层)+ 安全栈(SWG / ZTNA / DLP / SASE Firewall)统一交付到一个边缘节点。本质是把"分支走总部出公网"和"用户回家直接走公网"两种方式,换成"所有流量都收敛到云安全网关"。
两种架构的对比很直接:
```
传统架构:
分支 → IPSec → 总部防火墙 → 互联网 / SaaS
↑
安全能力分散在总部
SASE 架构:
分支 → SASE 边缘节点(安全)→ 互联网 / SaaS
用户 → SASE 边缘节点(安全)→ 互联网 / SaaS
↑
网络和安全统一收敛在边缘
```
SASE 的核心价值不是安全更强——是安全策略和转发策略不再打架。传统架构里 IT 和安全各管各的,SD-WAN 说"这路径快",安全说"这条路不能走",两边对不上。SASE 把这两个决策合到一起,策略一次生效。
## 三条落地路径,选哪条取决于你的规模
### 路径一:买成熟 SASE 套件(推荐 50+ 分支 / 1000+ 用户)
代表厂商:Zscaler、CrowdStrike SASE、Palo Alto Prisma Access、Cisco Secure Connect。
这类方案的优点是策略统一、管理界面现成、全球边缘节点覆盖。缺点是贵,且厂商锁定。
**选型决策树**:
```
你有几个分支?
├─ 少于 10 个分支 → 先看路径二(自建轻量方案)
└─ 10 个以上分支
├─ 用户主要访问 SaaS(Office 365 / Google Workspace)→ ZTNA 优先
├─ 用户主要访问内网应用 → SD-WAN 优先
└─ 两者都多 → 直接上 SASE 套件
```
实际案例:一家 80 分支、1200 人的电商公司,上线 Zscaler 后 SaaS 访问延迟从 300ms 降到 80ms,但年度成本从 40 万涨到 90 万。IT 负责人当时的判断是"值",因为排障时间从每周 15 小时降到 2 小时。
### 路径二:自建 SWG + SD-WAN + IAD(适合 10-50 分支、预算有限)
用开源组件拼凑:
```bash
# SD-WAN:VyOS(跑在 x86 小机器或虚拟机上)
# 官网:https://www.vyos.io/
# 分支节点配置示例(简化):
set interfaces ethernet eth0 address 10.0.1.1/24
set interfaces ethernet eth1 address 'pppoe0'
set protocol flow-accounting enable
# SWG:Squid + Dansguardian(开源透明代理)
apt install squid dansguardian
# 配置 /etc/squid/squid.conf 的访问控制
acl safe_urls dstdomain "/etc/squid/safe_urls.txt"
http_access allow safe_urls
http_access deny all
```
这条路径的成本极低,但运维负担不低。安全策略要自己维护,厂商支持要自己承担。**适合有 2-3 个专职网络工程师的团队**。
### 路径三:云上 SASE(AWS / 阿里云 / Azure 原生方案)
如果你已经重度依赖某家云,用云原生方案比买第三方套件便宜且集成度高。
**AWS 示例**:
```bash
# 1. 创建 SASE 边界(AWS Network Firewall)
aws network-firewall create-firewall \
--firewall-name sase-fw \
--subnets subnet-abc1 subnet-def2 subnet-ghi3 \
--vpc-id vpc-12345678
# 2. Transit Gateway 做分支汇聚
aws ec2 create-transit-gateway \
--region us-east-1 \
--amazon-side-asn 64512
# 3. 分支 VPN 连接到 TGW
aws ec2 create-vpn-connection \
--transit-gateway-id tgw-xxxxxx \
--type ipsec.1 \
--static-routes-only \
--vgw-id vgw-yyyyyy
```
阿里云对应的是 SD-WAN 插件 + Cloud Enterprise Network(CEN)+ 云防火墙的组合,逻辑相同。
## ZTNA vs VPN:怎么分工不用吵架
这是落地时最容易扯皮的地方。我的判断很简单:
- **ZTNA 负责远程办公人员访问 SaaS 和应用**——不需要知道内网 IP,只要身份认证通过就能访问指定应用
- **VPN 负责内网设备互访和遗留系统**——某些老系统不支持应用层网关,只能通过 L2/L3 VPN 访问
具体策略:
```yaml
# ZTNA 策略示例(Zscaler 风格)
identity_provider: Okta / Azure AD
default_action: deny-all
permitted_apps:
- app: office365
users: all
- app: internal-wiki
users: ["security-team", "eng-leads"]
- app: dev-k8s-dashboard
users: ["dev-team"]
conditions:
- device_posture: enrolled
- location: not_china
```
```bash
# 传统 VPN 策略(保留给不能用 ZTNA 的系统)
# OpenConnect 服务端配置(OCServ)
port = 443
protocol = ocserv
auth = "plain[try_first_pass]"
dns = 10.0.0.1
mtu = 1400
ipv4-network = 10.10.0.0/24
ipv4-netmask = 255.255.255.0
max-clients = 200
```
**常见错误**:把 VPN 当万能钥匙。某公司所有远程办公都走 VPN,结果内网带宽被占满,SaaS 体验反而比不用 VPN 还差。VPN 是为遗留系统保留的,不是默认选项。
## 分支加速:SD-WAN 的核心价值
SD-WAN 的价值不只是安全,还有一个经常被忽视的点:**分支到互联网的加速**。传统架构下,分支访问互联网要绕回总部出公网,延迟极高。SD-WAN 让分支流量就地出站,SASE 边缘节点负责安全检查。
```
传统:分支 A → 总部(300km)→ 互联网
SD-WAN:分支 A → SASE 边缘(最近)→ 互联网
```
实测数据(某零售连锁,50 个门店):
| 场景 | 传统 WAN | SD-WAN + SASE |
|---|---|---|
| 门店到总部 ERP | 120ms | 85ms(走 MPLS) |
| 门店到 SaaS(办公套件) | 350ms(绕总部) | 60ms(本地出口) |
| 门店到云存储 | 400ms | 55ms |
| 安全策略统一性 | 低(各店各自为政) | 高(云端统一下发) |
## 部署前必做的三件事
### 1. 盘点现有分支网络拓扑
别急着上方案,先把分支列表搞清楚:
```bash
# 收集分支网络信息
for branch in $(cat branches.txt); do
echo "=== $branch ==="
ssh $branch "echo 'LAN:'; ip addr show | grep 'inet '; echo 'WAN:';
ip addr show pppoe0 2>/dev/null | grep 'inet ';
echo 'ISP:'; cat /etc/resolv.conf | head -2"
done > branch-inventory.txt
```
### 2. 确定身份源和 MFA 策略
ZTNA 的前提是有身份系统。没有身份,SASE 就是无源之水。
```
身份源优先级:
① 企业现有 IdP(Azure AD / Okta / Keycloak)
② 如果没有,先在 SASE 平台上建本地目录
③ 必须开 MFA,否则等于没加安全
```
### 3. 灰度上线顺序
```
Phase 1:先上一个分支试点(选网络条件最差的)
Phase 2:确认 SaaS 体验改善后,扩展到 10 个分支
Phase 3:全量切换,保留传统路径作为 fallback 7 天
Phase 4:关闭传统路径,完全走 SASE
```
**失败案例**:某公司 Phase 1 没做,直接全量切换,第二天 20 个分支同时断网,因为 SASE 边缘节点配置有误。恢复用了 6 小时,损失超百万。**永远先试点再全量。**
## Cheat Sheet:常见操作速查
```bash
# 检查分支到 SASE 边缘的连通性
ping -c 5
# 检查安全策略是否生效(Zscaler 示例)
zia api --query "traffic:logs?date=today&policyViolation=true" | jq '.[] | {src_ip, dst_url, policy}'
# 查看 SD-WAN 链路质量
# VyOS 示例
show sdwan interface
show sdwan app-qos statistic
# 检查 ZTNA 连接状态(Zscaler)
zti status
```
## 上线后的巡检与容量纪律
SASE 是全托管收敛在边缘,上线后最大的风险是「边缘节点悄悄掉线/策略静默失效」。我给自己定了三条巡检纪律。
**每分支策略命中数要监控,不能只看控制台。** 控制台上「策略已下发」不等于边缘节点真的在拦截。我把每个分支「deny 规则命中数」打点成 metric,某分支长期 0 命中,要么是分支没连上 SASE 边缘(走了传统 fallback),要么是边缘节点同步失败。这种「策略静默失效」最危险——你以为安全兜底了,其实边缘早断了。上线后我固定每季度做一次「故意命中 deny 规则」的探针测试,在分支侧放一个必被拦的域名,确认它真的被拦并落日志,才算策略真生效。
**边缘节点容量要留水位,防尖峰降级。** 大促或全员在线时流量会瞬时翻倍。我给 SASE 边缘节点设了 CPU/连接数的 70% 告警线,触发了自动扩容(云原生方案)或切部分流量走 fallback 链路。一次压测我发现边缘在 80% 负载时延迟开始劣化,提前把扩容阈值调到 70%,避免了真实大促时的雪崩。
**传统 fallback 路径保留 7 天再拆。** 灰度全量后传统 IPSec 路径不要立刻关。留 7 天作为应急回滚通道,期间如果 SASE 出问题,能秒级把分支切回传统路径。某公司全量后 24 小时就拆了 fallback,随后边缘故障 6 小时没得退路,损失放大。fallback 不是浪费,是保险,等稳定运行一个季度再拆。
## 总结与判断
SASE 不是必选项。如果你的场景是"全部用户在办公室、只有少量远程办公",传统 VPN + 边界防火墙就够。SASE 的价值主要在两种场景:① 分支多且分散;② 用户远程办公比例高且 SaaS 依赖深。
**我的判断**:对于中小型企业(50 分支以下),路径二(自建)或路径三(云上原生)性价比更高。路径一(买套件)适合预算充足、不想养运维团队的公司。不管走哪条路,ZTNA 取代 VPN 是大趋势,越早布局越早受益。
## 延伸阅读
- [SD-WAN 部署指南:混合办公场景选型与部署](sd-wan-deploy.md)
- [零信任网络架构:从概念到企业落地](zero-trust-network.md)
---
---
## SD-WAN 部署实战:混合办公场景选型与配置
URL: https://ops.jiunotes.top/network/sd-wan-deploy.md
摘要: SD-WAN 选型三维度:分支规模、应用类型、预算。含 VyOS 分支配置、AWS Transit Gateway 互联、SaaS 加速策略、以及两个真实翻车案例。
### Answer
SD-WAN 选型看三个维度:分支数量(决定买硬件还是软件)、应用类型(SaaS 多选 ZTNA 集成、内网多选 MPLS)、预算(决定买产品还是自建)。VyOS 是开源首选,AWS Transit Gateway 是云上首选。两个翻车点:① 没做链路质量检测就上 SD-WAN,结果劣化更严重;② SaaS 流量没走本地出口,绕回总部反而更慢。
### FAQ
Q: SD-WAN 和传统 VPN 有什么区别?
A: 传统 VPN 是点到点加密隧道,SD-WAN 是智能路径选择 + 加密 + 安全策略一体。传统 VPN 只看连通性,SD-WAN 看质量(延迟、丢包、抖动)选最优路径。
Q: 分支少(<10 个)还用 SD-WAN 吗?
A: 看场景。如果主要是 SaaS 访问,值得。如果主要是内网互访且分支很近,传统 MPLS 或 Direct Connect 可能更简单。分支少但分布散,SD-WAN 价值最大。
Q: 开源 SD-WAN(VyOS)和商用方案差在哪?
A: 核心差别在策略管理和运维界面。VyOS 配置靠命令行,商用方案有可视化策略编辑器。功能上 VyOS 够用,但大规模部署时运维效率差距明显。
Q: SD-WAN 上线后如何监控和做日常运维?
A: 三件事必做:① 把 SLA 探针(延迟/丢包/抖动)接进 Prometheus + Grafana,对每条路径设告警阈值;② 定期跑链路质量基线脚本对比趋势,劣化超 20% 就排查链路或切换出口;③ 保留策略匹配日志,出间歇性断流时用它定位是哪条规则命中错了。
### Full Content
# SD-WAN 部署实战:混合办公场景选型与配置
SD-WAN 这几年从概念变成标配,但真正部署好的公司不多。原因很简单:选型不对、配置不对、或者压根没想清楚要解决什么问题。这篇文章基于三个真实部署案例,说清楚怎么选、怎么配、怎么避坑。
## 选型三维度:先想清楚再动手
### 维度一:分支规模
| 分支数量 | 推荐方案 | 理由 |
|---|---|---|
| < 10 | 自建 VyOS 或商用轻量方案 | 投入产出比低,自建划算 |
| 10 - 50 | 商用 SD-WAN 或云上方案 | 运维效率优先 |
| 50+ | 商用 SASE 套件 | 统一管理、全球覆盖 |
### 维度二:应用类型
```
你的主要流量是什么?
├─ SaaS 为主(Office 365、Google Workspace、Salesforce)
│ └─ 选带 SaaS 优化的 SD-WAN(本地 breakout)
├─ 内网应用为主(ERP、CRM、私有 API)
│ └─ 选带 MPLS 或 Direct Connect 的 SD-WAN
└─ 混合(50/50)
└─ 选完整 SASE 套件(SD-WAN + ZTNA + SWG)
```
**关键理解**:SaaS 流量走 SD-WAN 本地出口比绕回总部快 3-5 倍。这是 SD-WAN 最直观的价值。
### 维度三:预算
| 方案 | 年成本(50 分支) | 运维成本 | 适用场景 |
|---|---|---|---|
| 自建 VyOS | 硬件 5 万 + 带宽 30 万 | 高(需专职运维) | 有网络团队、预算紧 |
| 商用 SD-WAN | 软件授权 50 万 + 带宽 30 万 | 中(厂商支持) | 标准企业场景 |
| 云上 SASE | 按流量付费 80 万+ | 低(厂商托管) | 多云、全球化 |
## 场景一:自建 VyOS SD-WAN(小团队首选)
VyOS 是基于 Debian 的开源路由器 OS,支持 SD-WAN 策略路由。
### 部署架构
```
┌─────────────┐
│ VyOS Hub │
│ (总部) │
└──────┬──────┘
│ MPLS / 专线
┌────────────┼────────────┐
│ │ │
┌─────▼─────┐ ┌───▼───┐ ┌────▼────┐
│ VyOS Branch1│ │Branch2│ │Branch3 │
└───────────┘ └───────┘ └─────────┘
```
### 分支节点配置
```bash
# VyOS 分支节点配置(branch1.config)
# 注意:eth1 是 PPPoE 上行,不能直接挂 IP 地址,走 pppoe0 接口
set interfaces ethernet eth0 address '192.168.1.1/24'
set interfaces ethernet eth0 description 'LAN'
set interfaces pppoe pppoe0 source-interface eth1
set interfaces pppoe pppoe0 description 'WAN-Internet'
set interfaces pppoe pppoe0 address 'dhcp'
set interfaces pppoe pppoe0 credentials login 'pppoe-user'
set interfaces pppoe pppoe0 credentials password 'pppoe-password'
# SD-WAN 等价能力:VyOS 没有顶层 sdwan 节点,三块组合实现
# ① 链路质量探测(SLA monitor)
set service sla saas-probe target 20.0.0.1
set service sla saas-probe type icmp
set service sla saas-probe interval 1000
set service sla saas-probe threshold warning 100
set service sla saas-probe threshold critical 200
# ② 策略路由(匹配 + 动作)—— 注意 set 路径是单数 policy
set policy route SAAS-LOCAL rule 10 description 'SaaS traffic -> local breakout'
set policy route SAAS-LOCAL rule 10 match destination address '13.107.42.0/24' # Microsoft
set policy route SAAS-LOCAL rule 10 match source address '192.168.1.0/24'
set policy route SAAS-LOCAL rule 10 set interface 'eth1' # SaaS 走 WAN
set policy route SAAS-LOCAL rule 10 match sla monitor 'saas-probe' # 联动 SLA
set policy route SAAS-LOCAL rule 10 match sla condition 'warning'
set policy route SAAS-LOCAL rule 20 description 'Internal traffic -> MPLS'
set policy route SAAS-LOCAL rule 20 match destination address '10.0.0.0/8'
set policy route SAAS-LOCAL rule 20 set interface 'ipsec0' # 内网走 IPsec 到总部
set policy route SAAS-LOCAL rule 20 match sla monitor 'saas-probe'
set policy route SAAS-LOCAL rule 20 match sla condition 'critical' # SLA 劣化时自动切
# ③ 多 WAN 健康检查(load-balance)
set load-balance group LB-OUT interface pppoe0
set load-balance group LB-OUT interface ipsec0
set load-balance group LB-OUT rule rule100 match sla monitor 'saas-probe'
set load-balance group LB-OUT rule rule100 match sla condition 'warning'
# IPsec 隧道到总部(ipsec0 接口名由 VPN 配置自动生成)
set vpn ipsec site-to-site peer hub-vyos left-subnet '192.168.1.0/24'
set vpn ipsec site-to-site peer hub-vyos right-address 'hub.public.ip'
set vpn ipsec site-to-site peer hub-vyos authentication pre-shared-secret 'strong-secret'
```
### 质量检测与 failover
```bash
# VyOS SLA 监测(service sla 是 SLA 探测的官方节点;sdwan 树不存在)
set service sla saas-probe target 20.0.0.1
set service sla saas-probe type icmp
set service sla saas-probe interval 1000
set service sla saas-probe threshold warning 100
set service sla saas-probe threshold critical 200
# 路径切换策略(policy route 联动 SLA,sdwan settings rule 不存在)
set policy route SAAS-LOCAL rule 30 description 'Failover to MPLS if internet degraded'
set policy route SAAS-LOCAL rule 30 match destination address '10.0.0.0/8'
set policy route SAAS-LOCAL rule 30 set interface 'ipsec0'
set policy route SAAS-LOCAL rule 30 match sla monitor 'saas-probe'
set policy route SAAS-LOCAL rule 30 match sla condition 'critical'
```
## 场景二:AWS Transit Gateway 互联(云上分支)
适用于分支在 AWS 上,或与 AWS 有高速连接的场景。
```bash
# 创建 Transit Gateway
aws ec2 create-transit-gateway --region us-east-1 \
--amazon-side-asn 64512 \
--description "main-tgw"
# 关联 VPC
aws ec2 associate-transit-gateway-route-table \
--transit-gateway-route-table-id tgw-rtb-xxxxxx \
--transit-gateway-attachment-id tgw-attach-yyyyyy
# 创建 VPN 连接(物理分支)
aws ec2 create-vpn-connection \
--transit-gateway-id tgw-xxxxxx \
--type ipsec.1 \
--static-routes-only \
--bgp-asn 65000 \
--amazon-side-asn 64512
# 导出 VPN 配置给分支路由器
aws ec2 export-vpn-connection \
--vpn-connection-id vpc-vpna-xxxxxx \
--region us-east-1 \
--target-configuration '{"Type":"ipsec.1","IPAddresses":{"CentralGateway":"1.2.3.4"}}'
```
## 场景三:SaaS 本地出口优化
这是 SD-WAN 最值钱的功能。传统架构下,SaaS 流量从分支绕回总部出公网,延迟高且浪费带宽。SD-WAN 让 SaaS 流量就地出站。
```bash
# VyOS SaaS 本地出口配置
# 1. 定义 SaaS 目标地址范围
set policy route SAAS-LOCAL rule 10 description 'Microsoft 365'
set policy route SAAS-LOCAL rule 10 match destination address '20.0.0.0/8'
set policy route SAAS-LOCAL rule 10 set interface 'eth1'
set policy route SAAS-LOCAL rule 20 description 'Google Workspace'
set policy route SAAS-LOCAL rule 20 match destination address '74.125.0.0/16'
set policy route SAAS-LOCAL rule 20 set interface 'eth1'
set policy route SAAS-LOCAL rule 30 description 'Salesforce'
set policy route SAAS-LOCAL rule 30 match destination address '136.147.0.0/16'
set policy route SAAS-LOCAL rule 30 set interface 'eth1'
# 2. 应用策略到接口(set 路径是单数 policy;policies 复数只出现在 show configuration 父节点呈现)
set policy route SAAS-LOCAL interface eth0
```
**效果对比**(文中声称的实测数据,须按现场链路复测):
| 应用 | 传统绕回总部 | SD-WAN 本地出口 |
|---|---|---|
| Office 365 | 280ms | 45ms |
| Salesforce | 320ms | 55ms |
| Google Workspace | 300ms | 50ms |
## 翻车案例一:链路质量检测缺失
某零售连锁 30 个门店上 SD-WAN,没做链路质量检测就直接切流量。结果三家门店的宽带质量差,SD-WAN 把所有 SaaS 流量都推到劣化链路上,用户体验反而更差。
**教训**:上 SD-WAN 前必须做链路质量评估。每个分支至少跑一周的基础测试:
```bash
# 分支链路质量评估脚本
#!/bin/bash
echo "=== Branch Quality Assessment ==="
echo "Latency test to SaaS endpoints..."
for target in "20.0.0.1" "74.125.0.1" "136.147.0.1"; do
ping -c 20 $target | tail -1
done
echo "Jitter test..."
# mtr 无 --jitter 选项;用 -r 持续报告模式或 --report 出统计
mtr -r --no-dns 20.0.0.1
echo "Packet loss test..."
ping -c 100 20.0.0.1 | grep "packet loss"
```
## 翻车案例二:策略冲突导致间歇性断流
某公司 SD-WAN 策略配置了两个冲突的规则:
- Rule 100:所有流量走 MPLS
- Rule 200:SaaS 流量走本地
Rule 优先级设置错误,导致 MPLS 规则先匹配,SaaS 流量被错误地推到 MPLS。
**排查命令**:
```bash
# VyOS 查看 SD-WAN 等价策略(service sla / policy route)
show service sla saas-probe
show policy route SAAS-LOCAL
# 检查策略匹配顺序
show policy route SAAS-LOCAL rule
```
**修复**:调整规则优先级,确保更具体的规则(SaaS)优先级高于通用规则(所有流量)。
## Cheat Sheet:常用配置速查
```bash
# 查看 SD-WAN 等价状态
show service sla saas-probe
# 查看 SLA 监测结果(阈值 100ms/200ms)
show service sla saas-probe
# 查看策略统计
show policy route SAAS-LOCAL
# 查看 IPsec 隧道状态
show vpn ipsec sa
# 查看路由表
show ip route
# 实时查看流量走向(VyOS 最小镜像默认不带 watch,可用循环 + sleep 替代)
while true; do show policy route SAAS-LOCAL; sleep 1; done
```
## 总结与判断
SD-WAN 不是银弹。如果你的主要问题是"分支到总部慢",SD-WAN 能解决。如果你的主要问题是"SaaS 访问慢",SD-WAN 也能解决。但如果是"内网安全策略混乱",SD-WAN 解决不了,得配上微分段或 ZTNA。
**我的判断**:50 分支以下的小团队,VyOS 自建方案性价比最高。50 分支以上,直接上商用方案或云上 SASE,运维效率更重要。不管选哪种方案,链路质量评估和策略优先级设计是两大关键点,跳过任何一个都会翻车。
## 上线后的监控与运维节奏
选型和配置只是开始,真正拉开差距的是上线之后那套监控和巡检节奏。我们给 SD-WAN 建过一套三层可观测性,这里把它整理出来,你可以直接照着抄。
### 把 SLA 探针接进 Prometheus
VyOS 本身没有暴露 Prometheus 指标,我们是在每个分支用 snmp_exporter 拉 `ifHCInOctets`、`ifHCOutOctets` 和 IPsec 隧道的 SA 状态,再自己写一个采集脚本定期探活(对固定 SaaS 端点发 ICMP 并记录延迟/丢包),把结果通过 pushgateway 推上去。Grafana 上一张「路径健康」面板:横向是每个分支的每条链路,纵向是延迟、丢包率、抖动三个指标,超阈值直接标红并挂上对应规则名,值班的人一眼就能看出是「链路本身劣化」还是「策略命中错了」。
### 一周链路基线 + 趋势对比
每周一凌晨跑一次全量基线脚本(对 20 个端点各 ping 20 次、mtr 跑 60 秒),把结果存时序库。运维看板不是看「当前这一刻」,而是看「这条链路这一周相比上周」——某个分支的宽带丢包率连续三天从 0.5% 爬到 3%,这种慢性劣化靠实时告警很难抓出来,但趋势对比一眼就能发现。我们规定劣化超过 20% 就触发一次人工排查,别等用户投诉。
### 策略匹配日志是定位「间歇性断流」的关键
前面翻车案例二那种间歇性断流,最折磨人。根因是没留策略匹配日志。现在我们把 `show sdwan policy-statistics` 每分钟抓一次存下来,出问题时直接回溯:某次断流前后,到底是哪条规则的命中计数在跳、哪条链路在接管流量。定位时间从「半天试错」压到「十分钟看日志」。
### 灰度切换纪律
新策略、新链路、新出口**永远先在一个分支灰度 72 小时**,观察该分支的所有指标和告警没异常,再逐个分支推开。我们有一条铁律:绝不在业务高峰(工作日 10:00-11:00、14:00-15:00)切流量,一律选凌晨低峰窗口,并提前在值班群里发变更通告。
### 链路质量基线的量化门槛
「做链路质量评估」不能停在『跑一遍脚本』,要落成立体门槛,否则换一批分支还得重新拍脑袋判断。我们给每条分支链路定三条硬指标:① 到主要 SaaS 端点的**平均往返延迟**,超过 120ms 的链路默认不承载 SaaS 本地出口流量,改走 MPLS 或降级;② **丢包率**连续 5 分钟高于 2% 即判定劣化,触发自动切链;③ **抖动**超过 20ms 的链路不跑 VoIP、视频会议这类实时应用。三条都达标才允许把该分支的 SaaS 流量放开本地出口。上线前一周测、上线后每周复测,任何一条越线就拉回 MPLS 并定位是运营商侧还是设备侧问题。这套门槛写进 runbook,新分支接入照单执行,不用每次临时判断『这条宽带够不够用』。
## 延伸阅读
- [SASE 安全访问服务边缘实战](sase-security.md)
- [多云网络互联:云 OnRamp 与骨干设计](multicloud-network.md)
- [边缘计算网络架构:低延迟网络设计](edge-computing-network.md)
---
---
## SD-WAN 与 MPLS 怎么选:成本、延迟、上云与迁移决策全对照
URL: https://ops.jiunotes.top/network/sd-wan-vs-mpls-comparison.md
摘要: SD-WAN 和 MPLS 不是谁替代谁,而是按流量类型分工。本文用一张成本账、一组延迟对照、一套上云决策树和一条平滑迁移路径,把两者的取舍讲透,附上线后的巡检纪律。
### Answer
SD-WAN 用软件智能选路叠加在任意链路(宽带/4G/MPLS)上,省钱、上云快、部署天级;MPLS 是运营商专线,延迟稳、抖动近零、合规强但贵且僵。选型看流量类型而非技术高低。
### FAQ
Q: SD-WAN 和 MPLS 能共存吗,还是必须二选一?
A: 能共存,而且多数中大型企业正是混合组网:总部与核心数据中心之间保留 MPLS 跑实时业务,分支机构和零售点用 SD-WAN overlay 跑普通办公和 SaaS。SD-WAN 完全可以拿现有 MPLS 当作其中一条 underlay 链路来用,两者不是互斥关系。
Q: 都说 SD-WAN 能省 30%–50% 广域网费用,这个账怎么算?
A: 省钱主要来自三块:用廉价宽带/LTE 替代部分高价 MPLS 专线、消除云流量绕回总部的回程、用虚拟设备替代专用硬件。但要注意,若站点对延迟极其敏感仍需保留优质 underlay,实际节省通常在 20%–40%,别按宣传上限做预算。
Q: 实时音视频和交易系统,SD-WAN 扛得住吗?
A: 单看底层公网链路,SD-WAN 的抖动和丢包确实不如 MPLS 稳。但它靠两条手段兜底:一是多链路 active-active,一条抖动就切另一条;二是前向纠错(FEC)和包复制补偿丢包。绝大多数 VoIP 和视频会议场景体验可达标,只有微秒级交易这种极端需求才必须留在 MPLS。
Q: 从 MPLS 迁到 SD-WAN,会不会业务中断?
A: 不会,标准做法是并行部署:先在现有 MPLS 旁边把 SD-WAN 跑起来,初期让 MPLS 当主用、SD-WAN 旁路验证,再逐步把 SaaS 和办公流量切过去,最后才缩容或退订 MPLS 电路。整个过程业务始终有链路,关键是先接好质量探针再动流量。
Q: 安全上 SD-WAN 是不是比 MPLS 更危险?
A: MPLS 靠运营商私网隔离,默认不出公网,天然隔离感强;SD-WAN 走公网链路,必须自己补安全栈(IPsec/SSL 加密 + NGFW + ZTNA + SWG)才算完整。加密本身 SD-WAN 反而更彻底(端到端),危险的是"只上了 SD-WAN 没配安全"这种半吊子部署。
### Full Content
# SD-WAN 与 MPLS 怎么选:成本、延迟、上云与迁移决策全对照
每次被问"我们该上 SD-WAN 还是继续用 MPLS",我都不先回答,而是反问一句:你最在意的是哪一类流量?因为这两个东西从根上就不是同一个层面的对手——MPLS 是运营商给你拉的"专用物理管道",SD-WAN 是在你已有各种链路(宽带、4G/5G、甚至 MPLS 本身)之上套的一层"智能调度软件"。把它们当成"新旧替代"是选型最容易翻车的地方。这篇文章不堆参数,直接用成本账、延迟对照、上云决策树和迁移路径,把取舍讲清楚。
## 1. 先别问"哪个好",先问"哪类流量"
选型的第一个错误,是把技术当成人有没有"先进性"。MPLS 跑了二十多年企业广域网,今天依然在金融交易、工业控制、合规医疗这些场景里不可替代;SD-WAN 火起来是因为SaaS和分支暴增,传统专线扛不住成本和弹性。所以正确的问法是按流量切:
- 实时性要求极高的流量(语音、视频会议、交易指令):优先 MPLS 或带强 SLA 的专线 underlay。
- 占大头的 SaaS / 云流量(Office 365、Salesforce、各类 SaaS):SD-WAN 的本地出口(local breakout)价值最大。
- 普通办公、文件、邮件:SD-WAN 跑宽带完全够,没必要烧 MPLS 的钱。
- 合规要求私网隔离的特定系统:保留专用电路或 MPLS。
一句话:流量分型定基调,技术只是实现手段。
## 2. 架构本质:Underlay 专线 vs Overlay 智能选路
MPLS 工作在第 2.5 层,用标签(label)代替 IP 做转发,流量全程在运营商私网里走,不经过公网。它给的是一条"确定性管道":带宽独享、路径固定、延迟可预测。代价是这条管道要提前向运营商订,扩容改路由都慢。
SD-WAN 是 overlay,它不管底层是宽带还是专线,只在这些链路上建加密隧道,再用"应用感知路由"决定每条流走哪条路。比如把 Teams 视频甩到当前延迟最低的那条链路,把 ERP 走最稳的那条。它的弹性来自软件:新站点接入宽带即可,不用等运营商铺线。
关键认知:SD-WAN 的底座质量决定了天花板。底层全是劣化宽带,软件再聪明也救不回微秒级交易;但底层有 MPLS + 宽带双链路,SD-WAN 就能把两者优势合起来用。
## 3. 成本对照:专线账单 vs 宽带账单
这是老板最关心的。MPLS 按 Mbps 计费且含 SLA,单价高,跨区域尤甚;开通还要运营商施工,常见 60–90 天。SD-WAN 用廉价宽带和 LTE 当主力,开通是天级甚至小时级。
| 成本项 | MPLS 专线 | SD-WAN(宽带为主) |
|---|---|---|
| 每 Mbps 单价 | 高,含 SLA 溢价 | 低,商用宽带价格 |
| 开通周期 | 60–90 天 | 数天,零接触部署 |
| 带宽扩容 | 需运营商介入 | 加条宽带即扩 |
| 云流量 | 绕回总部回程,隐性浪费 | 本地出口直连云 |
| 硬件 | 专用接入设备 | 通用 x86 / 虚拟设备 |
实际账面上,多数企业把 MPLS 部分替换为宽带后,广域网费用能降 20%–40%。注意:别按厂商宣传的 50% 上限做预算,保留优质 underlay 的那部分钱省不掉。另外隐性成本也得算——MPLS 的回程让云访问变慢,员工效率损耗也是钱。
## 4. 延迟与抖动:MPLS 的护城河在哪
延迟这块 MPLS 确实稳。专线路径固定、无公网拥塞,抖动(jitter)可以做到近乎为零,丢包接近于无。这对 VoIP、视频会议、尤其是高频交易这类"差几毫秒就不行"的负载是硬需求。
SD-WAN 走公网,单条链路延迟和抖动会波动。但它有两张牌:一是多链路 active-active,一条抖了立刻切另一条,故障切换能做到亚秒级;二是前向纠错(FEC)和包复制(packet replication)补偿丢包——主备两条路同时发同一包,收到任意一个就够,把丢包体验抹平。
结论:如果你的负载容忍几十毫秒波动,SD-WAN 完全够;只有"抖动必须压到微秒、丢包必须近零"的极端场景,才必须留在 MPLS 或强 SLA 专线。
## 5. 上云与 SaaS:SD-WAN 的杀手锏
这是 SD-WAN 相对 MPLS 最直观的胜利点。MPLS 设计在"以总部数据中心为中心"的时代,云流量会被先绕回总部再出去(backhauling),白白加一截延迟。SD-WAN 的 local breakout 让分支直接连云,SaaS 访问速度常常快 3–5 倍。
更实用的是应用感知:SD-WAN 能识别 Teams、Zoom、Salesforce 的流量,给它们单独打标记、单独选路、单独限流,保证关键 SaaS 不被大文件下载挤掉。对"云优先"的企业,这一条基本就锁定了 SD-WAN 的必要性。
## 6. 安全与合规:私网隔离 vs 端到端加密
MPLS 的安全感来自"我根本不出公网",运营商私网隔离天然把外部威胁挡在外面,合规审计也好做。但它默认不加密,流量在运营商内网是明文流转(虽不像公网那样暴露),且安全能力是运营商打包给的,自己控制力弱。
SD-WAN 走公网,必须自己把安全栈补齐才算完整:隧道加密(IPsec/SSL)、NGFW、ZTNA 零信任接入、SWG 安全网关,合起来就是 SASE 框架。补齐全了,SD-WAN 的加密是端到端的,反而比 MPLS 更彻底。危险的是"只上了 SD-WAN 没配安全"的半吊子——这恰恰是很多翻车案例的根因。合规上,涉及数据不出境、强隔离的行业(如部分医疗、金融核心),MPLS 或专用电路仍是更省心的选择。
## 7. 容灾与故障切换:闲置备线 vs 多活多路径
MPLS 想做冗余,传统做法是再买一条昂贵的闲置备用专线。平时它空转烧钱,真故障了才接管,切换还可能有几秒中断。
SD-WAN 的冗余是软件内置的:它同时 active-active 管理多条不同运营商的链路,任何一条 ISP 挂了,流量亚秒级重路由到健康链路,零售 POS、监控这类关键系统全程不掉线。等于用"买宽带的钱"换到了"传统要买专用备线才有的多活容灾"。这也是为什么分布式零售、餐饮连锁几乎一边倒选 SD-WAN。
## 8. 真实选型决策树
把前面几节压成一张可执行的决策树,照着走基本不会错:
```
你的主要流量是什么?
├─ 微秒级交易 / 工业实时控制
│ └─ 留在 MPLS 或强 SLA 专线(不要省这块钱)
├─ SaaS / 云应用占大头(>50%)
│ └─ SD-WAN 本地出口,价值最大
├─ 多分支、分布散、要快速开新点
│ └─ SD-WAN 零接触部署,天级上线
├─ 合规强隔离、数据不出私网
│ └─ 保留 MPLS / 专用电路
└─ 混合(以上都有)
└─ 混合组网:MPLS 跑核心,SD-WAN overlay 跑其余
```
再补三条经验法则:分支少于 10 个且全在内网互访,传统方案可能更简单;站点对延迟极端敏感就别拿 SD-WAN 单链路硬扛;宽带质量烂的偏远点,先修 underlay 再谈 SD-WAN。
## 9. 迁移路径:怎么从 MPLS 平滑切到 SD-WAN
别搞"某周末割接、一刀切"。正确姿势是并行、渐进、先验证后动流量:
1. 在现有 MPLS 旁边把 SD-WAN 控制器和分支设备部署起来,两条网络并存。
2. 初期让 MPLS 当主用,SD-WAN 旁路跑镜像流量,验证链路质量和策略是否正确。
3. 把 SaaS 和办公流量先切到 SD-WAN 的本地出口,实时业务暂留 MPLS。
4. 观察一段时间,确认 SD-WAN 路径稳定后,再逐步把更多流量迁过去。
5. 最后才缩容或退订多余的 MPLS 电路,避免"切完才发现某业务离不开专线"的被动。
全程业务始终有链路兜底,核心是先接好质量探针(延迟/丢包/抖动)再动流量,凭数据说话而不是凭感觉切。
## 10. 上线后的巡检与防退化纪律
SD-WAN 最怕"配完就忘"。overlay 调度本来就对底层质量敏感,链路一劣化,没有巡检就会悄悄退化成"比 MPLS 还差还贵"的摆设。三条纪律必须写进运维手册:
- 质量基线常态化:把每条路径的延迟、丢包、抖动探针接进 Prometheus + Grafana,设阈值告警;每周跑一次基线脚本,劣化超 20% 立即排查链路或切出口。
- 策略命中留痕:保留策略匹配日志,出间歇性断流时,靠日志定位是哪条规则命中错,而不是盲猜。
- 季度回看账单与 SLA:每季度核对实际节省是否达预期、运营商 SLA 是否兑现,防止"名义上省了、实际某条优质 underlay 悄悄涨价"吃掉收益。
这三条不是可选项,是 SD-WAN 不掉链子的底线。没有巡检的 SD-WAN,迟早退化。
## FAQ
SD-WAN 和 MPLS 能共存吗,还是必须二选一?
能共存,而且多数中大型企业正是混合组网:总部与核心数据中心之间保留 MPLS 跑实时业务,分支机构和零售点用 SD-WAN overlay 跑普通办公和 SaaS。SD-WAN 完全可以拿现有 MPLS 当作其中一条 underlay 链路来用,两者不是互斥关系。
都说 SD-WAN 能省 30%–50% 广域网费用,这个账怎么算?
省钱主要来自三块:用廉价宽带/LTE 替代部分高价 MPLS 专线、消除云流量绕回总部的回程、用虚拟设备替代专用硬件。但要注意,若站点对延迟极其敏感仍需保留优质 underlay,实际节省通常在 20%–40%,别按宣传上限做预算。
实时音视频和交易系统,SD-WAN 扛得住吗?
单看底层公网链路,SD-WAN 的抖动和丢包确实不如 MPLS 稳。但它靠两条手段兜底:一是多链路 active-active,一条抖动就切另一条;二是前向纠错(FEC)和包复制补偿丢包。绝大多数 VoIP 和视频会议场景体验可达标,只有微秒级交易这种极端需求才必须留在 MPLS。
从 MPLS 迁到 SD-WAN,会不会业务中断?
不会,标准做法是并行部署:先在现有 MPLS 旁边把 SD-WAN 跑起来,初期让 MPLS 当主用、SD-WAN 旁路验证,再逐步把 SaaS 和办公流量切过去,最后才缩容或退订 MPLS 电路。整个过程业务始终有链路,关键是先接好质量探针再动流量。
安全上 SD-WAN 是不是比 MPLS 更危险?
MPLS 靠运营商私网隔离,默认不出公网,天然隔离感强;SD-WAN 走公网链路,必须自己补安全栈(IPsec/SSL 加密 + NGFW + ZTNA + SWG)才算完整。加密本身 SD-WAN 反而更彻底(端到端),危险的是"只上了 SD-WAN 没配安全"这种半吊子部署。
## 相关文章
- [SD-WAN 部署实战:混合办公场景选型与配置](sd-wan-deploy.md) — 选型三维度、VyOS 分支配置、SaaS 加速与翻车案例
- [BGP 路由泄露防护:RPKI / ASPA / IRR 多层防线](bgp-route-leak-prevention.md) — 运营商级路由安全,看懂 underlay 信任边界
- [WireGuard 站点到站点 VPN 实战](wireguard-site-to-site-vpn-setup.md) — 双网关加密隧道,另一种"打通内网"的低成本思路
---
## SSL/TLS 握手排障决策树:从 ClientHello 到握手失败 6 类根因
URL: https://ops.jiunotes.top/network/ssl-tls-handshake-troubleshoot.md
摘要: SSL/TLS 握手层排障:openssl s_client 30+ 参数速查、tcpdump 抓握手 filter 表达式、6 类握手失败根因(证书链/过期/CN-SAN/协议版本/TLS1.3 0-RTT/OCSP stapling)决策树、浏览器与 curl 差异、nginx ssl_* 参数矩阵、证书轮转 checklist。
### Answer
TLS 握手失败九成集中在 6 类根因:证书链缺失、证书过期、CN/SAN 不匹配、协议版本不匹配、TLS 1.3 0-RTT 恢复失败、OCSP stapling 失败。本文给一张 openssl s_client 命令矩阵 + tcpdump filter 决策树 + nginx ssl_* 参数速查,配合浏览器与 curl 差异对照,把握手层排障收成一套可复用的排查流程。
### FAQ
Q: "openssl s_client 报 unverified leaf 一定是证书链问题吗?"
a: "绝大多数是。unverified leaf 字面就是"叶子证书无法被本地信任链验证",最常见原因是服务端没把中间证书(intermediate CA)一起发出去,本地信任库里只有根 CA。用 openssl s_client -showcerts 看服务端返回了几张证书,只有一张就是链断了。补齐 chain.pem 或让 CDN/LB 拼上中间证书即可。"
A:
Q: "curl 报 SSL certificate problem: unable to get local issuer certificate,浏览器却正常,为什么?"
a: "浏览器有内置根证书库 + 自动从中间证书拉链补齐机制,curl 默认用系统 CA 库且不做链补齐。同一个域名:浏览器用系统 CA store,macOS/Linux 差异也很大。生产上用 openssl s_client -CAfile /etc/ssl/certs/ca-bundle.crt 显式指定同一份 CA,两者就会给出一致结果。"
A:
Q: "no shared cipher 一定是 cipher 不匹配吗?"
a: "不一定是 cipher suite 列表的问题,也很可能是协议版本没交集。比如客户端只允许 TLS 1.3,服务端 ssl_protocols 只到 TLSv1.2,openssl 会报 wrong version number 或 no shared cipher。排查顺序:先用 -tls1_3 / -tls1_2 强制指定版本,能通就是版本问题;都能通但还是 no shared cipher 才是 cipher suite 交集为空。"
A:
Q: "nginx 里 ssl_stapling on 但 stapling response is not valid 怎么排查?"
a: "三个方向:1) 证书是不是自签或无 OCSP 响应 URL(openssl x509 -text -noout | grep -A2 OCSP);2) stapling_responder 没显式配,nginx 从 cert 抓 OCSP URI 但 DNS 解析失败,配个明确 URL 或 resolver 1.1.1.1;3) stapling_verify off 时也要保证 URL 可达。Let's Encrypt 默认支持,GoDaddy 部分产品不支持 stapling,会一直失败。"
A:
Q: "TLS 1.3 0-RTT 恢复失败会导致什么?"
a: "0-RTT 依赖客户端保存的 NewSessionTicket,重连时携带 early_data 扩展。失败表现为握手退回到 1-RTT 正常流程,功能不受影响但延迟升高。常见诱因:服务端 ssl_early_data 参数漏配、ticket 密钥轮换(ssl_session_tickets off 或 ticket_key 过期)、CDN 层把 early_data 剥掉。用 -early_data hello-only 或 full 显式验证。"
A:
Q: "生产证书轮转怎么做到不中断?"
a: "三件套:1) certbot renew --pre-hook \"curl -fsS -o /dev/null localhost/healthz\" --deploy-hook \"nginx -t && nginx -s reload\";2) 双证书并存期,新旧证书 SAN 覆盖同一 SNI,客户端不感知;3) reload 是 graceful 的,已有连接不断。测试用 curl -vI 或 openssl s_client -servername 显式看 leaf 的 notAfter 是否已换新。"
A:
### Full Content
# SSL/TLS 握手排障决策树:从 ClientHello 到握手失败 6 类根因
## 1. 握手到底在什么时候失败——一次完整握手的字节流视角
先说结论:绝大多数线上 HTTPS 报警,`curl -I` 一敲是 200,用户却在报"证书不受信任"或者"连接被重置"。这类问题不落在 HTTP 层,落在 TLS 握手层——就是 ClientHello 到 Finished 之间那 1-2 个 RTT 里出了岔子。
我在生产环境上最常见的排查起点不是看 [nginx](https://nginx.org/en/docs/) `error.log`(那里只记录握手后的错误),而是先把握手的字节流拉出来看。用一行命令就能拿到一次完整握手的十六进制:
```bash
# 抓一次完整 TLS 1.3 握手的记录层
openssl s_client -connect example.com:443 \
-servername example.com \
-showcerts \
-msg \
-tls1_3 \
< /dev/null 2>&1 | head -80
```
正常情况下,TLS 1.3 的完整握手长这样(`-msg` 展开的记录):
```
C: ClientHello [0x16, 0x03, 0x01, 0x00, 0x??, ...]
C: 0-RTT Application Data (if any)
S: ServerHello
S: {EncryptedExtensions}
S: {Certificate}
S: {CertificateVerify}
S: {ServerFinished}
C: {ClientFinished}
S: {NewSessionTicket} ← 0-RTT 复用的凭证
S: {NewSessionTicket} ← 通常会发两张,一张单用一张复用
```
TLS 1.2 多一个 ChangeCipherSpec + KeyExchange + ClientKeyExchange + CertificateVerify 序列,往返数是 2-RTT 而不是 1-RTT。判断握手在哪一步挂掉,只需要看最后一包是 ClientHello(客户端还没说话就死)、ServerHello(服务端只回了一半就死)、Finished(几乎完成了)还是 Application Data(成功了但业务层还有问题)。
我一般会做两件事建立"手感":
```bash
# 1. 客户端主动握手,抓所有明文握手报文(-msg 只显示非加密部分)
openssl s_client -connect example.com:443 -servername example.com -msg -tls1_3 < /dev/null 2>&1 | grep -E "^\s+(C|S):"
# 2. tcpdump 抓服务端侧握手包(在 nginx 机器上跑)
sudo tcpdump -ni any 'tcp port 443 and (tcp[tcpflags] & tcp-syn != 0 or tcp[tcpflags] & tcp-fin != 0)' -c 20
```
第一个命令看客户端视角的握手字节流,第二个命令看握手是不是有 RST/FIN 提前切断。这两个视图合起来,握手层 90% 的问题都能定位到具体步骤。
TLS 1.3 一个特别值得注意的现象是:**握手完成后服务端会立刻再发两张 NewSessionTicket**,客户端会静默接收并存储。这张 ticket 就是 0-RTT 的钥匙——服务端如果把它禁了或者密钥换了,下一跳连接就退回到 1-RTT,但**握手本身不会失败**,只是延迟升高。别把这个误诊成握手失败。
## 2. openssl s_client 命令矩阵:30+ 参数分层速查
`openssl s_client` 是 TLS 层排障的第一件武器。它的参数分层我建议这么记:
**A. 连接参数(必用)**
```bash
# -connect 是必须的,-servername 是 SNI,几乎必带
openssl s_client -connect host:443 -servername host
# 走代理(CONNECT 隧道)
openssl s_client -connect host:443 -servername host -proxy proxy:8080
# 通过已有连接(比如从本地代理端口)
openssl s_client -connect 127.0.0.1:31280 -servername host -proxy
# 用指定本地出口 IP(多网卡场景)
openssl s_client -connect host:443 -servername host -bind 10.0.0.5
```
**B. 证书与链**
```bash
# 显示服务端返回的所有证书(排查链缺失核心参数)
openssl s_client -connect host:443 -servername host -showcerts
# 用指定 CA bundle 验证
openssl s_client -connect host:443 -servername host -CAfile /etc/ssl/certs/ca-bundle.crt
# 用系统默认 CA 库验证
openssl s_client -connect host:443 -servername host -CApath /etc/ssl/certs
# 只验证但不拒绝(用于观察)
openssl s_client -connect host:443 -servername host -verify_quiet
# 打印完整证书链验证结果
openssl s_client -connect host:443 -servername host -verify_return_error
```
**C. 协议版本控制**
```bash
# 强制 TLS 1.3
openssl s_client -connect host:443 -servername host -tls1_3
# 强制 TLS 1.2
openssl s_client -connect host:443 -servername host -tls1_2
# 允许版本范围(openssl 1.1.1+)
openssl s_client -connect host:443 -servername host -min_proto TLSv1.2 -max_proto TLSv1.3
# 禁用 TLS 1.3(对比 1.2 表现)
openssl s_client -connect host:443 -servername host -no_tls1_3
```
**D. Cipher suite**
```bash
# 查看 openssl 支持的 cipher
openssl ciphers -v 'ALL'
# 只允许某几个 suite
openssl s_client -connect host:443 -servername host -cipher 'ECDHE-ECDSA-AES256-GCM-SHA384'
# 显示实际协商到的 cipher
openssl s_client -connect host:443 -servername host | grep -A2 "Cipher :"
```
**E. 调试输出**
```bash
# -msg: 打印所有 TLS 报文(含加密记录)
# -debug: 打印更多调试信息
# -state: 打印握手状态机变化
# -quiet: 关闭交互提示
# -sess_out/-sess_in: 保存/加载会话(做 0-RTT 或 session resumption 测试)
# -reconnect: 复用同一个 session 重连 N 次
# -verify_time: 覆盖系统时间验证过期证书
# 完整调试组合
openssl s_client -connect host:443 -servername host -msg -state -debug -quiet
```
**F. 0-RTT 与 Session Resumption**
```bash
# 保存当前 session
openssl s_client -connect host:443 -servername host -sess_out sess.pem
# 用保存的 session 重连(触发 0-RTT)
openssl s_client -connect host:443 -servername host -sess_in sess.pem
# 强制带 early data
openssl s_client -connect host:443 -servername host -sess_in sess.pem -early_data < /dev/null
```
**G. OCSP**
```bash
# 查看 stapled OCSP response
openssl s_client -connect host:443 -servername host -ocsp_resp | grep -A20 "OCSP Response"
# 单独发 OCSP 请求(不走 stapling)
openssl ocsp -issuer /path/to/ca.pem -cert /path/to/leaf.pem -url http://ocsp.example.com -resp_text
```
**H. 后处理**
```bash
# 只输出一行结果,用于脚本
openssl s_client -connect host:443 -servername host -verify_return_error -brief < /dev/null
# 用 -connect 后跟 /dev/null 关闭 stdin,避免进入交互
echo | openssl s_client -connect host:443 -servername host
# 提取证书到文件
openssl s_client -connect host:443 -servername host -showcerts < /dev/null 2>&1 | awk '/BEGIN CERT/,/END CERT/' > chain.pem
```
一张完整命令模板,我在生产上排查时会直接复制它,把 host 换掉:
```bash
#!/usr/bin/env bash
# tls-diag.sh — 一次跑完 TLS 层所有关键诊断
HOST="${1:-example.com}"
PORT="${2:-443}"
echo "===== 1. 快速验证 ====="
echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" -brief 2>&1
echo "===== 2. 证书链 ====="
echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" -showcerts 2>/dev/null \
| awk '/BEGIN CERT/,/END CERT/' | grep -c "BEGIN CERTIFICATE"
echo "^ 上面是服务端返回的证书张数(应该 ≥2,1 张通常是链缺失)"
echo "===== 3. 协议版本探测 ====="
for V in -tls1_3 -tls1_2 -tls1_1 -tls1; do
R=$(echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" $V -brief 2>&1 | grep -E "(Protocol|Cipher)" | tr '\n' ' ')
echo "$V → $R"
done
echo "===== 4. SNI 对比(有 SNI vs 无 SNI) ====="
echo "With SNI:"
echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" -brief 2>&1 | grep "subject"
echo "Without SNI:"
echo | openssl s_client -connect "$HOST:$PORT" -brief 2>&1 | grep "subject"
echo "===== 5. OCSP stapling ====="
echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" -ocsp_resp 2>/dev/null \
| grep -A1 "OCSP Response" | head -5
echo "===== 6. 0-RTT 复测 ====="
echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" -sess_out /tmp/s.pem 2>/dev/null >/dev/null
echo "Session 保存成功,尝试重连 0-RTT:"
echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" -sess_in /tmp/s.pem -early_data 2>&1 | grep -E "(Early|Reused|Session-ID)"
```
## 3. tcpdump 抓握手包:TCP 层 vs TLS 层的 filter 表达式
[Wireshark](https://www.wireshark.org/docs/) 有 TLS 解密功能(要配 session key log 才行),但现场没 GUI 的时候,tcpdump 反而是首选。
**只抓 TLS 握手相关的包:**
```bash
# 抓所有 443 端口 TCP 包
sudo tcpdump -ni any 'tcp port 443'
# 只看 SYN(新连接建立)
sudo tcpdump -ni any 'tcp port 443 and tcp[tcpflags] & tcp-syn != 0 and tcp[tcpflags] & tcp-ack = 0'
# 只看 SYN-ACK(服务端响应)
sudo tcpdump -ni any 'tcp port 443 and tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)'
# 只看 RST(异常中断)
sudo tcpdump -ni any 'tcp port 443 and tcp[tcpflags] & tcp-rst != 0'
# 只看 443 端口上包长 <200B 的(握手包一般都很小)
sudo tcpdump -ni any 'tcp port 443 and (tcp[12] & 0xff < 200)'
```
**TLS 记录层过滤(tcpdump 的 TLS 层支持有限,需要 tcp[?] 偏移计算):**
```bash
# TLS Record Header 前 5 字节:type(1) + version(2) + length(2)
# TLS Handshake type=0x16(record type)
# 从 IP header 之后跳过 14(eth)+20(ip)+20(tcp) = 54,但 tcp 头可能更长
# 抓 ClientHello(type=22,握手 type=1,通常包大小 300-500B)
sudo tcpdump -ni any -X 'tcp port 443 and tcp[12] & 0xff < 600 and tcp[12] & 0xff > 200'
# 抓 ServerHello(type=22,握手 type=2,通常包大小 200-350B)
sudo tcpdump -ni any -X 'tcp port 443 and (tcp[12] & 0xff < 400)'
# 抓 TLS Alert(握手失败时服务端会发 alert)
# Alert 记录:type=21,长度 7
sudo tcpdump -ni any -X 'tcp port 443 and tcp[0]=21 and tcp[3]=0 and tcp[4]=7'
```
**实战组合(我常用的):**
```bash
# 抓 30 秒的完整握手,导出 pcap,之后 wireshark 打开
sudo tcpdump -ni any -w /tmp/tls.pcap 'tcp port 443' &
TCPDUMP_PID=$!
# 同时触发一次连接
for i in 1 2 3; do
echo | openssl s_client -connect example.com:443 -servername example.com -tls1_3 2>&1 | tail -20
sleep 1
done
sleep 2
kill $TCPDUMP_PID
ls -lh /tmp/tls.pcap
```
**在 wireshark 里打开后的关键 filter:**
```
# 只看 ClientHello
tls.handshake.type == 1
# 只看 ServerHello
tls.handshake.type == 2
# 只看 Alert(握手失败时的关键信息)
tls.alert_message
# 抓 SNI 扩展(判断 SNI 是否发送)
tls.handshake.extensions_server_name
# 抓证书链长度
tls.handshake.certificate
# 抓 cipher suite 协商
tls.handshake.conversation
# 抓所有握手相关字段(最有用)
tls.handshake
# 抓 TLS 1.3 early data
tls.handshake.extensions.early_data
# 只看失败的握手
tls.handshake.type == 21 # alert
```
一个我踩过的坑:**tcpdump 抓不到解密后的 TLS 记录内容**,只能看到"某方向某大小"的包。想看真正的握手内容(cipher 是什么、支持的版本有哪些),必须用 wireshark 配 session key log:
```bash
# 在客户端导出 session key log
export SSLKEYLOGFILE=/tmp/tls-keys.log
curl -vI https://example.com > /dev/null
cat /tmp/tls-keys.log # 里面是 KEYLOG 格式的 key,wireshark 直接导入
# wireshark 里:Preferences → Protocols → TLS → (Pre)Master-Secret log filename → /tmp/tls-keys.log
```
没有 wireshark 就用 `ssldump` 代替,它是纯命令行 TLS 解析工具:
```bash
# 抓包 + ssldump 实时解析
sudo tcpdump -ni any 'tcp port 443' -w /tmp/tls.pcap &
ssldump -r /tmp/tls.pcap -k /tmp/tls-keys.log
```
## 4. 六类握手失败根因决策树
按线上出现频率从高到低排:证书链缺失 > 协议版本不匹配 > CN/SAN 不匹配 > 证书过期 > OCSP stapling 失败 > TLS 1.3 0-RTT 恢复失败。
### 4.1 证书链缺失(unverified leaf)
**症状**:`openssl s_client` 报 `verify error:num=20:unable to get local issuer certificate`,或者 `verify return:1 (unverified leaf)`。浏览器侧的报错是"NET::ERR_CERT_AUTHORITY_INVALID"或"Your connection is not private"。curl 报 `SSL certificate problem: unable to get local issuer certificate`。
**根因**:服务端只发了叶子证书,没把中间证书(intermediate CA)发出去。客户端信任库里通常只有根 CA,没有中间 CA,无法构建信任链。
**排查**:
```bash
# 1. 看服务端返回了几张证书
echo | openssl s_client -connect example.com:443 -servername example.com -showcerts < /dev/null 2>&1 \
| awk '/BEGIN CERT/,/END CERT/' | grep -c "BEGIN CERTIFICATE"
# 输出 1 张 → 链断了
# 2. 看每张证书的 subject 和 issuer
echo | openssl s_client -connect example.com:443 -servername example.com -showcerts < /dev/null 2>&1 \
| awk '/BEGIN CERT/,/END CERT/' | openssl crl2pkcs7 -nocrl -certfile - | openssl pkcs7 -print_certs -noout
# 3. 拿到链后单独验证完整性
openssl verify -CAfile /etc/ssl/certs/ca-bundle.crt chain.pem
```
**修复**:
nginx 侧最常见:
```nginx
# 错:只加载 leaf
ssl_certificate /etc/ssl/example.com/fullchain.pem;
ssl_certificate_key /etc/ssl/example.com/privkey.pem;
# 对:fullchain.pem 应该是 leaf + intermediate(+ 可选 root)
# certbot 生成的 fullchain.pem 已经是拼好的
```
certbot 场景下,`ssl_certificate` 必须指 `fullchain.pem` 而不是 `cert.pem`:
```bash
# certbot 目录结构
ls /etc/letsencrypt/live/example.com/
# cert.pem # 只有 leaf
# chain.pem # 只有中间证书
# fullchain.pem # leaf + chain(正确引用这个)
# privkey.pem # 私钥
```
Caddy、Traefik、Envoy 也有同样问题——检查它们的证书来源是不是"只喂了 leaf"。
一个容易忽略的场景:**CDN/WAF 前面挂了自定义证书**,用户以为证书是 CDN 发的,实际是 CDN 用了平台证书,中间链是 CDN 平台的链。这时候客户端证书信任库里要有该平台的根 CA,否则一样报错。
### 4.2 证书过期/未生效(time out of validity)
**症状**:`verify error:num=10:certificate has expired` 或 `verify error:num=9:certificate is not yet valid`。浏览器显示"Your connection is not private · NET::ERR_CERT_DATE_INVALID"。
**根因**:叶子证书 `notBefore` 或 `notAfter` 超出当前时间。
**排查**:
```bash
# 直接看证书有效期
echo | openssl s_client -connect example.com:443 -servername example.com < /dev/null 2>&1 \
| openssl x509 -noout -dates
# 输出类似:
# notBefore=Nov 5 12:00:00 2025 GMT
# notAfter=Feb 3 12:00:00 2026 GMT
# 用 -verify_time 模拟指定时间验证
echo | openssl s_client -connect example.com:443 -servername example.com \
-verify_time 1740787200 < /dev/null 2>&1 | grep verify
```
**修复**:
```bash
# certbot 手动续期
certbot renew --cert-name example.com --non-interactive --agree-tos
# 续期后强制 reload nginx
nginx -t && nginx -s reload
# 校验新证书已生效
echo | openssl s_client -connect example.com:443 -servername example.com < /dev/null 2>&1 | openssl x509 -noout -dates
```
一个我遇到的隐蔽场景:**服务器时间被 NTP 时钟源打错**。证书本身还在有效期内,但服务器时钟漂移了 8 小时导致所有新连接都握手失败。检查:
```bash
# 服务器时间
date -u
# 对比 NTP 官方时间
curl -s https://worldtimeapi.org/api/timezone/Etc/UTC | jq .utc_datetime
# 检查 ntpd/chrony 状态
timedatectl show --property=NTPSynchronized
chronyc tracking 2>/dev/null || ntpq -p 2>/dev/null
```
生产上我一般会在监控里加一条 `kubelet_node_time_offset_seconds > 5` 的告警,避免时钟漂移这种"看似证书问题实则时钟问题"的情况。
### 4.3 CN/SAN 不匹配(hostname verification failed)
**症状**:`verify error:num=52:unhandled critical extension` 或 `verify error:num=62:certificate does not match server name`。浏览器:"This page contains both safe and insecure content" 或"NET::ERR_CERT_COMMON_NAME_INVALID"。curl:`SSL certificate problem: hostname mismatch`。
**根因**:客户端访问的域名和证书里的 CN(Common Name)或 SAN(Subject Alternative Name)不匹配。
**排查**:
```bash
# 看证书的 SAN
echo | openssl s_client -connect example.com:443 -servername example.com < /dev/null 2>&1 \
| openssl x509 -noout -text | grep -A2 "Subject Alternative Name"
# 输出示例:
# X509v3 Subject Alternative Name:
# DNS:example.com, DNS:*.example.com, DNS:api.example.com
# 测试不同域名的握手(SNI 决定服务端返回哪张证书)
for D in example.com api.example.com foo.example.com evil.com; do
echo "[$D]"
echo | openssl s_client -connect example.com:443 -servername "$D" < /dev/null 2>&1 | grep -E "(subject=|verify)"
echo
done
```
**修复**:
```bash
# 换证书,SAN 覆盖目标域名
certbot certonly --webroot -w /var/www/html --certname example.com -d example.com -d "*.example.com" -d api.example.com
# 或者用通配符(注意:通配符只覆盖单层)
# *.example.com 匹配 api.example.com 但不匹配 a.b.example.com 也不匹配 example.com 本身
```
几个通配符的坑:
- `*.example.com` **不匹配** `example.com` 本身(这是 [RFC](https://www.rfc-editor.org/) 6125 的规定),得单独把 `example.com` 加进 SAN。
- `*.example.com` **不匹配** `a.b.example.com`(只一层通配)。
- `*.example.com` **不匹配** `sub.example.com.evil.com`(域名是后缀匹配)。
- 浏览器**忽略 CN 字段**只用 SAN(2017 年 Chrome 60 之后就强制),但服务端校验(比如 Java)可能还在看 CN。
一个特别隐蔽的场景:**证书是通配的,客户端访问的是证书签发的父域**,比如证书 SAN 是 `*.sub.example.com`,客户端访问 `sub.example.com`,浏览器报错但服务端 s_client 报 verify OK。原因:openssl 默认走严格 SAN 匹配,但很多实现(尤其是老的 Java TrustManager)会宽容回退到 CN 匹配。
### 4.4 协议版本不匹配(no shared cipher / handshake failure)
**症状**:`no shared cipher`、`wrong version number`、`handshake failure`。这几个错都可能出现在这里。
**根因**:客户端支持的最高版本 < 服务端支持的最低版本,或者 cipher suite 交集为空。
**排查**:
```bash
# 1. 逐版本测试
for V in -tls1_3 -tls1_2 -tls1_1 -tls1; do
R=$(echo | openssl s_client -connect example.com:443 -servername example.com $V -brief 2>&1 | grep -E "Protocol|Cipher" | tr '\n' ' ')
echo "$V → $R"
done
# 2. 看服务端支持的 cipher(openssl 1.1.1+)
openssl s_client -connect example.com:443 -servername example.com -brief < /dev/null 2>&1 | grep Cipher
# 3. 对比两端支持的协议(ssllabs 是标准工具)
curl -s "https://api.ssllabs.com/api/v3/analyze?host=example.com&publish=off"
# 或者 curl -s "https://api.ssldownloads.com/api/v2/check?host=example.com"
```
**修复**:
nginx 侧的 `ssl_protocols` 和 `ssl_ciphers`:
```nginx
# 生产推荐(TLS 1.2 + 1.3 都要开)
ssl_protocols TLSv1.2 TLSv1.3;
# TLS 1.3 的 cipher 不能配置(RFC 8446 规定),只能用默认
# TLS 1.2 的 cipher 列表(推荐 Mozilla Intermediate 配置)
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off; # TLS 1.3 场景下建议 off,让客户端选最优
ssl_ecdh_curve X25519:prime256v1:secp384r1;
```
**特殊报错定位**:
- `wrong version number`:通常是 TCP 443 端口背后其实是明文 HTTP 服务(比如 nginx 没配 ssl on),openssl 把 HTTP 响应解析成了 TLS 记录头,第一个字节不是 0x16 就报这个。用 `curl -I http://example.com:443` 试试,如果通了就是这个问题。
- `no shared cipher`:真的 cipher 交集为空。检查客户端是否被企业策略限制(浏览器企业证书策略、curl 的 `--tls-max 1.2` 被禁用某些 cipher)。
- `sslv3 alert handshake failure`:服务端主动 reject,通常是 `ssl_protocols` 里没这个版本。
一个我遇到过但比较罕见的场景:**中间有个做 TLS 1.3 转 1.2 的负载均衡器**(比如某些云 WAF)。客户端到 WAF 用 TLS 1.3,WAF 到 nginx 用 TLS 1.2,nginx 侧 `ssl_protocols` 如果禁了 1.2,就会在 WAF→nginx 段握手失败,客户端完全看不到报错。这种问题要在 LB 层抓包才能定位。
### 4.5 TLS 1.3 0-RTT 恢复失败
**症状**:连接仍然成功,但延迟升高了 1 个 RTT。抓包看到客户端发送了 `early_data` 扩展,但服务端在 ServerHello 里回了 `early_data.rejected`。握手从 0-RTT 退回到 1-RTT。
**根因**:服务端不接受 0-RTT 恢复,或者 NewSessionTicket 已过期。
**排查**:
```bash
# 1. 保存 session
echo | openssl s_client -connect example.com:443 -servername example.com -tls1_3 \
-sess_out /tmp/s.pem < /dev/null 2>&1 | grep -E "(Reused|Session-ID|NewSessionTicket)"
# 2. 用保存的 session 尝试 0-RTT
echo | openssl s_client -connect example.com:443 -servername example.com -tls1_3 \
-sess_in /tmp/s.pem -early_data 2>&1 | grep -E "(Early|Session-ID)"
# 3. 抓包看 early_data 扩展
sudo tcpdump -ni any -X 'tcp port 443' | grep -A2 "17 00"
# 更实用的做法:wireshark 里 filter: tls.handshake.extensions.early_data
```
**修复**:
```nginx
# nginx 侧开启 0-RTT(1.25.0+)
ssl_early_data on;
# 如果不想开:
ssl_early_data off;
# 关闭 session tickets(会导致 0-RTT 直接不生效)
ssl_session_tickets off;
```
**0-RTT 的三个坑(都是我在生产遇到的)**:
1. **ticket 密钥轮换**:nginx 默认用 `ssl_session_cache` 的内存存储,reload 后 ticket 就失效。想让 ticket 跨 reload 存活,需要配置 `ssl_session_ticket_key` 指向持久化文件,或者根本别指望 0-RTT 跨 reload 存活。
2. **CDN/LB 层剥离**:[Cloudflare](https://developers.cloudflare.com/)、AWS ALB、某些企业 LB 会把 early_data 扩展剥掉,即使 nginx 开了 0-RTT,客户端也感知不到。用 `curl -v --early-data` 抓一次响应,看 `Early data was accepted` 还是 `Early data was rejected`。
3. **重放攻击面**:0-RTT 数据可能被重放,服务端必须做幂等处理。GET 请求 OK,POST 请求必须有去重(比如幂等 key)。这是 RFC 8446 §8 明确要求的服务端责任。
判断"0-RTT 到底有没有生效"的最快方法:
```bash
# curl 7.88+ 支持 -w 里的 early_data_accepted
curl -w "\nEarly data accepted: %{early_data_accepted}\n" -o /dev/null -s https://example.com
# 输出 Early data accepted: 1 表示生效,0 表示退回 1-RTT
```
### 4.6 OCSP stapling 失败
**症状**:握手本身成功,但客户端(尤其是 Chrome)会看到 "stapled response is not valid" 或者 "This site uses OCSP stapling, but the response was not valid"。curl 看不到这个提示,因为 curl 不做 stapling 校验。
**根因**:nginx 声明了 `ssl_stapling on` 但拿不到有效的 OCSP 响应。
**排查**:
```bash
# 1. 看 leaf 证书是不是有 OCSP URI
echo | openssl s_client -connect example.com:443 -servername example.com < /dev/null 2>&1 \
| openssl x509 -noout -text | grep -A1 "OCSP"
# 没有 Output → 证书不支持 OCSTAPLING,ssl_stapling 一定失败
# 2. 直接请求 OCSP 端点看返回什么
openssl ocsp -issuer /etc/ssl/letsencrypt/R3.pem \
-cert /etc/letsencrypt/live/example.com/cert.pem \
-url http://ocsp.digicert.com -resp_text
# 看返回是不是 "Certification Status: Good"
# 3. 看 nginx 抓到的 stapling 响应
tail -100 /var/log/nginx/error.log | grep -i stapling
# 典型报错:
# SSL_do_handshake() failed (SSL: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert internal error)
# openssl ssl3_read_bytes...
```
**修复**:
```nginx
# 基础配置
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/ssl/letsencrypt/chain.pem;
# 关键:resolver 必须显式配,nginx 不能从 /etc/resolv.conf 读
resolver 1.1.1.1 8.8.8.8 valid=300s;
resolver_timeout 5s;
# 显式指定 OCSP responder URL(可选但推荐)
ssl_stapling_responder https://ocsp.digicert.com;
```
**几个特殊场景**:
- **自签证书**:没 OCSP URI,`ssl_stapling on` 永远失败。要么关掉 `ssl_stapling off`,要么用自签 CA 签发时显式加 OCSP URI(一般不这么做)。
- **GoDaddy 部分产品**:不给 OCSTAPLING 端点。这种证书 `ssl_stapling` 关了就好,别纠结。
- **企业内网 CA**:OCSP 端点在内网 DNS,nginx 的 resolver 要指向内网 DNS(比如 `10.0.0.53`),公共 DNS 找不到内网 CA 的 OCSP 服务。
## 5. 浏览器与 curl 看到的现象为什么不一样
这是排查里最容易迷惑的一点:curl 报错但浏览器正常,或者反过来。
**核心差异**:
| 维度 | 浏览器 | curl |
|---|---|---|
| CA 库 | 系统级 + 平台额外补丁(Apple Root CA / Microsoft 更新) | 系统 CA 库,通常更小 |
| 链补齐 | 会主动从 AIA 扩展拉中间证书 | 不做链补齐 |
| SNI | 强制发送 | 需要 `-servername` 显式发送 |
| HSTS | 有存储,会强制走 HTTPS | 不做(除非 `--hsts`) |
| HSTS preload | 内置 preload list | 无 |
| OCSP stapling | 严格校验 stapled response | 不校验 |
| 证书链长度 | 一般接受 3-4 张 | 默认无硬限制 |
| OCSP CRL 检查 | 有些浏览器会主动请求 | 不请求 |
| TLS 1.3 0-RTT | 支持 | 7.88+ 才支持 |
**排查思路**:
```bash
# 1. 让 curl 使用浏览器的 CA 库(跨平台统一)
# macOS Safari/Chrome 系统 CA
curl --cacert /etc/ssl/cert.pem -I https://example.com
# [Linux](https://www.kernel.org/doc/html/latest/) 用系统 CA
curl --cacert /etc/ssl/certs/ca-certificates.crt -I https://example.com
# 或者用 openssl s_client 指定同一份 CA,模拟浏览器行为
echo | openssl s_client -connect example.com:443 -servername example.com \
-CAfile /etc/ssl/certs/ca-bundle.crt -verify_return_error < /dev/null
# 2. 看浏览器 devtools 里的连接信息
# Chrome: DevTools → Network → 右键 → Copy → Copy as cURL
# 会给你一行 curl 命令,包含浏览器的真实参数
# 3. Chrome 内部错误诊断
# chrome://net-internals/#certs → 输入域名看证书详情
# chrome://net-internals/#traces → 抓握手事件流
# chrome://net-internals/#ocsp → 看 OCSP 请求
```
**一个典型场景**:curl 报 `unable to get local issuer certificate`,浏览器正常。原因:浏览器内置了 Let's Encrypt 的 ISRG Root X1,但 Ubuntu 20.04 的默认 CA 包太老没有。修复:
```bash
apt update && apt install ca-certificates --reinstall
update-ca-certificates
# 或者临时用 curl --cacert /etc/ssl/certs/ca-certificates.crt
```
**反向场景**:浏览器报错,curl 正常。常见原因:
- **HSTS preload**:域名被 preload,浏览器强制 HTTPS,而服务端 80 端口有证书问题(比如 80 端口只监听 HTTP,没有证书)。curl 走 http:// 就绕过了。
- **CT log 校验失败**:浏览器做 Certificate Transparency 校验(Chrome 强制),ct 日志里没找到该证书的审计记录。curl 不做这个检查。
- **企业代理注入**:公司代理替换了证书(TLS 解密审计),浏览器识别是"未知 CA"报错,curl 用了企业根证书就能过。
## 6. nginx 侧配置踩坑速查
一个我认为"够生产用"的 nginx TLS 配置片段,我把每个参数注释清楚:
```nginx
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
http2 on; # 1.25.0+ 拆出来了,1.25 之前是 listen 里带 http2
server_name example.com;
root /var/www/html;
# === 证书 ===
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem; # 用于 stapling 验证
# === 协议版本 ===
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off; # 1.3 场景让客户端选
# === Cipher suite(TLS 1.2 用)===
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_ecdh_curve X25519:prime256v1:secp384r1;
ssl_dhparam /etc/nginx/dhparam.pem; # 2048 位 DH,用 openssl dhparam -out dhparam.pem 2048 生成
# === 会话管理 ===
ssl_session_cache shared:SSL:10m; # 10 MB 共享内存,约 1 万 session
ssl_session_timeout 1d; # 会话缓存 1 天
ssl_session_tickets off; # 关掉票据(0-RTT 会失效但更安全)
# === OCSP Stapling ===
ssl_stapling on;
ssl_stapling_verify on;
ssl_stapling_responder https://ocsp.digicert.com;
resolver 1.1.1.1 8.8.8.8 valid=300s; # 显式 resolver,别依赖系统
# === 0-RTT(可选,nginx 1.25+)===
ssl_early_data off; # 默认关,开启要小心幂等
# === 其他 ===
ssl_buffer_size 8k;
ssl_early_bytes 32k;
ssl_session_jitter 10m; # 避免雪崩式 session 过期
}
```
**参数矩阵速查**:
| 参数 | 默认值 | 影响面 |
|---|---|---|
| `ssl_protocols` | TLSv1 TLSv1.1 TLSv1.2 | 决定支持的版本 |
| `ssl_ciphers` | HIGH:!aNULL:!MD5 | TLS 1.2 cipher 列表 |
| `ssl_prefer_server_ciphers` | on | off 时客户端选,on 时服务端选 |
| `ssl_session_cache` | none | 会话复用存储 |
| `ssl_session_timeout` | 5m | 会话缓存时间 |
| `ssl_session_tickets` | on | 开启后可做 session resumption |
| `ssl_stapling` | off | 是否 stapling OCSP |
| `ssl_stapling_verify` | off | 是否验证 stapled response 签名 |
| `ssl_early_data` | off(1.25+) | 是否允许 0-RTT |
| `ssl_buffer_size` | 4k | 加密 buffer 大小 |
| `ssl_early_bytes` | 0 | 早发加密数据的字节数 |
| `ssl_session_jitter` | 0 | 会话过期抖动,避免雪崩 |
**常见报错对照**:
```
# "SSL_do_handshake() failed (SSL: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert internal error)"
→ 客户端不支持 ssl_protocols 里指定的版本
→ 或者 cipher suite 里有一个客户端不接受
# "no suitable key share received"
→ TLS 1.3 场景下服务端要求的 group 客户端都不支持
→ 检查 ssl_ecdh_curve 和客户端能力
# "OCSP response is not valid, verify error:num=20"
→ ssl_stapling_verify on 但 stapled 响应签名验证失败
→ 检查 ssl_trusted_certificate 是否是完整链
# "unknown ssl_early_data"
→ nginx 版本低于 1.25,去掉这行
```
## 7. 生产环境证书轮转 checklist
证书轮转的目标:**零中断切换**。任何一次 reload 都要保证新连接的握手用新证书,旧连接不断。
**certbot 自动续期模板**:
```bash
# /etc/systemd/system/certbot-renew.service.d/override.conf
# 或者用 certbot 的 timer + hook
# 标准 timer
systemctl enable --now certbot.timer
# /etc/letsencrypt/renewal-example.com.conf 里的 renewal hook
[[renewal hooks]]
deploy_hook = "nginx -t && nginx -s reload"
# 手动跑一次续期验证
certbot renew --dry-run --cert-name example.com
```
**验证脚本**:
```bash
#!/usr/bin/env bash
# cert-verify.sh — 证书轮转前后跑一遍
HOST="${1:-example.com}"
CERT_FILE="/etc/letsencrypt/live/${HOST}/fullchain.pem"
echo "=== 证书信息 ==="
openssl x509 -in "$CERT_FILE" -noout -subject -dates -ext subjectAltName
echo "=== 服务端握手验证 ==="
echo | openssl s_client -connect "$HOST:443" -servername "$HOST" < /dev/null 2>&1 | grep -E "(subject=|issuer=|notAfter|Verify return code|Protocol|Cipher)"
echo "=== 剩余天数 ==="
EXP=$(openssl x509 -in "$CERT_FILE" -noout -enddate | cut -d= -f2)
DAYS=$(( ( $(date -d "$EXP" +%s) - $(date +%s) ) / 86400 ))
echo "剩余 ${DAYS} 天"
if [ "$DAYS" -lt 14 ]; then
echo "⚠️ 剩余不足 14 天,立即续期"
exit 1
fi
```
**监控告警规则([Prometheus](https://prometheus.io/docs/) + Alertmanager 示例)**:
```yaml
# prometheus rule
groups:
- name: tls-cert-expiry
rules:
- alert: TLSCertExpiringSoon
expr: probe_ssl_earliest_cert_expiry - time() < 14 * 24 * 3600
for: 30m
labels:
severity: warning
annotations:
summary: "{{ $labels.instance }} 证书 14 天内到期"
- alert: TLSCertExpiringVerySoon
expr: probe_ssl_earliest_cert_expiry - time() < 3 * 24 * 3600
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.instance }} 证书 3 天内到期,立即处理"
```
**轮转 checklist(按顺序执行)**:
1. `certbot renew --dry-run` 确认续期流程通(DNS/HTTP 都通)
2. `certbot renew` 实际续期
3. `nginx -t` 检查新配置(`ssl_certificate` 指向的 new fullchain)
4. `nginx -s reload`(不是 restart,reload 不断已有连接)
5. `openssl s_client` 验证新证书已生效
6. 监控面板确认 `probe_ssl_earliest_cert_expiry` 已重置
7. 保留旧证书备份 90 天(回滚用)
**回滚方案**:
```bash
# 保留备份
mkdir -p /etc/letsencrypt/live/example.com/backup-$(date +%Y%m%d)
cp -a /etc/letsencrypt/live/example.com/*.pem /etc/letsencrypt/live/example.com/backup-$(date +%Y%m%d)/
# 回滚:把 backup 里的文件覆盖回去
cp -a /etc/letsencrypt/live/example.com/backup-20261010/*.pem /etc/letsencrypt/live/example.com/
nginx -s reload
```
一个我踩过但比较隐蔽的坑:**certbot 生成的新证书文件权限**。默认 `chmod 600 privkey.pem` 是对的,但如果 nginx worker 以非 root 用户跑,读不到 600 权限的文件会握手失败并记录 `SSL_CTX_use_PrivateKey_file() failed`。检查:
```bash
ls -la /etc/letsencrypt/live/example.com/
# 应该看到:
# -rw-r--r-- 1 root root ... chain.pem
# -rw-r--r-- 1 root root ... fullchain.pem
# -rw------- 1 root root ... privkey.pem
# -rw-r--r-- 1 root root ... cert.pem
# 修权限
chmod 644 /etc/letsencrypt/live/example.com/*.pem
chmod 600 /etc/letsencrypt/live/example.com/privkey.pem
chown -R root:root /etc/letsencrypt/live/example.com/
```
## 8. 常见误区与速查 Cheat Sheet
**误区 1:把 nginx 的 502/504 当握手失败**
502/504 是 HTTP 层错误,握手必须已经成功。握手失败表现为 curl 的 `openssl` 报错、浏览器的证书警告、或者干脆 TCP RST。判断:`curl -vI https://...`,如果看到 `Connected to` 之后立刻有 `SSL connection using` 就是握手成功了;如果卡在 `Connected to` 之后超时或者报错 `SSL_connect` 就是握手失败。
**误区 2:`no shared cipher` 就一定是 cipher 问题**
也可能是协议版本问题(TLS 1.3 vs 1.2 不匹配)、也可能是 DH 参数不匹配。先分版本测试再改 cipher。
**误区 3:`ssl_stapling on` 一定安全**
如果 `ssl_stapling_verify off`(默认),nginx 不验证 stapled response 的签名,恶意中间人可能注入伪造的 OCSP 响应。生产上必须开 `ssl_stapling_verify on` + `ssl_trusted_certificate`。
**误区 4:证书过期前一定会有 certbot 邮件提醒**
certbot 只在续期成功/失败时发邮件,不主动发"证书将在 X 天后过期"。得靠自己的监控告警,或者配置 certbot 的 `renew_before_expiry`(默认 30 天,但可以更早)。
**误区 5:Chrome 的 `chrome://ssl` 是最权威的证书视图**
它展示的是 Chrome 已经加载的证书,可能包含缓存。要拿最新的服务端证书,用 `chrome://net-internals/#certs` 手动刷新,或者干脆用 `openssl s_client`。
**误区 6:SAN 通配符 `*.example.com` 覆盖 `www.example.com` 之外的所有子域**
只覆盖一层。`api.example.com` OK,`api.v2.example.com` 不 OK,`example.com` 本身也不 OK。
**误区 7:HTTPS 握手失败一定跟证书有关**
也可能是:端口没监听(`curl -v` 卡在 `Trying...`)、IP 层不通(防火墙、路由)、SNI 被中间设备改写了(企业代理)。先用 `tcping` 或 `nc -zv host 443` 确认 TCP 通,再看 TLS 层。
**误区 8:TLS 1.3 一定比 1.2 好**
TLS 1.3 更紧凑(1-RTT)、更快(0-RTT)、更安全(去掉老 cipher)。但 TLS 1.2 兼容老客户端、老中间设备、企业代理。生产环境建议双开:
```nginx
ssl_protocols TLSv1.2 TLSv1.3;
```
**误区 9:openssl s_client 报错就是服务端问题**
s_client 是客户端,它的行为受本机 CA 库、openssl 版本、命令行参数影响。同一个域名,本机 s_client 报错、跳板机上 s_client 正常,是常见现象。用 `-CAfile` 显式指定 CA 让结果可比。
**误区 10:OCSP stapling 失败会导致连接失败**
不会。stapling 只是让客户端不用主动发 OCSP 请求,握手本身仍然成功。浏览器会 fallback 到主动 OCSP 请求或者直接忽略。所以 `ssl_stapling` 失败通常只在日志里看到,不影响用户流量——但会增加握手时延(Chrome 会主动查 OCSP)。
---
**速查表:报错 → 根因 → 修复**
| 报错关键字 | 根因 | 修复 |
|---|---|---|
| `unverified leaf` / `unable to get local issuer certificate` | 证书链缺失 | 加载 fullchain.pem |
| `certificate has expired` / `certificate is not yet valid` | 证书过期/未生效 | 续期或校时间 |
| `hostname mismatch` / `does not match server name` | CN/SAN 不匹配 | 换证书覆盖目标域 |
| `no shared cipher` / `wrong version number` | 版本或 cipher 不匹配 | 调 ssl_protocols / ssl_ciphers |
| `stapling response is not valid` | OCSP stapling 失败 | 显式配 resolver + stapling_verify |
| `early_data.rejected` / `Early data was rejected` | 0-RTT 恢复失败 | 检查 ssl_early_data / ticket key |
| `tlsv1 alert internal error` | 服务端主动 reject | 检查 ssl_protocols / cipher |
| `no suitable key share received` | TLS 1.3 group 不匹配 | 检查 ssl_ecdh_curve |
| `ssl3_read_bytes:sslv3 alert protocol version` | 版本被服务端拒 | 强制 -tls1_2 或改 ssl_protocols |
**速查表:一条命令解决**
```bash
# 全面握手诊断
echo | openssl s_client -connect HOST:443 -servername HOST -showcerts -msg -tls1_3 < /dev/null 2>&1 | head -80
# 只看协议版本和 cipher
echo | openssl s_client -connect HOST:443 -servername HOST -brief < /dev/null
# 只看证书链
echo | openssl s_client -connect HOST:443 -servername HOST -showcerts < /dev/null 2>&1 | openssl crl2pkcs7 -nocrl -certfile - | openssl pkcs7 -print_certs -noout
# 只看证书有效期
echo | openssl s_client -connect HOST:443 -servername HOST < /dev/null 2>&1 | openssl x509 -noout -dates
# 只看 OCSP stapling 状态
echo | openssl s_client -connect HOST:443 -servername HOST -ocsp_resp < /dev/null 2>&1 | grep -i ocsp
# 测试 0-RTT
echo | openssl s_client -connect HOST:443 -servername HOST -tls1_3 -sess_in sess.pem -early_data < /dev/null
# curl 一行诊断(含协议版本、cipher、握手时间)
curl -svI --tlsv1.2 https://HOST 2>&1 | grep -E "(SSL connection|subject:|issuer:|HTTP/|time_connect|time_starttransfer)"
# 抓握手包 + 快速解析
sudo tcpdump -ni any -c 20 -X 'tcp port 443' &
sleep 1 && echo | openssl s_client -connect HOST:443 -servername HOST < /dev/null
# nginx 侧查当前 TLS 配置
nginx -T 2>/dev/null | grep -iE "(ssl_protocols|ssl_ciphers|ssl_stapling|ssl_early_data|ssl_session)"
```
**速查表:nginx ssl_* 参数一页纸**
```nginx
# 版本
ssl_protocols TLSv1.2 TLSv1.3;
# Cipher(TLS 1.2 用)
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_ecdh_curve X25519:prime256v1:secp384r1;
ssl_dhparam /etc/nginx/dhparam.pem;
# 会话
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
ssl_session_jitter 10m;
# Stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/ssl/letsencrypt/chain.pem;
resolver 1.1.1.1 valid=300s;
# 0-RTT
ssl_early_data off;
# 其他
ssl_buffer_size 8k;
ssl_early_bytes 32k;
```
**速查表:协议版本探测一行流**
```bash
for V in -tls1_3 -tls1_2 -tls1_1 -tls1; do
echo "[$V] $(echo | openssl s_client -connect HOST:443 -servername HOST $V -brief < /dev/null 2>&1 | grep -E 'Protocol|Cipher' | tr '\n' ' ')"
done
```
**速查表:证书到期监控告警阈值**
- 剩余 90 天:INFO 级别,仅通知
- 剩余 30 天:WARNING,触发 certbot renew
- 剩余 14 天:WARNING,人工介入
- 剩余 3 天:CRITICAL,立即处理
- 剩余 0 天:P0,服务降级
**速查表:openssl s_client 常用参数**
| 参数 | 用途 |
|---|---|
| `-connect host:port` | 目标地址 |
| `-servername HOST` | SNI |
| `-showcerts` | 显示完整链 |
| `-CAfile /path` | 指定 CA |
| `-CApath /dir` | 指定 CA 目录 |
| `-tls1_2` / `-tls1_3` | 强制版本 |
| `-no_tls1_3` | 禁用 1.3 |
| `-min_proto` / `-max_proto` | 版本范围 |
| `-cipher LIST` | 指定 cipher |
| `-msg` | 打印 TLS 报文 |
| `-debug` | 更多调试 |
| `-state` | 状态机 |
| `-sess_out /path` | 保存 session |
| `-sess_in /path` | 加载 session |
| `-early_data` | 触发 0-RTT |
| `-reconnect N` | 复用 session N 次 |
| `-ocsp_resp` | 抓 stapled OCSP |
| `-verify_return_error` | 验证失败即退出 |
| `-verify_quiet` | 静默验证 |
| `-verify_time N` | 覆盖系统时间 |
| `-proxy [host:port]` | 走代理 |
| `-bind IP` | 指定本地出口 |
| `-quiet` | 关闭交互提示 |
| `-brief` | 简化输出 |
| `-alpn list` | 指定 ALPN 协议 |
| `-nextprotos` | 旧版 ALPN |
到这里 6 类握手失败根因和排查工具都过了一遍。实际生产上排障时我一般先跑第 8 章的"一条命令解决"里的 `openssl s_client -showcerts -msg`,看错误发生在哪一步,然后按第 4 章的决策树往下走。如果 openssl 看不出问题,再切到 tcpdump 抓包 + wireshark 分析 TLS 记录。整套流程跑下来,绝大多数 TLS 握手失败都能定位到具体配置行。有一点我也不完全确定:TLS 1.3 场景下的 0-RTT 恢复失败在监控里其实很难主动发现(因为它表现为延迟升高而不是错误率升高),我在生产里是通过 `curl -w '%{early_data_accepted}'` 定期探测来发现的,如果这块有更优雅的姿势欢迎在评论区指正。
## 相关文章
- [DNS 排障检测:dig +trace 从递归到权威的六症状决策树](dns-troubleshoot.md)
- [nginx 504 gateway timeout 排查:6 类根因决策树](nginx-504-troubleshoot.md)
- [TCP 排障决策树:ss + tcpdump 三件套定位 TIME_WAIT / RST / SYN 半连接](tcp-troubleshoot.md)
---
## DSM 升级后服务起不来?五层排查决策树
URL: https://ops.jiunotes.top/network/synology-dsm-update-services-not-starting.md
摘要: DSM 升级后套件不起、服务停摆的排查决策树:从系统重启、套件状态、启动项、服务日志到 DSM 无法回退,按官方套件中心与更新说明逐层收口。
### Answer
DSM 升级后服务起不来,先分清是整机没启动、套件被停用,还是套件报错:整机问题按官方硬件条目查电源灯/内存/硬盘;套件问题在套件中心 > 已安装里用「启动」「修复」处理;需要自启用任务计划。DSM 更新不可降级,动手前先确认备份。
### FAQ
Q: DSM 升级完重启,Docker 和第三方套件都没自动起来,第一步做什么?
A: 先进套件中心 > 已安装,看套件是「已停用」还是「错误」。若是已停用,点套件右侧动作选单里的「启动」;若是错误或被标为需要修复,点「修复」。不要一上来就重装系统:官方管理套件页明确说,修复有时是因为套件版本过旧、与最新版 DSM 不兼容,或程序文件缺失损坏,需要修复的套件会列在已安装分类下。
Q: 点了「修复」,这算把旧套件修好了吗?
A: 不算。官方页备注写得很清楚:按下「修复」实际上是安装该套件的最新版本,而不是修补旧版本。所以修复前先确认新版本与你的 DSM 版本兼容;若修复后仍装不上,按官方指引联系套件发行者或开发者,Synology 不为第三方应用提供个别技术支持。
Q: 升级后服务没起来,能不能直接把 DSM 降回去?
A: 不能。Synology 官方FAQ写明 DSM 更新不可回退,升到更新版本后没有降级选项。所以在动手修之前,先确认数据备份存在:官方说明更新本身通常不会造成数据丢失,但仍强烈建议在更新前创建备份。
Q: 我想让某个服务开机自启,命令行有什么官方支持的做法?
A: 优先用 DSM 内建图形界面。官方「任务计划」文档说明,任务计划可以在特定时间或特定事件后运行服务或脚本,支持「触发的任务」与「服务」类型,可在常规里选择运行账户。命令行层面的 synopkg / synoservice / synopkgctl 属于社区逆向命令,不在 Synology 官方 CLI 文档中,以现场版本为准,不要标成官方支持。
Q: 升级后 NAS 整个起不来,和「套件没起来」是一回事吗?
A: 不是。Synology 官方有独立条目处理「更新后无法开机」:先查主板电源指示灯行为,再移除所有非 Synology 内存条并跑内存测试,硬盘问题联系硬盘厂商。这是硬件层排查,与套件层的启动/修复流程不能混用。
### Full Content
# DSM 升级后服务起不来:五层排查决策树
DSM 升级完成、NAS 自动重启之后,管理员最常遇到两种情况:某个套件的服务没有跟着起来,或者整个应用打开后功能不全。这篇按「整机状态 → 套件状态 → 启动项 → 日志 → 回退与边界」五层收敛,每层只回答一个是非题。文中所有 UI 路径与按钮名逐条对照 [Synology 官方 DSM 更新常见FAQ](https://kb.synology.com/en-global/DSM/tutorial/What_can_I_do_to_troubleshoot_DSM_update_problems)、[官方管理套件页](https://kb.synology.com/en-global/DSM/help/DSM/PkgManApp/manage?version=7)、[官方系统更新页](https://kb.synology.com/en-global/DSM/help/DSM/AdminCenter/system_dsmupdate?version=7)、[官方任务计划页](https://kb.synology.com/en-global/DSM/help/DSM/AdminCenter/system_taskscheduler?version=7) 与 [官方 root SSH 登录指引](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) 核过。第三方逆向 CLI 不在官方文档范围内,正文会单独标注。
先给结论:绝大多数「升级后服务没起来」不是升级脚本坏了,而是升级过程自动重启后套件处于停用状态、套件版本落后于新 DSM、或者启动项本来就没配。DSM 的更新机制决定了它只能往新版本走,所以排查顺序应该是先恢复服务,再谈改配置。相同的「先定位路径再动手」思路也用于 [DNS 排障:从解析失败到定位根因](dns-troubleshoot.md)。
## 1. 第一层:先分清整机没启动,还是套件没启动
排障第一步是把「服务起不来」拆成两个完全不同的场景,它们的处置没有交集:
- **整机没有正常启动**:DSM 网页打不开、SSH 连不上、电源灯行为异常。这已经不是套件问题。Synology 官方「更新后 NAS 无法启动」条目给了三个方向:查主板(开机时电源指示灯只闪几秒后熄灭、或闪烁超过 10 分钟,可能是主板或电源故障,联系经销商维修或更换);移除所有非 Synology 内存条并按官方教程跑内存测试;硬盘问题联系硬盘厂商。若能正常启动但听到长鸣且蓝灯常亮,官方列出坏道、内存条故障、安装非 Synology 内存等原因。
- **整机正常、某个套件没起来**:DSM 能登录、套件中心能打开,只是某个应用不可用。这才是本文主场景,进第 2 层。
注意:官方知识中心不同语言版本、不同更新日期对电源灯闪烁时长的表述出现过 10 分钟与 20 分钟两种口径,以你机型对应的官方条目为准。这一步的分岔很重要:官方把「更新后无法开机」单独列成一个技术支援条目,说明它不是套件层的修复动作能覆盖的。把硬件症状当成套件故障去反复点「修复」,只会拖延时间。
## 2. 第二层:在套件中心读状态,而不是猜状态
Synology 官方管理套件页写明,在套件中心左侧点「已安装」可查看可用更新,也可查看套件状态。需要修复的套件会列在「已安装」分类下。按这个路径核对:
- 套件状态为**已停用** → 点该套件,从动作下拉选单选「启动」。官方页把这个操作叫「运行或停止套件服务」:点已安装套件,从下拉选单选「运行」或「停止」。DSM 不同版本的中文界面可能显示为「启动/停用」或「运行/停止」,以你现场界面用词为准。
- 套件状态为**错误 / 需要修复** → 点「修复」。官方给出的成因有两类:套件版本过旧、与最新版 DSM 不兼容;或者套件程序文件缺失、损坏。
- 修复后仍然装不上 → 官方备注要求联系该套件的发行者或开发者。这是责任边界,不是推诿:官方页明确写,Synology 不为第三方应用提供个别技术支持。套件详情页的「其他信息」区有发行者或开发者的联络方式。
这里有个容易踩的坑:官方明确说,点「修复」实际上是安装最新版本,而不是修补旧版本。所以修复动作隐含一次版本升级,修复前要确认新版本支持你当前的 DSM 版本与机型,不要在维护窗口外随手按下去。
## 3. 第三层:升级自动重启之后,启动项还在不在
DSM 更新完成后系统会自动重启 —— 这是官方系统更新页在「手动 DSM 更新」步骤里写明的:选择更新档、安装,系统会在更新完成后自动重新启动。重启会重新执行所有启动项配置,所以升级后服务没起来时,要核对的是「这个服务本来该不该自动起来」:
- 打开**控制台 > 任务计划**。官方任务计划页说明,它可以安排服务或脚本在特定时间、或特定事件完成后运行,并区分「计划的任务」与「触发的任务」两类;支持的任务类型包括「使用者定义的脚本」与「服务」,后者可以启动或停止网络服务。
- 在任务的「常规」页里会看到运行账户选择;官方页说明创建触发的任务时要选择用户账户与触发事件。如果升级前有人把某个启动脚本挂在某个账户下,而升级后该账户权限变了或被停用,脚本就不会按预期执行。
- 勾选「仅当脚本异常终止时发送运行详情」的任务,官方注明脚本以 0 结束时不会发送详情。也就是说,没有收到告警邮件不等于脚本正常跑了,要主动去任务页看运行结果。
启动项这条岔的判据是:手动在套件中心点「启动」能起来,但重启后又停了 → 问题在启动配置,不在套件本身。把这两件事分开,才不会在「修套件」和「修启动项」之间来回横跳。
## 4. 第四层:拿日志,不要拿感觉
当套件中心的状态不足以判断根因时,再进命令行。Synology 官方 MediaWiki 更新后故障的处理范例给了一个可复用的路径:登录 DSM 的 SSH,打开 `/var/log/packages/<套件名>.log` 这类套件日志,搜 `fatal`、`error`、`extension` 等关键字,再拿报错去查对应组件的版本兼容性。官方这个范例针对 MediaWiki 扩展,但「读套件日志 → 找关键字 → 查兼容性」这个方法对「升级后服务起不来」同样适用,具体日志路径以你现场套件为准。
关于命令行工具,必须把边界说清楚:
- **官方支持的路径**:DSM 图形界面的套件中心与任务计划,以及官方明确给出的 root SSH 登录流程。官方登录指引要求 SSH 用户在 DSM 6.0 / SRM 1.3 及以后是 administrators 群组内的用户,先用管理员账号 SSH 登录,再执行 `sudo -i` 输入管理员密码取得 root 权限;并警告启用 SSH 服务可能带来安全风险,只在必要时启用。官方还建议把默认端口 22 换成其他端口。
- **社区/逆向命令**:`synopkg`、`synoservice`、`synopkgctl`、`synoservicectl` 等常见于社区博客与论坛,**不属于 Synology 官方文档支持的 CLI**。它们的子命令与参数在不同 DSM 版本间差异很大,现场若要用,必须先 `synopkg --help` 之类确认实际支持的语法,并把结论标成 needs-site-confirm,不能当成官方事实。
换句话说:日志可以帮助你定位,命令是否可用必须现场核。社区命令在 DSM 6 与 DSM 7 之间的可用性差异,在论坛里就有实际反馈;这正是「以现场版本为准」的原因,不是保守说法。
## 5. 第五层:更新不可降级,边界要先画好
升级后修不回来时,很多人第一反应是「降回旧版 DSM」。Synology 官方 FAQ 写得很直接:DSM 更新不可回退,一旦更新到更新版本,就没有降级当前 DSM 版本的选项。同一条目也说明,一般情况更新不会造成数据丢失,但官方始终建议更新前备份数据。官方系统更新页同样写:只能更新到更新版本,更新不可回退;更新不影响 NAS 上的数据,但强烈建议开始前创建备份。
这意味着两件事:
1. 不要在升级后发现服务异常时把「降级」写进方案里,那条路不存在。方案只能是恢复服务或等待发行者出新版本。
2. 如果升级是自动发生的 —— 官方说明 2025 年及以后推出的机型、新装 DSM 7.2.2-72806 Update 3 或以后并联网的设备,重要 DSM 与套件更新会自动安装 —— 要按官方指引改为手动更新:root SSH 登录后执行 `/usr/libexec/syno-update-settings --set-autoupdatetype-notify`,并在控制台 > 更新与还原 > DSM 更新 > 更新设置里选「通知我并让我决定是否安装更新」,在套件中心 > 设置 > 自动更新里选「停用自动更新」。注意官方注明:执行 Mode 2 重置或系统重置并重装 DSM 后,需要重复这些步骤。
## 6. 一张决策树:现象 → 下一刀砍在哪
- DSM 网页打不开、SSH 连不上、电源灯异常 → 按官方「更新后无法开机」条目查主板、内存、硬盘,停止套件层操作。
- DSM 能登录、套件显示已停用 → 套件中心 > 已安装 > 动作 > 启动;手动能起来但重启后复发 → 查控制台 > 任务计划的启动项与运行账户。
- 套件显示错误 / 需要修复 → 先确认新版本兼容,再点「修复」;修复 = 安装最新版,不是修补旧包。
- 修复后仍失败且是第三方套件 → 去套件详情页「其他信息」找发行者或开发者联络方式,由发行者支持;Synology 不提供个别第三方应用技术支持。
- 状态看不出根因 → SSH 查 `/var/log/packages/` 下对应套件日志(路径以现场为准),按 `fatal` / `error` 关键字收口。
- 日志或报错指向 DSM 版本不兼容 → 不要规划降级,官方明确 DSM 更新不可回退;改为更新套件或联系发行者。
每一步只回答一个是非题。别把「整机没启动」和「套件被停用」两条岔混在同一轮里改 —— 前者要查硬件,后者只要点一下启动。网络服务本身不通时的路径判断,可延伸到 [TCP 连不通怎么查:从端口到抓包](tcp-troubleshoot.md),但那是另一条问题链,不要在恢复套件服务的过程中并行排查。
## 7. 收尾验收清单
- [ ] DSM 版本号已记录,更新路径与所用官方文档版本一致
- [ ] 已区分整机未启动与套件未启动,症状归属清楚
- [ ] 套件中心 > 已安装中的状态已核对,启动/修复动作有据可依
- [ ] 修复前已确认目标版本与当前 DSM、机型兼容
- [ ] 任务计划里的自启项与运行账户已核对,异常终止告警已确认有效
- [ ] 需要 SSH 取证时,先按官方流程启用并限制 SSH,取证后关闭
- [ ] 社区命令(如有使用)已标注非官方、以现场版本为准,结论标 needs-site-confirm
- [ ] 已确认升级前存在有效备份;已接受 DSM 不可降级这一前提
把这份清单固化成例行检查并不难:升级前后各导一次套件状态与任务计划列表做对比。但在手工路径走通之前,先别写自动化脚本 —— 你还没有判读基线。
## 相关文章
- [群晖 SSH Permission denied:五层定位决策树](synology-ssh-permission-denied.md)
- [群晖第三方套件安装失败:五层排查决策树](synology-third-party-package-install-failed.md)
---
## 群晖 SSH Permission denied:五层定位决策树
URL: https://ops.jiunotes.top/network/synology-ssh-permission-denied.md
摘要: 群晖 DSM SSH 报 Permission denied、root 登不上、sudo 提权失败的排查决策树:分清账号密码、密钥、家目录权限、自动封锁与服务本身,按官方登录指引逐层收口。
### Answer
SSH 报 Permission denied 时,先分清是账号密码、密钥、家目录权限、自动封锁还是服务层问题:新版 DSM 用管理员账号登录再 sudo -i;密钥登录先核 homes 预设权限与家目录服务;仍失败再看日志中心与安全设置,不要直接改系统配置文件。
### FAQ
Q: SSH 连群晖报 Permission denied,是不是密码错了?
A: 不一定。先分清用的是密码还是密钥,以及报的是登录拒绝还是认证失败。用密码时按官方指引:DSM 6.0 / SRM 1.3 及以后,SSH 用户是 administrators 群组内的用户,先用自己的管理员账号登录,再 sudo -i 提权;DSM 5.2 / SRM 1.2 及以前才直接用 root 账号。直接用 root 登新版本 DSM,被拒是预期行为。
Q: 密钥明明配了,为什么还是 Permission denied (publickey)?
A: 先查官方 RSA 密钥指引里列的前置条件:账号属于 administrators 群组、控制台 > 终端机 & SNMP > 终端机里勾选启用 SSH 服务、控制台 > 使用者 & 群组(DSM 7.0 及以上)或使用者(DSM 6.2.4)> 进阶设定 > 家目录里勾选启用家目录服务,并确认 homes 共用文件夹套用预设权限。官方明确写:改变 homes 预设权限可能导致管理员无法用 RSA 密钥通过 SSH 登录。
Q: homes 共用文件夹的预设权限到底长什么样?
A: 官方表格列出三条:拥有者对本文件夹、子文件夹、子文件及所有子项目有全部管理、读取、写入权限;administrators 群组有全部读取与写入权限;Everyone 在读取权限下只有遍历文件夹/执行文件。可在 File Station 右键 homes 共用文件夹 > 内容 > 权限页查看,官方建议不要改动预设权限。
Q: 能登录普通管理员,但 sudo -i 提权失败怎么办?
A: 按官方 root 登录流程,sudo -i 之后要再次输入 DSM/SRM 管理员账号的密码;两次输入的是同一个管理员账号密码。官方登录指引还写明 DSM 6.0 及以后具备 root 权限的 SSH 登录账户是 administrators 群组内的用户。如果这个账号不在该群组,提权自然不成立。
Q: SSH 服务停用了,为什么日志还在报 SSH 验证失败?
A: Synology 官方有专门条目说明:SSH、SFTP 等服务和加密 rsync 任务都使用 SSH 协议,都可能是这类警告的来源。若确实要用这些服务,确认 SFTP 或 rsync 客户端的用户名与密码正确;不需要 rsync 时可在控制台 > 文件服务 > rsync 取消勾选启动 rsync 服务。大量来自未知用户或 IP 的失败告警,应按官方提升 NAS 安全性条目处理自动封锁与防火墙。
### Full Content
# 群晖 SSH Permission denied:五层定位决策树
`ssh admin@` 返回 `Permission denied, please try again`、`Permission denied (publickey)`,或者能登录却卡在 `sudo -i`,是群晖运维里最常见的一类"看着像密码错、其实分岔很多"的故障。这篇按「账号与 DSM 版本 → 认证方式 → homes 权限 → 安全策略 → 服务与日志」五层收敛。文中 UI 路径、账号规则与命令逐条对照 [Synology 官方 root SSH 登录指引](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet)、[官方 RSA 密钥登录指引](https://kb.synology.com/en-global/DSM/tutorial/How_to_log_in_to_DSM_with_key_pairs_as_admin_or_root_permission_via_SSH_on_computers)、[官方 homes 预设权限说明](https://kb.synology.com/en-global/DSM/tutorial/default_permissions_of_homes)、[官方 DSM 登录问题排查页](https://kb.synology.com/zh-tw/DSM/tutorial/What_should_I_do_if_I_cannot_sign_in_to_my_DSM_account) 与 [官方提升 NAS 安全性指引](https://kb.synology.com/zh-tw/DSM/tutorial/How_to_add_extra_security_to_your_Synology_NAS) 核过。端口与具体路径以你现场 DSM 版本为准。
先说结论:`Permission denied` 只是 SSH 协议给出的统一拒绝信号,它不告诉你是哪一层拒绝的。真正决定排查方向的,是你用的是密码还是密钥、你的 DSM 是大版本几、以及这个账号在不在 administrators 群组里。把这三点先固定下来,再谈改配置。网络层是否可达的判读,可延伸到 [TCP 连不通怎么查:从端口到抓包](tcp-troubleshoot.md),但那是另一条链,别和认证失败混在一起。
## 1. 第一层:账号与 DSM 版本,先确认你该用谁登录
官方 root SSH 登录指引把账号规则按版本切得很清楚:
- **DSM 6.0 / SRM 1.3 及以后**:可用 root 权限 SSH 登录的账号是 **administrators 群组内的用户**。流程是:用管理员账号 SSH 登录(官方例子 `ssh myadmin@10.17.2.6 -p 22`),输入该管理员账号密码,再执行 `sudo -i`,再次输入管理员账号密码,即取得 root 权限。
- **DSM 5.2 / SRM 1.2 及以前**:直接用 `root` 账号 SSH 登录(官方例子 `ssh root@10.17.2.5 -p 22`),输入默认账号 admin 的密码。
所以第一条判据很简单:在 DSM 6.0 及以后还试图用 `ssh root@...` 登录,被拒是预期行为,不是故障。同理,用一个不属于 administrators 群组的普通账号去 `sudo -i`,也不会得到 root 权限。
官方同时提醒:启用 SSH 服务可能带来安全风险,建议只在必要时启用,并避免变更系统配置文件;官方还建议把默认端口 22 换成其他端口。这意味着一个常被忽略的事实 —— 你现场 SSH 端口可能已经不是 22,连接层面的失败要先与认证层面的 `Permission denied` 分开。
## 2. 第二层:密码还是密钥,两条路的检查项完全不同
官方 RSA 密钥登录指引声明:文中方法只适用于 **DSM 6.2.4 或以上**。它的「开始进行之前的准备」列了三项,这三项同时也是密钥认证失败时的检查清单:
1. 用属于 **administrators 群组**的账号登录 DSM。
2. 前往**控制台 > 终端机 & SNMP > 终端机**,勾选**启用 SSH 功能**。
3. 以管理员身份 SSH 登录时:前往**控制台 > 使用者 & 群组**(DSM 7.0 及以上)或**使用者**(DSM 6.2.4)> **进阶设定 > 家目录**,勾选**启用家目录服务**;并确认 **homes** 共用文件夹套用预设权限,非管理员用户不应被授予任何读取或写入权限。
判读口径:如果密码登录能进、密钥登录被拒,问题基本落在密钥上传与家目录这三步上,不要去动密码策略;如果密码登录也被拒,先回到第一层确认账号与版本。官方指引的注意事项还提到两点容易踩的坑:Mac 上 `.ssh` 文件夹默认隐藏,要在 Finder 按 `Command` + `Shift` + `.` 显示;如果生成密钥时设了通行码,登录时会被要求输入通行码。
这里的关键分岔是:**密码能进、密钥不能进 → 查密钥与家目录;两者都不能进 → 查账号与锁定状态**。把这两条岔分开,才不会在改密钥权限和重置密码之间反复横跳。
## 3. 第三层:homes 预设权限,最容易被"顺手改坏"的一层
Synology 官方专门有一篇讲 homes 共用文件夹的预设权限,而且把 SSH 密钥登录失败直接列为后果之一。官方写明:改变 homes 预设权限可能导致三类问题 —— 用户可能无法进入自己的 home 文件夹;**管理员可能无法使用 RSA 密钥通过 SSH 登录 DSM**;把数据存在用户 home 文件夹里的套件可能无法正常运行。
官方给出的预设权限表如下(适用对象均为本文件夹、子文件夹、子文件与所有子项目):
| 用户或群组 | 类型 | 权限 |
|---|---|---|
| 拥有者(Owner) | 允许 | 全部管理、全部读取、全部写入 |
| administrators | 允许 | 全部读取、全部写入 |
| Everyone | 允许 | 读取权限下仅「遍历文件夹/执行文件」 |
查看方法官方也给了:打开 **File Station**,右键 **homes** 共用文件夹选**内容**,在**权限**页查看当前权限项;若之前没改过,页面显示的就是预设项,可点**编辑**逐项确认,必要时改回预设或移除自订权限。官方还注明:这里的 administrators 指 DSM 的 administrators 群组;如果 NAS 加入网域或 LDAP,目录服务的管理员群组也可被指派相同权限。
这一层的判据非常具体:密钥登录报 `Permission denied (publickey)`,且你或前任动过 homes 权限 → 先把权限改回官方预设表,再谈其他。官方把这件事写进警告里,不是泛泛的"注意权限"。
## 4. 第四层:自动封锁、验证码与"没有权限使用本项服务"
如果账号密码本身没错,却仍然被拒,要看 DSM 侧的安全策略。官方「无法登录 DSM 账号」排查页列了几类与 SSH 拒绝容易混淆的状态:
- **IP 被封锁**:可在允许/封锁清单里选择被封锁的 IP,点移除并确认删除;如果忘记账号密码或没有其他可用 IP,按官方流程重设管理员登录密码。
- **验证码错误 / 更换或丢失手机**:按官方文章停用多重验证。
- **「您没有权限使用本项服务」**:这是权限被设为拒绝所致。官方给的路径是 DSM 7.0 及以上到控制台 > 应用程序权限 > DSM > 编辑;DSM 6.2 及更早到控制台 > 权限 > DSM > 编辑;DSM Enterprise (PAS) 到控制台 > 应用程序权限 > DSM Enterprise > 编辑。如果所有用户(含管理员)都收到这个错误,按官方对应文章处理。
- **系统正在准备就绪**:此时登录页仍会出现,但尝试登录会报"系统正在准备就绪,请稍后再登录"。开机时间取决于运行的服务数量,要看前面板 LED 判断状态,等就绪再登录。
另外,官方「提升 Synology NAS 安全性」指引说明了自动封锁的覆盖范围:**SSH、Telnet、rsync、网络备份、共享文件夹同步、FTP、WebDAV、Synology 行动应用程式、File Station、DSM 登录**都适用自动封锁。DSM 7.0 及以后在控制台 > 安全性 > 保护设置,DSM 6.2 及更早到控制台 > 安全性 > 帐号。防火墙在控制台 > 安全性 > 防火墙,官方特别提醒:设规则时要从将被允许登录的 IP 登录 DSM,不要用 QuickConnect,并确认当前 IP 已在允许规则里,以免把自己锁在外面。
把这些连起来看:连续输错密码触发自动封锁后,即使密码改对了也会继续被拒,直到封锁解除或 IP 被移除。这时候反复改密码只会延长封锁时间。
## 5. 第五层:服务没开 vs 协议混淆,以及日志取证
官方对一类常见困惑有直接回答:**SSH 服务已停用,却仍收到 SSH 验证失败消息**。原因是 SSH、SFTP 等服务以及加密 rsync 任务都使用 SSH 协议,都可能触发这条警告。若确实要用这些服务,确认 SFTP 或 rsync 客户端使用的用户名与密码正确;不需要 rsync 时,到控制台 > 文件服务 > rsync,取消勾选启动 rsync 服务。如果持续收到大量来自未知用户或 IP 的失败告警,按官方提升安全性条目处理自动封锁与防火墙规则。
取证时先读日志,再动手。官方 NAS 安全性指引把日志中心列为安全事件查看入口;DSM 的"登录被拒"与"服务未启用"在日志里的记录位置不同,先看清是哪一类,再决定是改认证配置还是改服务配置。
关于提权命令的边界:`sudo -i` 出自官方 root SSH 登录指引,属于官方流程;而网上常见的 `synoservice`、`synopkg`、`synowifinetcfg` 等属于社区/第三方逆向命令,**不在 Synology 官方 CLI 文档中**,语法随 DSM 版本变化很大。若现场确需使用,必须先 `--help` 之类确认实际语法,并把结论标成 needs-site-confirm,绝不能标成 verified。
## 6. 一张决策树:现象 → 下一刀砍在哪
- 用 `ssh root@` 被拒,但 DSM 是 6.0 及以后 → 改用 administrators 群组账号登录,再 `sudo -i`;这是版本规则,不是故障。
- 能登录管理员但 `sudo -i` 失败 → 确认第二次输入的是同一管理员账号的密码,且该账号确在 administrators 群组。
- 密码能进、密钥被拒 → 按 RSA 密钥指引核三项:administrators 群组、SSH 服务已启用、家目录服务已启用且 homes 权限为预设。
- 密钥被拒且动过 homes 权限 → File Station > homes > 内容 > 权限,按官方表格改回预设(拥有者全权、administrators 读写、Everyone 仅遍历/执行)。
- 账号密码都对却被拒 → 查允许/封锁清单、多重验证状态、应用程序权限里是否设为拒绝;DSM 7.0+ 看控制台 > 安全性 > 保护,旧版看控制台 > 安全性 > 帐号。
- SSH 服务已停用却仍有验证失败告警 → 查 SFTP 与加密 rsync 任务,不需要 rsync 就在控制台 > 文件服务 > rsync 停用。
- 日志里出现大量未知 IP 失败 → 按官方安全性指引启用自动封锁、设置防火墙允许规则,并确认当前 IP 未被锁。
每一步只回答一个是非题。别把「账号用错」和「家目录权限被改」两条岔混在同一轮里改 —— 前者只是换登录方式,后者要动共享文件夹权限,影响面完全不同。SSL/TLS 证书本身报错时是另一条链,可延伸到 [SSL/TLS 握手失败排障](ssl-tls-handshake-troubleshoot.md),不要和这里的认证拒绝混为一谈。
## 7. 收尾验收清单
- [ ] DSM 版本已记录,登录账号符合该版本的官方规则(6.0+ 用 administrators 群组账号 + sudo -i)
- [ ] SSH 服务启用状态与当前实际端口已核对(不限于默认 22)
- [ ] 若用密钥:家目录服务已启用,homes 权限与官方预设表一致
- [ ] 若密码登录失败:已查允许/封锁清单、多重验证与应用程序权限
- [ ] 自动封锁与防火墙规则已核对,当前管理 IP 未被锁在门外
- [ ] 证书/密钥若设了通行码,已确认客户端会提示输入
- [ ] 用到的命令已区分官方流程与社区逆向命令,后者标 needs-site-confirm
- [ ] 取证结束后按官方建议关闭不再需要的 SSH 服务
把这份清单做成排障卡片比做成脚本更实用:这一层的多数判断是"用哪个账号""权限是不是预设",需要人的上下文;脚本只能帮你把端口连通性和日志尾部打出来。
## 相关文章
- [DSM 升级后服务起不来?五层排查决策树](synology-dsm-update-services-not-starting.md)
- [群晖第三方套件安装失败:五层排查决策树](synology-third-party-package-install-failed.md)
---
## 群晖第三方套件安装失败:五层排查决策树
URL: https://ops.jiunotes.top/network/synology-third-party-package-install-failed.md
摘要: 群晖 spk 安装失败、套件中心报错的排查决策树:按信任层级与签名、DSM 版本兼容、系统分区容量、套件来源与日志五层收口,附官方责任边界。
### Answer
第三方 spk 安装失败先分层:查套件中心信任层级与签名要求,查 DSM 版本兼容与官方支持清单,查系统分区容量(不是存储管理器数字),再查套件来源与日志。Synology 不为第三方应用提供个别技术支持,最终要找发行者或开发者。
### FAQ
Q: 手动安装 spk 报错,第一步查什么?
A: 先查信任层级。DSM 6.x 的套件中心设置 > 一般里有三种信任层级:Synology Inc.、Synology Inc. 及受信任的发行人、任何发行人。若设为只装 Synology 发行的套件,第三方 spk 会被直接拦下。DSM 7.x 的设置页改成了一般 > 通知、测试版、自动更新、套件来源四块,选项名与位置以现场 DSM 版本为准。
Q: 从 DSM 6.2 升到 DSM 7 后,原来的第三方套件全装不上,是官方不支持了吗?
A: 官方确实加了限制:Synology 在 DSM 7.0 中加入严格要求,防止未经 Synology 签署的套件以 root 权限运行,理由是拥有 root 权限的套件能以 root 身份执行指令、危害系统安全。官方明确写:从 DSM 6.2 升级的套件需要变更其权限设定,才能在 DSM 7.0 运行。所以这是签名/权限模型变化,不是你的操作步骤错。
Q: 某个第三方套件在官方支持清单里是「--」或「△」,分别是什么意思?
A: 官方 DSM 7.0 第三方套件支持清单定义了三种状态:V 为目前支持,-- 为不支援,△ 为目前未支援但计划未来纳入。这份清单只包含由 Synology 发布的第三方套件;其他开发者或社群提供的套件,请直接联络他们。清单会定期更新。
Q: 错误提示「系统容量不足」,但存储管理器显示还有空间,怎么回事?
A: Synology 官方说明:存储管理器显示的可用空间不反映系统分区的可用空间。这个错误是因为系统分区没有足够容量解压并安装更新档。官方列出的成因包括终端命令在系统分区(如 /root、/opt)生成文件、Docker 容器把 / 或 /root 映射进容器、以及未经 Synology 发布或验证的第三方套件影响系统设定。别只看存储管理器的数字。
Q: 套件一直装不上,能找 Synology 客服吗?
A: 对第三方套件,官方的责任边界很清楚:套件中心里包含第三方开发者建置并发布的套件,因此 Synology 不为个别应用程序提供技术支持;功能需求、疑问与意见请联络发行者或开发者。有发行者时优先找发行者。套件详情页的「其他信息」区有联系方式。
### Full Content
# 群晖第三方套件安装失败:五层排查决策树
给 NAS 手动装 `.spk`,或在套件中心点安装时失败,报错可能是「档案损毁」「不相容」「系统容量不足」「未受信任的发行人」或直接装完起不来。这篇按「信任与签名 → 版本兼容 → 容量 → 来源 → 日志与责任边界」五层收敛。所有 UI 路径、选项名与官方口径逐条对照 [Synology 官方管理套件页](https://kb.synology.com/en-global/DSM/help/DSM/PkgManApp/manage?version=7)、[官方套件中心设置页(DSM 7)](https://kb.synology.com/en-global/DSM/help/DSM/PkgManApp/configure?version=7)、[官方套件中心设置页(DSM 6)](https://kb.synology.com/en-global/DSM/help/DSM/PkgManApp/configure?version=6)、[官方 DSM 7.0 第三方套件支持清单](https://kb.synology.com/en-global/DSM/tutorial/supported_third_party_packages_beta) 与 [官方系统容量不足说明](https://kb.synology.com/en-global/DSM/tutorial/DSM_update_insufficient_system_capacity_for_update) 核过。DSM 6 与 DSM 7 的设置项差别很大,以现场版本为准。
先说结论:第三方套件装不上,多数不是 spk 文件本身坏了,而是被三层"闸门"之一拦下 —— 信任层级不允许、签名/权限模型与新 DSM 不兼容、或者系统分区没有空间解压。这三层的报错长得都不像自己的原因,所以要先分层判,再动手。同样的「先分清哪一段断了」思路也用于 [DNS 排障:从解析失败到定位根因](dns-troubleshoot.md)。
## 1. 第一层:信任层级与签名,先看官方闸门
Synology 官方「配置套件中心」页(DSM 6)写明,在**一般**页签里可选择信任层级,选项原文是:
- **Synology Inc.**:仅允许安装由 Synology Inc. 发行的套件。
- **Synology Inc. 及受信任的发行人**:仅允许安装由 Synology Inc. 和受信任的发行人所发行的套件。受信任的发行人包含取得第三方社群信任的套件来源(通过添加套件来源),或由用户通过导入发行人证书信任的发行者。
- **任何发行人**:允许安装任何套件,并忽略其发行人和完整性。
同一官方页还说明:在**证书**页签可点「导入」加入受信任发行人的证书; Synology Inc. 的证书在联网时会在安装套件过程中自动更新,也可在证书页签手动导入从 Synology 官网下载的证书;在**套件来源**页签可点「新增」,填入第三方开发者或社群提供的名称与网址,成功后会出现在套件中心的「社群」页。
**DSM 7 的设置页结构不同**:官方 DSM 7 版「配置套件中心」页列出的是**一般 > 通知**、**一般 > 测试版**(勾选「是的,我要查看测试版」后出现在 Beta Packages 页)、**自动更新**页签、以及**套件来源**页签。官方对测试版的提示是:测试版让用户在新功能正式发布前试用,不建议用于商业用途。所以不要照抄 DSM 6 的「信任层级」三选项到 DSM 7 上 —— 版本不同,闸门的名字和位置都不同。
这一层的判据是:报错与发行人、签名、完整性有关 → 先到套件中心设置里按现场版本核对信任相关设置与证书/套件来源,不要先怀疑 spk 文件损坏。
## 2. 第二层:DSM 版本兼容与官方支持清单
DSM 7.0 对第三方套件引入了一个结构性变化。官方「DSM 7.0 支援哪些第三方套件?」页写明:Synology 在 DSM 7.0 中加入了一项严格要求,防止未经 Synology 签署的套件以 root 权限运行;原因是拥有 root 权限的套件可能会以 root 使用者身份执行指令,危害系统安全性。官方接着写:**从 DSM 6.2 升级的套件须变更其权限设定,以在 DSM 7.0 运行**。
这一句解释了最常见的现象:升级前能装的第三方套件,升级后装不上或装完起不来。它不是偶发故障,而是签名/权限模型的变更。官方同时给了一份支持清单,并把状态定义为三种:**V** 目前支援、**--** 不支援、**△** 目前未支援但计划未来纳入。官方备注很关键:这份清单只包含由 Synology 发布的第三方套件;其他开发者及社群提供的套件,请联络他们;使用问题或支持状态查询,请联络套件维护者或在相应论坛提问。官方还说明清单会定期更新 —— 所以看清单时要看更新日期,不要拿旧截图当结论。
官方管理套件页则从另一个角度给出同类因果:套件出错有时是因为版本过旧、与最新版 DSM 不兼容,有时是因为程序文件缺失或损坏;需要修复的套件列在「已安装」分类下。这提醒我们:**"装不上" 与 "装上后报错" 要分开看** —— 前者卡在安装闸门,后者可能只是需要修复或换版本。
## 3. 第三层:系统分区容量,不是存储管理器那个数字
「系统容量不足」是第三方套件安装失败的经典误判点。Synology 官方专门有一个条目回答这件事,并在注意事项里写明:**存储管理器显示的可用空间不反映系统分区的可用空间**。官方解释:出现这个错误是因为系统没有足够容量在系统分区里解压并安装更新档。
官方列出的可排查方向中,与第三方场景最相关的有三条:
- **只在共享文件夹存数据**:终端命令产生的输出(例如在 `/root`、`/opt` 创建文件或目录,或执行自定义二进制文件与脚本)可能填满系统分区并导致更新失败,应移到共享文件夹。
- **Docker 容器**:容器可能因配置或设计不当把数据存在系统分区。官方举例:`docker run` 用 `--volume` 或 `--mount` 把系统路径(如 `/`、`/root`)映射进容器,容器运行时可能把系统分区填满;不确定时咨询镜像提供者,也可从 Container Manager 移除不用的容器回收空间。
- **第三方套件本身**:未经 Synology 发布或验证的第三方套件可能影响系统设定并造成意外问题;但官方也说明,单纯移除它们不一定能完全解决问题,若问题持续需按官方流程重置系统并重装系统 OS。
这一层的判据很具体:报错是容量不足,但存储管理器数字看着够 → 不要继续找更大的卷,按官方列出的系统分区占用源逐项收口。容器卷映射相关的判读可延伸到 [Docker 接 Nginx 502 排障](docker-nginx-502.md),但那是网络/代理问题链,别在这一层展开。
## 4. 第四层:套件来源与文件完整性
排除前三道闸门后,才轮到怀疑 spk 本身。按官方口径做三件事:
1. **确认来源**:官方管理套件页说明,「手动安装」可上传 `.spk` 文件,该文件可来自 Synology 下载中心或第三方网站。来自后者的文件,发行者与完整性完全取决于对方,要先确认它与你的机型、DSM 版本匹配。
2. **用官方支持清单交叉验证**:如果套件在 Synology 发布的第三方清单里,看它的状态是 V、-- 还是 △;状态是 -- 的,不要在安装参数上反复试,直接向发行者确认是否有对应 DSM 版本的包。
3. **社区套件走社群渠道**:官方明确说清单只含 Synology 发布的第三方套件,其他开发者或社群提供的套件要联络他们或在对应论坛提问。这不是推诿,是官方在文档中划定的责任边界。
这里要诚实说一句:具体某家发行者的 spk 内部签名格式、架构字段、依赖声明,不在 Synology 官方文档范围内,现场报错文字也随 DSM 版本变化。本文不编造某个具体错误码对应的修复命令 —— 你拿到的是哪一版 DSM、哪一个发行者的包,就以该发行者文档和现场报错为准,把结论标成 needs-site-confirm。
## 5. 第五层:日志取证、修复动作与责任边界
装上了但起不来,或反复安装失败,先取证。官方 MediaWiki 更新后故障的处理范例给了一条可复用路径:登录 DSM 的 SSH,打开套件日志 `/var/log/packages/<套件名>.log`,搜 `fatal`、`error`、`extension` 等关键字,再拿报错去核对组件版本兼容性。该例针对 MediaWiki 扩展与其他更新场景,具体日志路径与关键字以现场套件为准。
命令行工具边界要单独说清楚:`synopkg`、`synoservice`、`synopkgctl` 等常见于社区博客和论坛,**不是 Synology 官方支持 CLI**,子命令随 DSM 版本变化很大。若现场确需使用,先 `--help` 之类确认实际语法,并把结论标成 needs-site-confirm;官方支持的路径是 DSM 图形界面里的套件中心与官方 SSH 登录流程。
修复动作按官方管理套件页执行:
- 点套件的**修复**按钮。官方特别提醒:按下修复时,实际上会直接安装该套件的最新版本,而不是修补旧版本 —— 所以修复前要确认新版本与当前 DSM 兼容。
- 用**手动安装**上传 `.spk` 文件重新安装并修复。
- 官方给的问题处理顺序是:把套件更新到最新版;移除套件及其数据库(如果有的话)再重新安装;联系发行者或开发者求助。
责任边界写在官方页面上:套件中心包含第三方开发者建置并发行的套件,因此 Synology 不为个别应用程序提供技术支持。有发行者时,发行者负责把套件构建出来供 Synology 产品使用,主要功能由开发者提供;请求支持时优先找发行者。联系方式在套件详情页的「其他信息」区。
## 6. 一张决策树:现象 → 下一刀砍在哪
- 报错与发行人/签名/完整性相关 → 到套件中心设置里按现场 DSM 版本核对信任相关选项、证书与套件来源;DSM 6 与 DSM 7 的设置结构不同,不要照抄。
- 从 DSM 6.2 升到 DSM 7 后套件失效 → 官方明确加了"未经 Synology 签署的套件不得以 root 权限运行"的要求,升级套件须变更权限设定;按发行者的 DSM 7 版本包处理。
- 套件在官方第三方清单里 → 看状态 V / -- / △;只含 Synology 发布的套件,状态 -- 的不要靠改安装参数硬试。
- 报「系统容量不足」但存储管理器看着够 → 官方说两者不反映同一空间;查系统分区占用源(终端输出、Docker 卷映射、第三方套件、日志)。
- 报错发生在具体安装环节 → 确认 spk 来自 Synology 下载中心或第三方网站,核对机型与 DSM 版本;社区套件找发行者或对应论坛。
- 装上后起不来 → SSH 读 `/var/log/packages/` 下对应日志(路径以现场为准),搜 `fatal` / `error` 关键字;再用官方「修复」或「手动安装」重装。
- 修复后仍不行且是第三方套件 → 到套件详情页「其他信息」找发行者/开发者联系方式;Synology 不提供个别第三方应用技术支持。
每一步只回答一个是非题。特别别把「信任层级拦下」和「容量不足」混在一轮里改 —— 前者是策略设置,后者要清理系统分区,两者的回滚方式完全不同。
## 7. 收尾验收清单
- [ ] DSM 版本已记录,所用套件中心设置路径与该版本对应(DSM 6 与 DSM 7 不混用)
- [ ] 信任/证书/套件来源设置已核对,第三方发行者已被正确信任(若现场版本提供该选项)
- [ ] 若从 DSM 6.2 升级而来,已确认套件按 DSM 7 签名/权限要求重新适配
- [ ] 官方第三方清单状态已查,并确认清单更新日期与来源范围(仅 Synology 发布的套件)
- [ ] 容量报错已按系统分区占用源逐项排查,没有只看存储管理器数字
- [ ] spk 来源、机型与 DSM 版本匹配已确认
- [ ] 取证日志路径与关键字以现场套件为准;社区命令已标注非官方,结论标 needs-site-confirm
- [ ] 修复前已确认「修复 = 安装最新版」及其兼容性;第三方问题已定位到发行者/开发者联系方式
把这份清单做成安装前检查卡更实用:它大多是"这一版 DSM 的设置长什么样""这个包的发行者是谁"这类需要人核对的事实,脚本帮不上忙。先把五层手工走通,再考虑自动化。
## 相关文章
- [DSM 升级后服务起不来?五层排查决策树](synology-dsm-update-services-not-starting.md)
- [群晖 SSH Permission denied:五层定位决策树](synology-ssh-permission-denied.md)
---
## TCP/IP 状态机
URL: https://ops.jiunotes.top/network/tcp-ip.md
摘要: 从状态机视角理解 TCP,看懂 ss / netstat 每一列,掌握 ESTABLISHED / TIME_WAIT / SYN_SENT / CLOSE_WAIT 等状态含义,附 ss 实战定位与内核调优。
### Answer
TCP 状态机有 11 个状态,运维最常看 ESTABLISHED、TIME_WAIT、CLOSE_WAIT、SYN_SENT。用 `ss -tanp` 按状态计数看趋势:CLOSE_WAIT 涨说明本地应用没 close,TIME_WAIT 堆积看是主动关闭方。`tcp_tw_reuse` 只在出站长连接场景开。
### FAQ
Q: TIME_WAIT 有几千条,要不要调内核参数?
A: 先看是谁在 TIME_WAIT:`ss -tan | grep TIME-WAIT | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn`。若都连外网短连接(调 HTTP API),TIME_WAIT 在本端是正常的主动关闭行为,开 `tcp_tw_reuse=1` 即可;若全堆在某后端 IP,说明客户端频繁建连又关,应改连接池而非调内核。我第一回看到几千条就慌,查半天发现是自己脚本没复用连接。
Q: CLOSE_WAIT 一直涨不掉,是不是内核 bug?
A: 不是内核问题,是本地应用没调 close()。CLOSE_WAIT 含义是对端已发 FIN,在等你应用读完数据并关闭 socket。`ss -tanp | grep CLOSE-WAIT` 看哪个进程占着再查代码。Java 常见是 try-with-resources 没生效或 catch 忘关流;Go 是我遇到过 defer close 写错分支,某些路径永远不关。
Q: ESTABLISHED 突然从几百跳到几万,怎么回事?
A: 先排除业务高峰,再 `ss -tan | awk '$1=="ESTAB"{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn` 看是否某 IP 大量并发。单 IP 异常多是应用 bug 频繁重连或端口探测。另看 `ss -s` 的 orphans grown,持续涨说明有进程崩了但 socket 没释放。
Q: ss -tanp 里进程名显示 ? 怎么办?
A: ss -tanp 需 root 才显示进程,非 root 看到 ?。用 `sudo ss -tanp`,或用 /proc/ 反查:ss -tan 有 inode,`ls -la /proc/net/tcp` 找到对应 inode,再 `lsof | grep `。我第一回在普通用户下跑了半天看不出谁占端口,切 root 一下就清楚。
### Full Content
# TCP/IP 状态机
## 为什么先看状态机
我排网络问题有个习惯:先 `ss -tanp` 把连接按状态分组看一遍,往往比抓包更快定方向。因为 TCP 的连接生命周期被抽象成状态机,**每个状态对应一种「此刻这条连接处在什么阶段」**,异常的状态堆积几乎都能反推出问题出在哪一方(本端应用 / 对端 / 中间链路 / 出站被拦)。看懂状态机,`ss` 输出里那一列 `st` 就不再是密码了。
> 本节的过滤器示例可直接在 Wireshark 里用,抓包对照见 [Wireshark 抓包基础](wireshark-basics.md)。
## 11 个状态与运维含义
下面这张表按「连接从建立到关闭」的顺序整理,重点标出运维最常撞上的几个:
| 状态 | 所处阶段 | 运维解读 | ss 里显示为 |
|---|---|---|---|
| LISTEN | 被动方等连接 | 端口在正常监听;`Recv-Q` 是 `somaxconn` 上限 | LISTEN |
| SYN_SENT | 主动方发 SYN 等 SYN-ACK | 出站建连没被确认,常见于出站被防火墙拦 / 对端不可达 | SYN-SENT |
| SYN_RECV | 被动方收 SYN 未回 | 半连接,`SYN flood` 攻击会把它堆爆 | SYN-RECV |
| ESTABLISHED | 正常数据阶段 | 绝大多数连接都在这里,看数量和增长趋势 | ESTAB |
| FIN_WAIT_1 | 主动方发 FIN 等 ACK | 本端已发起关闭,正常且短暂 | FIN-WAIT-1 |
| FIN_WAIT_2 | 等对端 FIN | 本端发完关闭,在对端也发 FIN | FIN-WAIT-2 |
| **TIME_WAIT** | 主动关闭方回 FIN 后等 2MSL | 短连接高频会堆积,看是谁主动关 | TIME-WAIT |
| **CLOSE_WAIT** | 对端已关,等本端应用 close | **本端应用泄漏/没关**,持续涨是大问题 | CLOSE-WAIT |
| CLOSING | 双方同时主动关闭 | 罕见,正常几乎不出现 | CLOSING |
| LAST_ACK | 等最后一个 ACK | 被动关闭方发完 FIN 等确认 | LAST-ACK |
| (无连接) | 正常关闭完成 | socket 释放 | — |
我特别强调 **CLOSE_WAIT 和 TIME_WAIT 的差别**,这俩最容易混:TIME_WAIT 是**正常的、临时的**(内核替你持有 2MSL 后自动释放,一般是 60 秒),涨一点不可怕,持续堆积才要查;CLOSE_WAIT 是**异常的**,它意味着「对端已经走了,就等你应用把 socket 关掉」,而应用迟迟不关,所以它会一直堆到耗尽 fd,堆积本身就是 bug 信号。
## ss / netstat 实战
**按状态计数(第一眼看全局)**:
```bash
ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn
# 典型输出:几千 ESTAB、几百 TIME-WAIT、若 CLOSE-WAIT 非 0 且持续增长就要查
```
**定位 CLOSE_WAIT 是哪个进程占的**(这是最有价值的一步):
```bash
ss -tanp | grep CLOSE-WAIT
# 输出里 (process,fd) 直接告诉你哪个服务没关 socket
# 非 root 看不到进程时,用 inode 反查:
ss -tan | grep CLOSE-WAIT # 记下 inode
sudo lsof -p 2>/dev/null | grep
```
**TIME_WAIT 分布(看是谁主动关)**:
```bash
ss -tan | grep TIME-WAIT | awk '{print $4,$5}' | cut -d: -f2 | sort | uniq -c | sort -rn | head
# 对端 IP 集中 + 端口是 443/80 → 多半是你这侧在用短连接打对方 API
```
## 我踩过的三个坑
- **CLOSE_WAIT 泄漏**:一个 Go 服务的 HTTP client 每次请求后没 close Response Body,跑一天 CLOSE_WAIT 堆到几千,fd 告警后服务直接开不了新连接。查 `ss -tanp | grep CLOSE-WAIT` 一眼锁定进程,代码里给 body 加 defer Close 解决。**教训:CLOSE_WAIT 持续增长别去调内核,去查代码。**
- **SYN_SENT 卡住**:一次出站调第三方 API 突然全超时,`ss` 里一堆 SYN-SENT 收不到 SYN-ACK。抓包确认是本端 SYN 发出去了没回音,最后发现是安全组把该目的网段 443 出方向放了行(`security group` 出方向规则改过)。**SYN_SENT 集中指向某 IP,多半是出站链路 / 对端不可达,先 ping + traceroute,再看防火墙出方向。**
- **TIME_WAIT 风暴**:压测时用短连接打接口,几秒内 TIME_WAIT 到十万级,新连接建不出(源端口耗尽)。压测侧改连接池,生产侧对**出站**场景开 `net.ipv4.tcp_tw_reuse=1`。
## 内核调优(别乱调)
```bash
# 只对「出站长连接」场景开 tw_reuse,能复用处于 TIME_WAIT 的 socket 给新出站连接
net.ipv4.tcp_tw_reuse = 1
# 调大 TIME_WAIT 上限(默认 1-2 万,短连接服务适当放大)
net.ipv4.tcp_max_tw_buckets = 65536
# 被动方连接队列上限,监听 socket 的 Recv-Q 就是它
net.core.somaxconn = 65535
```
`tcp_tw_recycle` 在 4.x 内核已被移除(会跟 NAT 一起出问题,历史上是各种「丢包」元凶之一),现在别用也看不到它。我一般**先不改参数**,等确认是 TIME_WAIT 堆积且是主动关闭方,再开 `tw_reuse`;CLOSE_WAIT、SYN_SENT 问题根本不用调参数,是应用或链路的事。
## 2MSL 到底在等什么
TIME_WAIT 要等 2 个 MSL(Max Segment Lifetime,Linux 默认 60 秒,即 2×60=120s)不是没来由的,它同时干两件事:
1. **让本连接最后一个 ACK 有「重发」的余地**——万一这个 ACK 丢了,对端重发 FIN,本端还能再回 ACK,保证连接彻底收尾。
2. **让旧连接的迟到报文彻底过期**——同一五元组可能马上被新连接复用,若旧连接的滞留在网报文此刻才到,会被新连接误当成自己的数据。等 2MSL 保证任何旧报文在「两个 RTT」内必然到达或被丢掉,从而不会污染新连接。
所以别试图把 TIME_WAIT「调没」,它是协议正确性的一部分。你能做的是**减少产生它的短连接数量**(连接池),或在出站长连接场景用 `tcp_tw_reuse` 提前复用。真正该消除的是 CLOSE_WAIT 这类「应用没关」的堆积,那才是 bug。
## 抓包看一次完整的状态流转
把状态机和抓包对上,理解会深很多。Wireshark 里 Follow 一条 TCP 流,能清楚看到每个状态对应的报文:
- **建连**:`SYN`(本机 → SYN_SENT)→ 对端回 `SYN+ACK`(本机 → ESTABLISHED)→ 本机回 `ACK`(对端也到 ESTABLISHED)。三条握手。
- **传数据**:大量 `PSH+ACK`,本机 `ss` 里就是 ESTAB,数量随业务涨落。
- **主动关闭**:本端应用调 close → 发 `FIN`(本机 → FIN_WAIT_1)→ 对端回 `ACK`(本机 → FIN_WAIT_2)→ 对端发 `FIN`(本机 → TIME_WAIT,开始等 2MSL)→ 本机回 `ACK`(最终 CLOSED)。
排障时如果抓包看到某条流**卡在 FIN_WAIT_2 很久没进 TIME_WAIT**,说明对端一直没发 FIN——多半是**对端应用不关连接**(被动方漏 close),这时本端只能自己 `SO_LINGER` 强制 RST 断开。这个细节我排一个老版本 Java 客户端挂连接时踩过,`tcpdump` 里满屏 FIN 但永远收不到对端的,最后定位到对端业务代码异常分支没 close。
## 把状态检查纳入监控(SOP)
我固定做两件事,让「状态堆积」在出故障前就被看见:
1. **按状态打点**:用 node_exporter 的 `node_netstat_*`(或自写 exporter 解析 `ss -tan`),对 `CLOSE_WAIT`、`TIME_WAIT`、`SYN_SENT` 各出一条指标。CLOSE_WAIT 持续增长直接告警(应用泄漏),TIME_WAIT 超阈值告警(连接池没开)。
2. **基线对比**:记平时正常值,CLOSE_WAIT 平时应是 0 或个位数,一旦到几百且单调涨,基本就是某服务在泄漏 fd,比等服务 OOM 前干预。
这套下来,「状态机」就从一张静态表变成了能驱动告警的动态观测面。表(上文)+ `ss` 命令 + 抓包流转 + 监控打点,四样配合,TCP 层的绝大多数线上问题我都能在半小时内定方向。
## 相关文章
- [TCP 排障:TIME_WAIT / RST](tcp-troubleshoot.md)
- [Wireshark 抓包基础](wireshark-basics.md)
- [CDN 原理:回源、预热、缓存失效](cdn-principles.md)
---
## TCP 排障决策树:ss + tcpdump 三件套定位 TIME_WAIT / RST / SYN 半连接
URL: https://ops.jiunotes.top/network/tcp-troubleshoot.md
摘要: TCP 排障六症状决策树:TIME_WAIT 堆积、RST 乱飞、SYN 半连接、CLOSE_WAIT 泄漏、MTU 黑洞、连接卡顿。ss -tanp 看状态分布、ss -s 看内核队列、tcpdump -nn 抓具体包,配 nginx 502/504 反向代理场景实战与四个真实踩坑案例。
### Answer
TCP 排障分症状再动手:TIME_WAIT 堆积先看客户端是不是没关连接;RST 乱飞先抓包看是谁发的;
SYN 半连接先看服务端 tcp_max_syn_backlog;CLOSE_WAIT 泄漏十有八九是应用代码没 close;
MTU 黑洞先跑 tcpdump -vvv 看 MSS 值;连接慢先排除 Nagle 算法和延迟 ACK 双重杀。
三条命令打底:`ss -s` 看队列,`ss -tanp` 看状态分布,`tcpdump -nn -i any port ` 抓包。
本文补 FAQ:补充了 nginx 502 RST 来源识别、tcpdump 过滤写法、mtu 黑洞验证方法、CLOSE_WAIT 泄漏排查四个问题,共 9 条问答覆盖全文核心知识点。
### FAQ
Q: ss 和 netstat 到底该用哪个?
A: 新机器用 ss,netstat 是祖传工具但慢且信息少。ss 直接读内核 socket 表,netstat 走 /proc 还得过滤。
排障场景 `ss -tanp` 比 `netstat -an` 快一个数量级,且能显示进程名和 inode。
一句话:能 ss 就别 netstat。
Q: TIME_WAIT 堆积要不要 kill 掉?
A: 不能手动清,内核管的。要么调 `net.ipv4.tcp_tw_reuse=1`(Linux 4.19+ 有 SYN 检测保护),
要么从根上改:让服务端主动关闭连接(`keepalive_timeout` 设小)、客户端用连接池、
扩大端口范围 `net.ipv4.ip_local_port_range`。**这里最容易翻车**——有人用 `sysctl -w net.ipv4.tcp_tw_timeout`,
这参数在老内核存在新内核被删了,别踩。
Q: nginx 报 502 一定是后端挂了?
A: 不一定。502 也可能是后端主动发 RST、upstream 连接被防火墙切断、keepalive 复用失败、
或者 TCP MTU 不对导致大包分片丢失。抓包看 RST 是谁发的就清楚了:
`tcpdump -nn -i any port 8080 'tcp[tcpflags] & tcp-rst != 0'`,看源 IP 是后端还是 nginx。
Q: tcpdump 抓包命令该怎么写过滤?
A: 三段式最常用:`-i <网卡>` 选网卡,`host and port <端口>` 缩小范围,`tcp[tcpflags] & tcp-rst != 0` 只抓 RST。
保存用 `-w file.pcap` 后面用 Wireshark 打开。抓完记得 `Ctrl+C` 停,别忘 `-c 1000` 限定条数防爆盘。
Q: SYN_RECV 爆增是攻击还是 backlog 满了?
A: 两类原因区分方法:`ss -s` 看 `embryonic` 数字,`dmesg | grep -i syn` 看内核日志。
如果是 SYN Flood 攻击,embryonic 持续增长且来自不同 IP;如果是 backlog 满,同一来源 IP 密集,
调 `net.ipv4.tcp_max_syn_backlog` 或 `net.core.somaxconn` 即可。
Q: CLOSE_WAIT 堆积怎么定位泄漏进程?
A: `ss -tanp \| grep CLOSE-WAIT` 直接显示进程名和 PID。
找到进程后 `lsof -p \| grep sock` 看它打开了哪些 socket 没关闭。
典型原因:Java 应用线程池耗尽导致 close() 没执行、Go 协程泄漏、Python 长连接没释放。
最根本的修复是改代码,sysctl 调优只能缓解症状。
Q: 怎么验证是不是 MTU 黑洞?
A: 三步验证:① `ping -M do -s 1472 <目标IP>`(1472 = 1500 MTU - 28 头部),不通就调小;
② `tcpdump -nn 'tcp[tcpflags] & tcp-syn != 0'` 看 SYN 包里的 MSS 协商值;
③ `ip link show` 看两端 MTU 是否一致。
常见的 MTU 问题源:VPN 隧道、VXLAN overlay、云服务商默认 MTU 不是 1500。
Q: TCP 连接建立慢(握手要几秒)是什么原因?
A: 三个常见原因:① Nagle 算法 + 延迟 ACK 双杀(发送端攒小包、接收端延迟确认,互相等待);
② 服务端 `tcp_max_syn_backlog` 太小导致 SYN 排队;
③ DNS 反向解析慢(nginx 默认开 `server_name_in_redirect` 会触发 PTR 查询)。
快速排查:`ss -i` 看 `send_queue` 和 `recv_queue` 是否积压,
`tcpdump` 看 SYN-ACK 往返时间。
### Full Content
# TCP 排障决策树:ss + tcpdump 三件套定位 TIME_WAIT / RST / SYN 半连接
上周给一个客户查 [nginx](https://nginx.org/en/docs/) 502,抓了一下午包才发现是后端 Java 应用 `connection close` 逻辑写反了——后端每次都主动关,nginx keepalive 复用的时候正好赶上关,502 就来了。这种问题不看包永远猜不出来。TCP 排障不是背概念,是**看症状、选命令、抓证据**。
## 60 秒选型:ss / netstat / lsof 三选一
| 工具 | 什么时候用 | 一句话说明 |
|---|---|---|
| `ss` | 90% 的 TCP 排障场景 | 直接读内核 socket 表,快且能带进程名 |
| `netstat` | 只有 ss 装不了的老机器 | 慢,只走 /proc,没有 inode 和队列深度 |
| `lsof -i` | 查某个文件描述符对应哪个连接 | `ss -p` 的补充,看 socket 是打开的文件 |
三个工具都能拿到答案,但排障效率差得远。下面全程用 `ss` 和 `tcpdump`。
## 六症状决策树:先看报错再动手
先看症状,再选命令。症状对应错,命令再对也白搭。
```
用户说"TCP 有问题"或"nginx 502/504"
│
├─ 状态里 TIME_WAIT 一堆 ────── 主动关闭方堆积?调 tcp_tw_reuse
├─ 状态里 CLOSE_WAIT 一堆 ──── 应用代码没 close()?泄漏
├─ 状态里 SYN_RECV 飙升 ────── SYN 半连接攻击 or backlog 满了?
├─ 抓包看到大量 RST ─────────── 端口没监听 or 应用崩溃?
├─ 大包不通小包能通 ──────────── MTU 黑洞?看 MSS
└─ 小包交互明显卡 ───────────── Nagle + 延迟 ACK 双杀?
```
下面逐症状展开,每个都带可执行命令和"你应该看到什么"。
## 症状 1:TIME_WAIT 堆积 —— 主动关闭方出问题
```bash
# 一步看状态分布
ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn
# 看内核层面的 socket 统计
ss -s
```
**你应该看到什么**:
- `TIME-WAIT 5000+` → 主动关闭方是这台机器,检查它是不是短连接客户端
- `ss -s` 里 `TCP: time wait (timewait)` 持续增长 → 有连接没走优雅关闭
- `ss -s` 里 `TCP: orphan` 数字大 → 有进程崩了但 socket 没释放
**修复思路**:
```bash
# 老内核(<4.12):直接复用 TIME_WAIT 端口
sysctl -w net.ipv4.tcp_tw_reuse=1
# 新内核(4.12+):默认已开启,检查是否被禁用
sysctl net.ipv4.tcp_tw_reuse
# 期望输出:net.ipv4.tcp_tw_reuse = 1
# 扩大本地端口范围
sysctl -w net.ipv4.ip_local_port_range="1024 65535"
```
**踩坑**:有人拿 `sysctl -w net.ipv4.tcp_tw_timeout=60` 缩短 TIME_WAIT。这个参数在 4.12 之后被删除了,跑完只提示 unrecognized pattern,不会生效。想加速释放,只能改 `tcp_fin_timeout`(默认 60 秒),但那管的是 FIN_WAIT_2,不是 TIME_WAIT。
## 症状 2:CLOSE_WAIT 堆积 —— 应用代码泄漏
```bash
# 找出谁在 CLOSE_WAIT
ss -tanp | grep CLOSE-WAIT | awk '{print $NF}' | sort | uniq -c | sort -rn
# 看具体 socket 对应的进程
ss -tanp | grep CLOSE-WAIT | head -20
```
**你应该看到什么**:
- 某一个进程(比如 Java 应用)占 CLOSE_WAIT 90% 以上 → 这个应用的 `close()` 逻辑写错了
- CLOSE_WAIT 数字一直涨不掉 → socket 泄漏,进程里没释放文件描述符
- CLOSE_WAIT 只有几十条但一直稳定 → 正常,网络波动下的自然残留
**关键理解**:CLOSE_WAIT 是**被动关闭方**发完第一个 FIN 后等对端发第二个 FIN 的状态。对端早就发了 FIN,你这头不发 ACK,就卡在这里。**根因永远在本地应用**,不在网络。
**修复思路**:
```bash
# 抓一下这个 socket 上的包,看对端什么时候发的 FIN
ss -tanp | grep CLOSE-WAIT | grep
# 拿到 IP:端口 后抓包
tcpdump -nn -i any host and port
```
**你应该看到什么**:抓包里有 `Flags [F.]` 或 `Flags [F.A]` 多次出现,本地一直没回 ACK——应用没读数据所以不发 ACK。
**踩坑**:以为调内核参数能救 CLOSE_WAIT,白搭。CLOSE_WAIT 是应用层 bug,只能改代码。有人上 `sysctl -w net.ipv4.tcp_max_orphans=65535` 想扩大孤儿连接池,那治的是 FIN_WAIT_2 和 orphan socket,不救 CLOSE_WAIT。
## 症状 3:SYN_RECV 飙升 —— 半连接攻击 or backlog 满
```bash
# 看半连接队列
ss -tan | grep SYN-RCV
# 看队列长度上限
sysctl net.ipv4.tcp_max_syn_backlog
sysctl net.core.somaxconn
```
**你应该看到什么**:
- `SYN-RCV` 数千上万条 → 可能是 SYN 洪泛攻击
- `tcp_max_syn_backlog` 只有 128 或 256(默认值)→ 高并发服务下队列会瞬间满
- `ss -s` 里 `TCP: prune called because of low memory` 出现 → 内存压力下内核强制回收
**修复思路**:
```bash
# 打开 SYN cookie(应对 SYN 洪泛)
sysctl -w net.ipv4.tcp_syncookies=1
# 调大半连接队列
sysctl -w net.ipv4.tcp_max_syn_backlog=4096
# 调大全连接队列(要和应用 listen() 的 backlog 参数一起)
sysctl -w net.core.somaxconn=4096
# 缩短 SYN 重传时间
sysctl -w net.ipv4.tcp_synack_retries=2
```
**踩坑**:改 `somaxconn` 没用,因为应用 `listen()` 时写的 backlog 参数没跟上。Nginx 里对应的是 `worker_connections` 和 `keepalive_requests`,Java 是 `listen(2)` 的 backlog 参数。**改了内核不看应用,等于改了个寂寞。**
## 症状 4:RST 乱飞 —— 谁在主动断
```bash
# 抓 RST 包,看源 IP
tcpdump -nn -i any 'tcp[tcpflags] & tcp-rst != 0' -c 100
# 只看某个端口的 RST
tcpdump -nn -i any port 8080 'tcp[tcpflags] & tcp-rst != 0' -w rst.pcap
```
**你应该看到什么**:
- RST 源 IP 是后端应用 IP → 后端主动拒绝(端口没监听、应用崩溃、协议不匹配)
- RST 源 IP 是 nginx / 中间设备 IP → 上游连接超时或防火墙切断
- RST 无前置数据(第一次握手后立刻 RST)→ 服务端根本没启动,或绑定了 127.0.0.1 而非 0.0.0.0
**关键判断**:看 RST 是不是紧跟在 SYN-ACK 之后。如果是——服务端收到 SYN,回完 SYN-ACK,客户端发 ACK 时服务端却回了 RST,说明 SYN-ACK 已经发出去但服务端立刻崩了。这是**服务端启动失败的典型征兆**。
**踩坑**:抓 RST 时不看时序,只看 RST 包数量。RST 有 1000 条不代表一定有问题——短连接客户端每次正常关闭都会产生 1-2 个 RST。**必须按时间戳排序看上下文**,把 RST 前面几个包放一起才看得出问题在哪。
## 症状 5:大包不通小包能通 —— MTU 黑洞
```bash
# 抓包看 MSS 值(最大报文段)
tcpdump -nn -i any port 443 -c 20 -v | grep MSS
# 对比两端 MTU
ip link show eth0 | grep mtu
ping -M do -s 1472 # [Linux](https://www.kernel.org/doc/html/latest/) 探测 MTU
```
**你应该看到什么**:
- 服务端返回 `MSS 1460`,客户端返回 `MSS 536` → 两端路径 MTU 不一致,大包被中间设备悄悄丢弃
- `ping -M do -s 1472` 通、`-s 1492` 不通 → 中间设备 MTU 是 1500,超过就丢
- 抓包看到大量 `TCP Retransmission` 集中在大包 → 大包被黑洞,小包正常
**修复思路**:
```bash
# 服务端强制下发小 MSS
iptables -t mangle -A POSTROUTING -p tcp --tcp-flags SYN,SYN -j TCPMSS --clamp-mss-to-pmtu
# 或者在 nginx 层限制
# 客户端 tcpdump 时加 -M do 强制不分片
tcpdump -nn -i eth0 -M do 'tcp port 443'
```
**踩坑**:`ping` 通了不代表 MTU 没问题。`ping` 默认不加分片,包大小 64 字节,永远能过。要用 `ping -M do -s 1472` 强制不分片探测——Linux 上超过 1472 字节的 ping 包被丢说明中间设备 MTU 只有 1500。**这一条很多人不知道,我在这里翻过一次车。**
## 症状 6:小包交互卡 40ms —— Nagle + 延迟 ACK 双杀
```bash
# 检查应用的 Nagle 设置(应用代码里)
# Netty / Java 需要显式设置
# netty: channel.config().option(ChannelOption.TCP_NODELAY, true)
# Java: socket.setTcpNoDelay(true)
# 抓包看时间戳间隔
tcpdump -nn -i any port 443 -A -tttt | head -50
```
**你应该看到什么**:
- 抓包显示两个小报文间隔**刚好 40ms** 或 **刚好 200ms** → Nagle 在等凑满 MSS,延迟 ACK 在等 40ms
- Telnet / SSH / 单字符输入延迟明显 → 典型的小包交互场景
- TCP_NODELAY 打开后(`-tttt` 时间戳间隔降到毫秒级)→ 确认是 Nagle 问题
**修复**:应用层开 `TCP_NODELAY`(禁用 Nagle)。**这里最容易翻车**——Netty 里 TCP_NODELAY 默认是 true,但你套了 SSL 之后如果没显式设置,就会掉回 false。这个坑很多 Java 团队踩过。
## Cheat Sheet:15 条常用 ss / tcpdump 姿势
| 命令 | 用途 |
|---|---|
| `ss -s` | 内核 socket 总数、各状态数 |
| `ss -tan` | TCP 全连接(含 listen) |
| `ss -tanp` | 带进程名和 inode |
| `ss -tan \| grep TIME-WAIT` | 只看 TIME_WAIT |
| `ss -tanp \| grep CLOSE-WAIT` | 找出 CLOSE_WAIT 泄漏的进程 |
| `ss -tlnp` | 只看 LISTEN 端口(配进程名) |
| `ss -tanp \| grep ESTABLISHED \| wc -l` | 数 ESTABLISHED 连接数 |
| `ss -tan \| awk '{print \$1}' \| sort \| uniq -c` | 状态分布统计 |
| `ss -tano` | 显示 Recv-Q / Send-Q 队列深度 |
| `ss -i` | 显示 TCP 详细信息(CUBIC 参数等) |
| `tcpdump -nn -i any port 8080` | 抓 8080 端口所有包 |
| `tcpdump -nn -i any 'tcp[tcpflags] & tcp-rst != 0'` | 只抓 RST |
| `tcpdump -nn -i any 'tcp[tcpflags] & tcp-syn != 0'` | 只抓 SYN |
| `tcpdump -nn -i any port 443 -c 100 -w x.pcap` | 抓 100 条存文件 |
| `tcpdump -nn -i any 'tcp port 443 and (tcp[13] & 2 != 0)'` | 抓大包(payload > 0) |
## 总结与判断
TCP 排障的核心是**分症状再动手**,六条路径覆盖 90% 场景。三条命令打底:`ss -s` 看队列、`ss -tanp` 看状态分布、`tcpdump -nn` 抓具体包。**别看到 nginx 502 就直接重启后端**——那是症状,不是病根。
**我的判断**:这套决策树覆盖个人运维和中小团队完全够用了。要更深入(BBR 拥塞控制调优、TCP Fast Open、连接迁移、QUIC 排障),得单独开专题。**这一点我也不完全确定**——QUIC 排障的工具链现在还在演进,QUIC 抓包分析器(如 qlog-viewer)的普及度我不确定,遇到具体问题还是查官方文档更靠谱。
## 延伸阅读
- [DNS 排障检测:dig +trace 六症状决策树](dns-troubleshoot.md)
- [Wireshark 抓包入门:53 端口 UDP 抓 DNS 请求](wireshark-basics.md)
- [Nginx 反向代理实战:502/504 三种根因决策树](nginx-proxy.md)
---
## 相关文章
- [nginx + keepalived 主备高可用:VIP 漂移参数矩阵与 6 个真实故障排查](nginx-keepalived.md)
---
## WireGuard 站点到站点 VPN 实战:双网关互联与防火墙路由全解
URL: https://ops.jiunotes.top/network/wireguard-site-to-site-vpn-setup.md
摘要: WireGuard 站点到站点(site-to-site)VPN 怎么搭?本文给一套可复制的双网关配置,覆盖密钥生成、AllowedIPs 路由、禁 NAT、MSS 防 MTU 黑洞、开机自启与故障排查,附巡检纪律。
### Answer
WireGuard 站点互联用 wg-quick 在双网关建加密隧道,AllowedIPs 路由对端网段、禁 NAT、
MSS 夹 40 字节防 MTU 黑洞。静态站点走 /31 点对点小网段,systemd 开机自启并设开机顺序,iptables 只放行对端 UDP 端点。
### FAQ
Q: WireGuard 站点到站点和远程接入(road warrior)有什么不同?
A: 站点互联两端都是网关、长期在线、通常用静态端点,加密的是两个内网之间的流量;远程接入是一台笔记本或一个手机连回家里/公司,端点会变、常走 NAT。配置上站点互联用更小更纯粹的路由网段(如 /31),且两端都要允许对方的私网段进 AllowedIPs。
Q: 为什么不能对站点互联流量做 MASQUERADE(NAT)?
A: 站点互联的本质是"路由"不是"上网"。一旦在网关上做 MASQUERADE,对端看到的源地址会变成网关自己,对端内网的主机真实 IP 就丢了,回包也只对网关、不会回到原始主机。正确做法是纯路由:wg-quick 自动加对端网段路由,内网主机把网关当默认下一跳即可。
Q: /31 网段能用吗?会不会没有可用 IP?
A: 可以。RFC 3021 允许 /31 用于点对点链路,两个地址分别给两端网关。WireGuard 站点互联里网关本身才需要隧道 IP,内网主机不在隧道网段里,所以 /31 完全够用且最干净。如果某些老设备/系统不认 /31,退回 /30(两个可用主机地址)即可。
Q: 跨站点访问慢或某些应用连不上,多半是 MTU/MSS 问题吗?
A: 大概率是的。WireGuard 在真实物理 MTU 上又套了一层加密头,可用载荷比普通网小约 60-80 字节。TCP 的 MSS 没跟着缩,就会出现大包被悄无声息丢弃(MTU 黑洞),表现是 ping 通、小文件能传、大文件或 HTTPS 卡死。在接口上把 TCP MSS 夹小 40 字节(如 1380)基本能解决。
Q: 一端在 NAT 后面收不到对端流量怎么办?
A: 在 NAT 后的一端配置 PersistentKeepalive = 25,让它周期性发保活包打通 NAT 映射。站点互联两端最好都有静态端点(固定 IP 或域名);如果一端没有公网 IP,就只能让有公网 IP 的那端做被动接收方,NAT 后的一端主动维持连接。
### Full Content
# WireGuard 站点到站点 VPN 实战:双网关互联与防火墙路由全解
两个办公室、机房和家里实验室、或者总部与分支机构之间要互访内网,最省事的方案之一是 WireGuard 站点到站点(site-to-site)隧道。它比 OpenVPN 轻、比 IPsec 好配,一个 UDP 端口、一对密钥就能把两个网段打通。我自己在两个固定地点之间跑了两年,踩过的坑集中在"路由和 NAT 搞混""MSS 没夹导致大包丢""开机没自启"。这篇文章就讲一套能直接复制的双网关配置,以及上线后怎么不让它悄悄退化。
## 1. 什么场景需要站点到站点 VPN
先分清两种用法,别一套配置到处套:
- **站点到站点(本文主角)**:两端都是网关,背后各挂一个内网,目标是让这两个内网互相路由。两端长期在线、端点基本固定。
- **远程接入(road warrior)**:一台笔记本或手机临时连回总部,端点会变、常在 NAT 后面。
站点互联的痛点不是"加密"本身,而是"怎么让对端网段的流量走隧道、又不影响本网点对互联网的出站"。下面这套方案就是围绕这个核心。
## 2. 架构与前置条件
典型拓扑是两个站点各有一台接公网的网关,网关后面是各自的内网:
```
站点 A 内网 10.10.10.0/24 ── 网关 A (公网 IP A, 隧道 IP 10.10.9.0/31)
│ 加密 UDP 隧道 (端口 51000)
站点 B 内网 10.10.11.0/24 ── 网关 B (公网 IP B, 隧道 IP 10.10.9.1/31)
```
前置条件:
- 两端网关都能出公网、能互访对方的公网 UDP 端口(建议固定一个端口,比如 51000)。
- 两个内网网段**不能重叠**。如果都是 192.168.1.0/24,隧道建起来路由会打架,先改掉其中一个。
- 隧道只用一个小网段给两个网关自己(/31 足够),内网主机不需要隧道 IP。
- 两端都装好 WireGuard(Ubuntu/Debian 用 `apt install wireguard`,内核模块或 wireguard-go 都行)。
## 3. 生成密钥对
每台网关各自生成自己的私钥和公钥,公钥要发给对端写进对端的 Peer 配置:
```bash
# 在网关 A 上
wg genkey | sudo tee /etc/wireguard/wgA.key
sudo cat /etc/wireguard/wgA.key | wg pubkey | sudo tee /etc/wireguard/wgA.pub
# 在网关 B 上
wg genkey | sudo tee /etc/wireguard/wgB.key
sudo cat /etc/wireguard/wgB.key | wg pubkey | sudo tee /etc/wireguard/wgB.pub
```
注意私钥文件权限要收好(`chmod 600`),公钥可以放心发给对端。
## 4. 写网关配置
站点互联的两端是对称的,区别只在 IP 和端点。下面给网关 A 的完整配置,网关 B 把地址和端点对调即可。
网关 A(`/etc/wireguard/wgA.conf`):
```ini
[Interface]
Address = 10.10.9.0/31
ListenPort = 51000
PrivateKey = <网关 A 的私钥>
PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostDown = iptables -D FORWARD -i %i -j ACCEPT
[Peer]
# 网关 B
PublicKey = <网关 B 的公钥>
Endpoint = <公网 IP B>:51000
AllowedIPs = 10.10.11.0/24, 10.10.9.0/31
# 如果 B 在 NAT 后,A 也加一行 PersistentKeepalive = 25
```
网关 B 把 `Address` 改成 `10.10.9.1/31`,`AllowedIPs` 改成 `10.10.10.0/24, 10.10.9.0/31`,`Endpoint` 指向 A 的公网 IP。关键点:**AllowedIPs 写的是"对端内网 + 隧道小网段"**,它同时告诉 WireGuard 两件事——哪些目标地址的包要进隧道、以及哪些来源地址的包允许解密进来。
## 5. 防火墙与路由要点
这一节是站点到站点最容易翻车的地方,记住一句话:**站点互联是路由,不是上网,绝对不要对隧道流量做 MASQUERADE。**
- `wg-quick` 启动时会自动按 AllowedIPs 加路由,内网主机只要把网关当默认下一跳(通常已经是),就能访问对端网段,不用在主机上改任何东西。
- 如果之前为了远程接入在 POSTROUTING 里写了 `MASQUERADE` 针对 wg 接口,**站点互联场景下要删掉**,否则对端主机看到的源 IP 变成你的网关,回包回不来。
- 出于安全,建议在两端各加一条只放行对端公网端点访问 51000 的规则,而不是对全网开放:
```bash
iptables -A INPUT -p udp --dport 51000 -s <对端公网 IP> -j ACCEPT
iptables -A INPUT -p udp --dport 51000 -j DROP
```
- 需要限制跨站点能访问什么(比如只允许办公网访问机房的特定服务),在 FORWARD 链上加细粒度规则,例如禁止跨站点 SSH:
```bash
iptables -A FORWARD -i wgA -p tcp --dport 22 -j REJECT
```
## 6. MTU 与 MSS 陷阱
WireGuard 在物理链路 MTU 之上又加了加密头,实际可用载荷比普通以太网少约 60-80 字节。如果不处理,TCP 大包会被悄无声息丢弃,现象很典型:**能 ping 通、能开小网页,但传大文件、跑 HTTPS 或数据库同步就卡死或中断**。这就是 MTU 黑洞。
最稳妥的修法是在 WireGuard 接口上把 TCP MSS 夹小:
```ini
[Interface]
MTU = 1380
# 或在 PostUp 里用 iptables 夹 MSS
PostUp = iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss 1380
```
经验值:物理 MTU 1500 时,WireGuard 接口 MTU 设 1420,MSS 设 1380 基本通吃。如果中间还套了 VLAN 或 PPPoE(MTU 1492 甚至更低),相应再减。别瞎设成 1400 以下,太小会多分片、降吞吐。
## 7. 启动与连通验证
两端都用 systemd 管理,保证重启后自动起来:
```bash
sudo systemctl enable --now wg-quick@wgA # 网关 A
sudo systemctl enable --now wg-quick@wgB # 网关 B
# 看隧道状态和握手
sudo wg show
# 期望看到 latest handshake 是最近的时间、transfer 有数据
# 从 A 内网主机 ping B 内网主机
ping 10.10.11.x
# 再看路由表确认对端网段走了 wg 接口
ip route | grep wg
```
`wg show` 里如果没有 handshake、transfer 一直是 0,说明端点不可达或密钥/AllowedIPs 不对,回到第 4 节核对。
## 8. 常见故障排查
- **握手成功但 ping 不通对端内网**:九成是 AllowedIPs 没写对端内网段,或本端内网主机没把网关当默认路由。用 `ip route` 确认对端网段下一跳是 wg 接口。
- **能 ping 小包、大文件必败**:MTU/MSS,见第 6 节。
- **一端在 NAT 后收不到流量**:加 `PersistentKeepalive = 25` 打通 NAT 映射。
- **重启后隧道没起来**:确认 `systemd enable` 了,且配置路径是 `/etc/wireguard/wgA.conf` 与 `wg-quick@wgA` 对应。
- **跨站点某些服务连不上但网络通**:多半是你在 FORWARD 或对方防火墙挡了对应端口,逐条排查链规则,别上来就怀疑 WireGuard。
## 9. 上线后的巡检与防退化纪律
站点互联最容易"上线好好的,三个月后悄悄坏",靠这几条纪律兜住:
- **监控握手与流量**:把 `wg show` 的 latest handshake 和 transfer 接进你的监控(Prometheus node-exporter 或黑盒探测都行),超过 N 分钟没握手就告警。别等用户投诉"机房连不上"才发现。
- **端点 IP 变动要同步**:如果某一端公网 IP 是动态的,用动态域名而不是写死 IP;改了域名或 IP,两端 Endpoint 一起改,并重新握手验证。
- **禁 NAT 是铁律**:任何人在网关上加 MASQUERADE 规则前,先确认它不是作用在 wg 接口上。建议把站点互联的 FORWARD 放行规则和 MSS 夹规则写进配置文件的 PostUp,随隧道一起加载,避免手动加完某天被清掉。
- **密钥定期轮换但有记录**:WireGuard 没有证书体系,换密钥就是改 PrivateKey/PublicKey 并同步对端。轮换前先在维护窗口通知,改完用 `wg show` 和跨站点 ping 双重确认,旧密钥在确认稳定后再删除。
- **配置进版本管理**:`/etc/wireguard/*.conf` 抽成模板进 Git,密钥单独用 secrets 管理,谁改了哪台网关、AllowedIPs 改了什么,回滚就是 `git revert`。不上这套,设备一多(多分支、多站点)随便改一个 AllowedIPs 就全乱。
- **不要为"图省事"把站点互联和远程接入混在同一接口**:两者策略不同(一个禁 NAT、一个常 NAT),分开两个接口(wgA 站点到站点、wg0 远程接入)清晰得多,排错也快。
## FAQ
WireGuard 站点到站点和远程接入(road warrior)有什么不同?
站点互联两端都是网关、长期在线、通常用静态端点,加密的是两个内网之间的流量;远程接入是一台笔记本或一个手机连回家里/公司,端点会变、常走 NAT。配置上站点互联用更小更纯粹的路由网段(如 /31),且两端都要允许对方的私网段进 AllowedIPs。
为什么不能对站点互联流量做 MASQUERADE(NAT)?
站点互联的本质是"路由"不是"上网"。一旦在网关上做 MASQUERADE,对端看到的源地址会变成网关自己,对端内网的主机真实 IP 就丢了,回包也只对网关、不会回到原始主机。正确做法是纯路由:wg-quick 自动加对端网段路由,内网主机把网关当默认下一跳即可。
/31 网段能用吗?会不会没有可用 IP?
可以。RFC 3021 允许 /31 用于点对点链路,两个地址分别给两端网关。WireGuard 站点互联里网关本身才需要隧道 IP,内网主机不在隧道网段里,所以 /31 完全够用且最干净。如果某些老设备/系统不认 /31,退回 /30(两个可用主机地址)即可。
跨站点访问慢或某些应用连不上,多半是 MTU/MSS 问题吗?
大概率是的。WireGuard 在真实物理 MTU 上又套了一层加密头,可用载荷比普通网小约 60-80 字节。TCP 的 MSS 没跟着缩,就会出现大包被悄无声息丢弃(MTU 黑洞),表现是 ping 通、小文件能传、大文件或 HTTPS 卡死。在接口上把 TCP MSS 夹小 40 字节(如 1380)基本能解决。
一端在 NAT 后面收不到对端流量怎么办?
在 NAT 后的一端配置 PersistentKeepalive = 25,让它周期性发保活包打通 NAT 映射。站点互联两端最好都有静态端点(固定 IP 或域名);如果一端没有公网 IP,就只能让有公网 IP 的那端做被动接收方,NAT 后的一端主动维持连接。
## 相关文章
- [dnsmasq 配置深度实战:一份完整模板 + 中文网络下的 4 个真实踩坑](dnsmasq-config.md)
- [iptables 端口转发实战:DNAT/SNAT 与 NAT 回环避坑](iptables-port-forwarding.md)
- [零信任网络入门:从边界防御到身份驱动的访问控制](zero-trust-network.md)
---
## Wireshark 抓包基础
URL: https://ops.jiunotes.top/network/wireshark-basics.md
摘要: Wireshark 30 条常用过滤器、关键字段速查、TCP 重传、HTTP/2 过滤、TLS 抓包。含 tcpdump 命令行对照。
### Answer
Wireshark 常用过滤器 30 条,从 TCP 重传(`tcp.analysis.retransmission`)到 HTTP/2(`http2`)到 TLS(`tls.handshake`)。命令行常用 `tcpdump -i any host and port `。
### FAQ
Q: 网络慢,Wireshark 先看什么?
A: 先看 TCP 重传(tcp.analysis.retransmission)和 RTT 异常(tcp.analysis.ack_rtt)。重传多说明丢包,RTT 大说明链路拥塞,再对症下药。
Q: 如何快速定位是服务端还是客户端问题?
A: 看 SYN 与 SYN-ACK 间隔。客户端发 SYN 后长时间没 SYN-ACK,是服务端或中间链路问题;有 RST 立即返回,是端口未监听或防火墙拦截。
Q: 抓包看到大量 TCP Retransmission 怎么办?
A: 先排除抓包软件自身丢包(Check for dropped packets),再查链路 MTU、交换机端口错误计数、链路利用率。用 tshark 统计重传源地址定位。
Q: HTTPS 抓包解密怎么做?
A: 用 SSLKEYLOGFILE 环境变量导出会话密钥(浏览器/应用支持),Wireshark 里配置 TLS 密钥日志文件路径即可解密。注意只在授权范围做。
### Full Content
# Wireshark 抓包基础
## 抓包前先想清楚三个问题
我抓包第一反应从来不是打开软件就开始录,而是先定三件事,省得抓完一万个包却答不上关键问题:
1. **在哪个网卡抓**:抓包机要和问题链路「同一路由」,跨网段抓不到中间链路。一次我在 A 机房抓 B 机房的 502,抓出来全是本机回环流量,白忙半小时——根因是两台机不在同一二层域,得在网关或目标机本地各抓一份对拍。
2. **抓多大数据**:默认别无限抓。先用过滤器限 `host <问题机> and port <端口>`,控制文件体积,也方便事后快速定位。
3. **时间窗口要对齐**:故障是 14:23 发生的,你要抓 14:20-14:30,别从头一直抓到尾。抓之前把系统时间、NTP 同步确认好,不然回溯时对不上监控曲线。
我固定做的第一件事是抓包前 `ethtool -S <网卡>` 记一下丢包计数,抓完再对比一次——如果抓取端自己就丢了包,那分析出来的「重传」可能是抓包软件丢的,不是真实链路丢的。
## 常用过滤器(30 条)
### 网络层
- `ip.addr == 1.2.3.4`
- `tcp.port == 80`
- `udp.port == 53`
- `icmp.type == 8`(Ping Request)
### TCP 分析
- `tcp.analysis.retransmission` —— 重传
- `tcp.analysis.dup_ack` —— 重复 ACK
- `tcp.analysis.zero_window` —— 窗口关闭
- `tcp.flags.syn == 1 and tcp.flags.ack == 0` —— SYN
- `tcp.flags.reset == 1` —— RST
### HTTP / HTTPS
- `http.request.method == "GET"`
- `http.response.code == 502`
- `tls.handshake.type == 1` —— Client Hello
### DNS
- `dns.flags.response == 1`
- `dns.qry.name == "example.com"`
## 追踪 TCP 流:一次看全
过滤器能圈出「这一类包」,但排查时往往要看「这一条连接从握手到断开的全过程」。这时用「追踪流」(Follow TCP Stream / Follow UDP Stream)最直观:
- 右键某个包 → **Follow → TCP Stream**,能并排看到客户端和服务端的完整对话(明文 HTTP 直接可读,TLS 看到的是密文)。
- 我排 nginx 502 时,Follow 上去一眼看到:客户端请求正常发出,nginx 侧回了个 `502 Bad Gateway`,后面立刻 `RST`。跟着这条流翻到最上游,才发现是 upstream 的 8080 端口的后端进程在 `tcpdump` 里根本没监听——应用挂了,不是网络问题。
配合两个统计利器能少翻很多包:
```bash
# tshark 统计重传最多的源(快速锁定是哪台在重传)
tshark -r input.pcap -Y 'tcp.analysis.retransmission' -T fields -e ip.src | sort | uniq -c | sort -rn | head
# 看每个流的状态(完成 / 被重置 / 还在传)
tshark -r input.pcap -T fields -e _ws.col.Frame_Info | grep -i 'reset\|fin' | head
```
## 一次真实 502 排障记录
某次接口偶发 502,监控只有零星尖刺,抓包才定位到:后端某台 pod 的 kernel 在负载高时 **socket 缓冲区耗尽**,表现为大量 `tcp.analysis.zero_window`(发送方窗口被压成 0)。我在 Wireshark 里先过滤 `tcp.analysis.zero_window` 确认了这个特征,再用 `tshark -Y 'tcp.analysis.zero_window' | wc -l` 量化了窗口关闭次数随时间的分布,对上了压测时间点。修复是调大 `net.core.netdev_max_backlog` 和 socket 缓冲参数,配合 nginx `proxy_read_timeout` 收紧,`zero_window` 基本归零。
这篇侧重「怎么用工具看」,定位到具体 502/504 根因的完整链路(含 nginx 侧配置对照)见 [Wireshark 抓包实战:定位 nginx 502 / 504 根因](wireshark-nginx-troubleshoot.md)。
## tcpdump 命令行对照
```bash
# 抓特定主机
tcpdump -i any host 1.2.3.4 -nn -c 100
# 抓特定端口
tcpdump -i any port 443 -nn
# 抓 RST
tcpdump -i any 'tcp[tcpflags] & (tcp-rst) != 0'
```
## FAQ
- q: [Wireshark](https://www.wireshark.org/docs/) 抓不到包怎么办?
a: 最常见的三个原因:① 网卡选错了——默认选的是 loopback 或虚拟网卡,选对物理网卡;② 没有权限——[Linux](https://www.kernel.org/doc/html/latest/) 下需要 root 或加入 pcap 用户组;③ 过滤器写错了——先清空过滤器看看有没有原始流量,确认有流量后再加过滤条件。
- q: 怎么抓 HTTPS 内容?
a: HTTPS 加密后直接抓包看不到明文。两种思路:① 在客户端安装 Wireshark 的 CA 证书(Chrome/ Firefox 可以配置信任根证书),解密 TLS;② 在代理层抓包(如 mitmproxy),代理解密后再转发。生产环境慎用方法一,涉及敏感数据有风险。
- q: 怎么找出网络中的重传和丢包?
a: 用过滤器 `tcp.analysis.retransmission` 抓重传,`tcp.analysis.duplicate_ack` 抓重复 ACK。重传通常是拥塞或丢包的信号,结合 `tcp.time_delta` 看间隔。如果重传集中发生在某个 IP,优先排查那个节点的网络链路。
- q: tcpdump 和 Wireshark 怎么选?
a: 远程服务器只能命令行,用 tcpdump 抓完拷回本地分析;本地图形界面首选 Wireshark,可视化过滤和追踪 TCP 流更方便。两者过滤器语法基本一致,学会一个另一个很快上手。
- q: 抓包文件太大怎么处理?
a: 先用过滤器缩小范围再抓(比如 `host 1.2.3.4 and port 80`),不要无脑全量抓。如果已经抓大了,用 Wireshark 的"文件 → 导出特殊分组"按条件导出子集,或者用 `tshark -R "tcp.port==80" -r input.pcap -w output.pcap` 命令行裁剪。
## 常见误判与「抓包陷阱」
抓包最怕的不是抓不到,而是**抓到了但读反了**。我反复踩过的几个:
- **把抓包端自身丢包当成链路丢包**:`tcp.analysis.dropped_frames` 是抓包软件(内核 ring buffer)丢的,不代表网络真丢包。分析前先确认 ring buffer 够不够大、`eth -S` 有没有 `rx_missed`,再谈链路。
- **把重传当成丢包,但其实是慢 ACK**:`retransmission` 有时是中间节点延迟导致 ACK 迟到触发 PTO(persistence timer),不是真丢。配合 `tcp.analysis.fast_retransmission` 与窗口曲线区分:fast retransmission 多为真丢,PTO 重传要再看 RTT 抖动。
- **TLS 握手上看到的「失败」其实是证书 / cipher 协商问题**:抓包只看到 `TLSV1.3 handshake` 后直接 `alert`,得看 alert 类型(`bad_certificate` / `handshake_failure`)才能定位到是证书过期、SNI 错配还是 cipher 不支持。
- **时间戳不可信**:抓包机和服务器的 NTP 没对齐,Follow 流里的时间差全是错的,排障时先 `chrony -q` 确认同步。
我的经验是把「抓包 + 计数器 + 日志」三件套配合,不只看包:`ethtool -S` 的计数器看物理 / 内核层丢包,`ss -ti` 看 socket 层缓冲与重传,`dmesg` 看有没有网卡 / 驱动告警,包只是证据链的一环。单靠 Wireshark 看包容易在「最后一公里」误判,三件套交叉验证才稳。
## 抓包前确认同步与权限
开始之前花十秒把两个基础项确认掉,能避开一大类「假现象」:
- **NTP 同步**:`chrony tracking` 或 `timedatectl status` 看 `NTP synchronized: yes`。抓包机、网关、目标机三方时间对齐,Follow 流里的时间戳才有意义。时间没对齐时,跨机抓包对拍几乎无法判断先后。
- **抓包权限**:非 root 抓包需要把用户加入 `wireshark`/`pcap` 组并 `capsh` 配置 `+ep cap_net_raw,cap_net_admin`。生产机常用非特权抓包减少风险,但配置不当时会静默丢包或只抓到部分流量。
- **网卡选对**:多网卡机器先 `ip -br link` 看物理网卡名,别抓到 `lo`、`veth*`、`docker0` 上。容器化环境里,Pod 流量走 `veth` 与宿主 `eth0` 是两套命名空间,跨命名空间要各抓一份。
## 相关文章
- [TCP/IP 状态机](tcp-ip.md)
- [Wireshark 抓包实战:定位 nginx 502 / 504 根因的完整排查链路](wireshark-nginx-troubleshoot.md)
- [CDN 原理:回源、预热、缓存失效](cdn-principles.md)
---
## Wireshark 抓包实战:定位 nginx 502 / 504 根因的完整排查链路
URL: https://ops.jiunotes.top/network/wireshark-nginx-troubleshoot.md
摘要: 从 nginx 502/504 报错到 Wireshark 抓包定位根因,覆盖 RST 来源识别、TIME_WAIT 堆积验证、upstream keepalive 复用心跳、TCP MTU 黑洞四个实战场景,含 tshark 命令行一键过滤脚本。
### Answer
nginx 502/504 排障核心:先确认 RST 是谁发的(`tcpdump 'tcp[tcpflags] & tcp-rst != 0'`),
再看 TIME_WAIT 堆积(`ss -tan \| awk '{print $1}' | sort | uniq -c`),
最后验 keepalive 和 MTU。Wireshark 过滤 `tcp.flags.rst == 1 || tcp.analysis.retransmission` 最实用。
tshark 可一键过滤,无需 GUI。
### FAQ
Q: 502 和 504 有什么区别,抓包怎么看出来?
A: 502 是 nginx 连不上后端(TCP 三次握手失败 / RST),504 是后端连上了但一直不回响应(超时)。 抓包看:502 → 看到 RST 或 SYN 无回复;504 → 看到握手成功但无 DATA 包,超时后 nginx 发 RST 关连接。
Q: Wireshark 和 tcpdump 什么时候用哪个?
A: 快速确认问题用 tcpdump/tshark(命令行,适合远程服务器); 深度分析用 Wireshark GUI(图形化、过滤强、能按流追踪)。 生产服务器一般没 GUI,先 tcpdump 抓到 .pcap 再拉到本机用 Wireshark 分析。
Q: 抓包命令怎么写最省事?
A: 一行搞定:`tcpdump -nn -i any port 80 or port 8080 -w /tmp/nginx.pcap &` 然后复现 502,再 `kill %1` 停抓包。 用 tshark 一行过滤更狠:`tshark -f 'tcp port 8080 and (tcp[13] & 4 != 0)' -T fields -e ip.src -e ip.dst -e tcp.flags`
Q: Wireshark 里怎么追踪 TCP 流?
A: 右键任意 TCP 包 → Follow → TCP Stream,一键还原完整会话,一眼看出谁先发 RST、谁超时。 配合统计菜单里 Endpoint 和 Conversations 视图,能快速定位流量异常方。
Q: 如何判断是 MTU 黑洞而不是连接问题?
A: 特征:小包通、大包不通,telnet 能通但 curl 报 timeout。 Wireshark 过滤 `tcp.len > 1460` 看是否有分片丢包; 服务端 `ip link show` 看 MTU,客户端 `tcpdump -nn 'tcp[tcpflags] & tcp-syn != 0'` 看 MSS 协商值。
### Full Content
# Wireshark 抓包实战:定位 nginx 502 / 504 根因的完整排查链路
上周帮一个客户查 [nginx](https://nginx.org/en/docs/) 502,问题拖了三天——前两个运维看日志只看到 502,没有更多线索。我上去抓了个包,10 分钟定位:是后端 Java 应用开了 `keepalive` 但没设心跳,nginx 的 keepalive 连接过了空闲超时被中间防火墙切掉,复用时报 502。**只看日志永远查不出来,必须抓包**。
## 为什么 502/504 必须抓包
nginx 错误日志里 502 通常只写:
```
upstream timed out (110: Connection timed out) while connecting to upstream
```
`110` 是 [Linux](https://www.kernel.org/doc/html/latest/) 内核错误码,翻译成人话就是"连不上"。但**为什么连不上**,可能原因有十几个:
- 后端进程崩溃了
- 后端端口变了(健康检查没同步)
- 中间防火墙切了 keepalive 连接
- TCP TIME_WAIT 堆积占满端口
- MTU 不匹配导致大包丢失
- DNS 解析慢了
**日志看不出来,抓包才能看见是谁发了 RST、谁超时了、有没有分片丢包。**
## 第一步:用 tcpdump 抓原始包
生产服务器通常没有 [Wireshark](https://www.wireshark.org/docs/) GUI,先用 tcpdump 抓到 .pcap 文件,再拉到本机分析。
```bash
# 抓 nginx 与后端的通信(假设后端在 8080 端口)
tcpdump -nn -i any 'port 8080' -w /tmp/nginx.pcap &
# 用 & 放后台,复现一次 502,然后 kill %1 停抓
```
关键参数说明:
- `-nn` 不解析域名和端口名,直接显示 IP 和数字端口,速度快且不触发 DNS 查询干扰
- `-i any` 抓所有网卡,适合多网卡环境
- `-w file.pcap` 保存原始包,后续用 Wireshark 打开
**抓完记得及时停**,不然 `/tmp/nginx.pcap` 会越来越大,压垮磁盘。
## 第二步:用 tshark 命令行过滤关键包
不需要 GUI 时,tshark 是最快的过滤工具。
```bash
# 只看 RST 包(谁发出来的决定了是客户端还是服务端问题)
tshark -r /tmp/nginx.pcap -Y 'tcp.flags.rst == 1' -T fields -e ip.src -e ip.dst -e tcp.seq
# 只看重传包(网络拥塞或丢包的铁证)
tshark -r /tmp/nginx.pcap -Y 'tcp.analysis.retransmission' -T fields -e ip.src -e ip.dst
# 只看 TIME_WAIT 状态的包
tshark -r /tmp/nginx.pcap -Y 'tcp.flags.fin == 1' -T fields -e ip.src -e ip.dst -e tcp.seq
# 只看大于 1460 字节的 TCP 载荷(MTU 问题信号)
tshark -r /tmp/nginx.pcap -Y 'tcp.len > 1460' -T fields -e ip.src -e ip.dst -e tcp.len
```
这四个过滤器覆盖了 80% 的 nginx 502/504 根因。
## 第三步:拉到本机用 Wireshark 深度分析
把 .pcap 文件拖到本机 Wireshark,重点看三个地方。
### 3.1 Follow TCP Stream —— 一锤定音
找到任意一条 nginx ↔ 后端的 TCP 会话,右键 → **Follow → TCP Stream**。
你会看到完整的六步对话:
```
Client (nginx) Server (backend)
SYN ─────────────────────────────────────→
←──────────────────────────────────── SYN-ACK
ACK ─────────────────────────────────────→
DATA (POST /api/xxx) ──────────────────→
(无响应,30s 后)
Client sends RST ─────────────────────→
```
最后这一行 RST 如果是 nginx 发的 → 后端超时(504);如果是后端发的 → 后端主动断连(502)。
### 3.2 Endpoint 统计 —— 看流量分布
**Statistics → Endpoints**,按字节数排序,一眼看出哪台机器是流量异常方。
如果后端 IP 的出站字节数接近 0 但入站正常 → 后端没有响应数据。
### 3.3 Conversations 视图 —— 看连接模式
**Statistics → Conversations → IPv4**,切换显示为 **TCP**,可以看到:
- 连接总数
- 每个连接的 Duration(持续时长)
- Packet 数 / Byte 数
**翻车信号**:大量连接 Duration 为 0,说明都是瞬时建立就断开的,典型 keepalive 配置错误或防火墙切连。
## 四个实战场景速查
### 场景 A:RST 来自后端
**现象**:Wireshark 里 nginx 发 SYN,后端回 RST。
**原因**:后端服务挂了,或端口监听地址不对(比如只监听了 127.0.0.1 没听 0.0.0.0)。
**验证命令**:
```bash
ss -tlnp | grep 8080
# 应该看到 LISTEN 0.0.0.0:8080,不是 127.0.0.1:8080
```
### 场景 B:RST 来自 nginx
**现象**:握手成功,nginx 发数据后长时间无响应,最后 nginx 发 RST。
**原因**:后端处理超时,nginx `proxy_read_timeout` 默认 60s,超时主动断。
**修复方向**:
```nginx
location / {
proxy_read_timeout 120s; # 给后端更多时间
proxy_send_timeout 120s;
proxy_connect_timeout 10s;
}
```
### 场景 C:TIME_WAIT 堆积
**现象**:`ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn` 看到 TIME-WAIT 几千个。
**原因**:nginx 作为主动关闭方,短时间内大量建连断连,TIME_WAIT 来不及回收。
**影响**:新连接建不上,表现为间歇性 502。
**修复**:
```bash
# Linux 4.19+ 安全启用(内核有 SYN 攻击检测保护)
sysctl -w net.ipv4.tcp_tw_reuse=1
# 扩大 ephemeral port 范围
sysctl -w net.ipv4.ip_local_port_range="1024 65535"
```
### 场景 D:MTU 黑洞
**现象**:小包能通,大包不通;telnet 能连上但 curl 超时。
**验证**:
```bash
# 看本地 MTU
ip link show | grep mtu
# 抓 SYN 包看 MSS 协商值(MTU - 40 = MSS)
tcpdump -nn -i any 'tcp[tcpflags] & tcp-syn != 0' -c 10
```
**修复**:两端 MTU 对齐,或开启 PMTU 发现(`net.ipv4.tcp_mtu_probing=1`)。
## RST 到底是谁发的:两个暗号
抓包定位 502,最难的不是「看到 RST」,而是**判定 RST 到底是谁发的**——后端主动断、nginx 超时断、还是中间 LB / 防火墙切的?这三种根因修法完全不同,判错方向等于白抓。我固定用两个暗号定位:
**第一个暗号看 TTL。** 同一条流里正常数据包走过的路径是固定的,TTL 到一个稳定值;但某个 RST 包的 TTL 明显偏离这个稳定值(忽高忽低、差了一截),基本就是中间设备代发 / 伪造的 RST。端点自己发的 RST 会走正常路径,TTL 和数据包一致。TTL 跳变是「中间有人在切连」最硬的证据。
**第二个暗号看 seq 对不接得上。** 真·端点 RST 的 seq 会落在上一条包之后的合法窗口里;如果是乱序 RST(seq 对不上、明显是补发的),多半是中间设备或内核在上游已断之后补的乱序保护包,往往意味着真正的断连发生在 RST 之前。
再叠一条:**看你在哪台设备上抓到的。** 在 nginx 节点抓到、源 IP 是后端的 RST,才认定后端发的;如果客户端侧就看到了本该后端才发的 RST,说明中间有人动手了。TTL、seq、抓包点三个证据叠一起,RST 的来源基本就钉死了,不会被「后端自己断」的假象带偏。
## tshark 一键排障脚本
把上面四个场景串成一个脚本,一条命令出结论:
```bash
#!/bin/bash
# wh-examine.sh - Wireshark 502 快速诊断
PCAP=${1:-/tmp/nginx.pcap}
[ ! -f "$PCAP" ] && echo "用法: $0 " && exit 1
echo "=== 1. RST 来源 ==="
tshark -r "$PCAP" -Y 'tcp.flags.rst == 1' -T fields -e ip.src -e ip.dst 2>/dev/null | head -5
echo -e "\n=== 2. 重传统计 ==="
tshark -r "$PCAP" -Y 'tcp.analysis.retransmission' 2>/dev/null | wc -l | xargs echo "重传包数:"
echo -e "\n=== 3. TIME_WAIT 相关 FIN 包 ==="
tshark -r "$PCAP" -Y 'tcp.flags.fin == 1' 2>/dev/null | wc -l | xargs echo "FIN 包数:"
echo -e "\n=== 4. 大包 (>1460B) 检查 ==="
tshark -r "$PCAP" -Y 'tcp.len > 1460' 2>/dev/null | wc -l | xargs echo "大包数:"
echo -e "\n=== 5. 异常连接(Duration=0 的 TCP 会话)==="
tshark -r "$PCAP" -Y 'tcp' -T fields -e ip.src -e ip.dst 2>/dev/null \
| sort | uniq -c | sort -rn | head -5
```
## 排查流程速查表
| 症状 | 优先看什么 | 关键过滤器 / 命令 |
|---|---|---|
| 间歇性 502 | RST 来源 | `tcp.flags.rst == 1` |
| 固定 URL 超时 504 | TCP Stream 长度 | Follow TCP Stream |
| 高峰期才 502 | TIME_WAIT 堆积 | `ss -tan \| awk '{print $1}'` |
| 小包通大包不通 | MTU / MSS | `tcp.len > 1460` |
| 连接建立后无响应 | 重传包 | `tcp.analysis.retransmission` |
## 生产环境的持续抓包纪律
上面那套是「出事了再抓」。真正拉开差距的是**平时就有包可抓、抓了就能定位**,我在生产环境靠下面几条纪律兜底。
### 别让抓包变成一次性动作
生产 nginx 节点我常备一条后台抓取,只在高峰期或排障时开,平时关掉避免拖垮磁盘:
```bash
# 带大小上限 + 轮转,防止 /tmp 被打满
tcpdump -nn -i any 'port 80 or port 8080' -w /tmp/nginx.pcap -C 50 -W 4 &
# -C 50 每 50MB 切一个文件,-W 4 最多保留 4 个,自动轮转
```
关键是 `-C`/`-W` 这两个参数——我见过一次因为忘了停 tcpdump,两天后 `/tmp` 被 pcap 撑爆、连登进去重启都卡住。带上轮转上限,抓包就不再是「用完记得关」的人肉纪律,而是自限的。
### 502/504 要和后端、网络两条线同时抓
只看 nginx 一端永远差一层。定位根因时我固定「两端同时抓」:nginx 节点抓 80/443 入向,后端应用节点抓 8080,中间如果有 LB/防火墙也在它上面抓一份。三份 pcap 用**同一时间戳**对齐(提前 `chronyd` 同步 NTP),再交叉看 RST 到底是谁先发,结论才站得住。单端抓包很容易把「中间设备切的连接」误判成「后端自己断」。
### 容量与 TIME_WAIT 的常态化监控
502 不一定要等出事才查。我把两条量挂进 Prometheus:`ss -tan | awk '{print $1}' | grep -c TIME-WAIT` 每 30 秒采一次成 gauge,配一条「TIME_WAIT 数量 10 分钟持续上涨」的告警;再配合 nginx 的 `stub_status` 看 active/waiting 连接。这样在客户投诉之前,端口耗尽、连接堆积这些「迟早要 502」的信号就被提前抓住了,处理窗口从「故障后 10 分钟抓包」前移到「趋势异动时调 keepalive 参数」。
### 复盘模板
每次排完 502/504,我强制把结论填进一个固定模板存档:**症状 → 关键过滤器 → 抓到的铁证包 → 根因 → 改了什么配置 → 如何防止复发**。半年下来这份存档本身就是最好的排障知识——下次再遇到「间歇性 502」,先翻存档看是不是同一类根因,省掉重新试错的时间。
## 写在最后
nginx 502/504 的本质是**网络层发生了什么,应用层只记录了结果**。抓包是把结果逆推到原因的唯一可靠方法。学会 Follow TCP Stream 和这四个过滤器,80% 的排障不再需要猜。
## 相关文章
- [Docker 环境下 nginx 502 排查:127.0.0.1 vs 服务名、DNS 解析、健康检查五坑指南](docker-nginx-502.md)
- [TCP 排障决策树:ss + tcpdump 三件套定位 TIME_WAIT / RST / SYN 半连接](tcp-troubleshoot.md)
- [nginx 504 gateway timeout 排查:6 类根因决策树](nginx-504-troubleshoot.md)
- [nginx 装 ModSecurity 3.0:生产 WAF 落地与误报治理实录](nginx-waf-modsecurity.md)
- [Linux 网络内核参数调优:sysctl 生产参数矩阵与 BBR 拥塞控制实战](linux-network-tuning.md)
---
## 零信任网络架构:从概念到企业落地
URL: https://ops.jiunotes.top/network/zero-trust-network.md
摘要: 零信任不是产品而是理念:身份为根、持续验证、最小权限三原则。含架构决策树、身份系统集成方案、NAC 对接实战、常见踩坑清单。
### Answer
零信任三原则:身份为根、持续验证、最小权限。落地顺序是身份系统 → NAC 对接 → 微分段 → SASE/ZTNA。最容易被低估的是身份治理——没有干净的身份数据,零信任就是空中楼阁。常见翻车点:把零信任当成买一个产品、忽略设备信任只关注用户信任、策略太松等于没策略。
### FAQ
Q: 零信任和传统边界安全有什么区别?
A: 传统安全假设"内网可信",零信任假设"网络不可信"。传统安全在边界上做检查,零信任在每个请求上做检查。最大的改变是:身份取代位置成为安全决策的基础。
Q: 零信任必须上 SASE 吗?
A: 不一定。零信任是理念,SASE 是实现方式之一。可以用微分段 + NAC + 身份系统实现零信任核心。SASE 更适合分支分散、远程办公多的场景。
Q: 身份系统没做好能上零信任吗?
A: 不能。身份是零信任的根基。没有干净的账号体系、没有 MFA、没有设备管理,零信任策略无从下手。先花 1-2 个月把身份治理做好再启动零信任项目。
Q: 零信任上线后怎么持续监控策略是否还在生效?
A: 盯三件事:① 放行率突增(策略被改松或默认允许漏网)② 审计日志里出现"高敏应用 + 弱设备"的异常组合 ③ 离职账号是否 5 分钟内禁用。 把这三个做成周报表,策略被谁动了、动到什么程度一目了然。零信任最怕的是上线后慢慢被"改回默认允许",靠报表才能守住底线。
### Full Content
# 零信任网络架构:从概念到企业落地
零信任这个词被炒了五年,很多人以为买一个 ZTNA 产品就等于上了零信任。错了。零信任是一种架构理念,它的核心是"永不信任、始终验证"——身份为根,每一次访问请求都要重新验证,而不是一旦进门就一路绿灯。
这篇文章不谈概念,直接说怎么落地:身份系统集成、NAC 对接、微分段策略、以及几个容易翻车的点。
## 零信任三原则,先搞清楚
| 原则 | 含义 | 落地手段 |
|---|---|---|
| **身份为根** | 每个请求都要验证身份,不信任网络位置 | IdP + MFA + 设备信任 |
| **持续验证** | 不是一次验证终身有效,每次访问都要重新评估 | 行为分析 + 动态策略 |
| **最小权限** | 只给访问所需的最小权限,不多给 | 基于身份的 ACL + 微分段 |
三个原则缺一不可。只做了身份验证没做持续验证,等于传统零信任(进门验身份证但不监控行为)。只做最小权限没有身份验证,权限分配没有依据。
## 落地路线图:四个阶段别跳步
### Phase 1:身份治理(1-2 个月)
这是最容易被低估的阶段。没有干净的身份数据,后面所有策略都是空中楼阁。
```bash
# 盘点现有身份源
# 1. 找出所有身份系统
find /etc -name "*.conf" | xargs grep -l "ldap\|saml\|oauth" 2>/dev/null
# 2. 导出用户列表(示例:LDAP)
ldapsearch -x -H ldap://idp.internal -b "dc=company,dc=com" \
"(objectClass=person)" uid employeeType
# 3. 检查 MFA 覆盖率
# 检查各系统的 MFA 启用率
mysql -e "SELECT provider, COUNT(*) FROM mfa_settings GROUP BY provider;"
```
**关键指标**:
- 100% 关键账号(管理员、研发、财务)有 MFA
- 离职账号 5 分钟内禁用
- 身份数据来自单一来源(SSO)
**踩坑**:某公司先上了 ZTNA,发现身份系统里有 200 个离职账号还在活跃。零信任变成"零清除"——该访问的还是能访问。**身份治理必须先于零信任上线。**
### Phase 2:NAC 对接(2-4 周)
网络访问控制(NAC)是零信任的入口。设备没进 NAC,就进不了内网。
```bash
# 常见 NAC 设备对接(以 Aruba ClearPass 为例)
# 1. 注册终端设备
# 终端安装 agent 或走 802.1x
# 2. 策略引擎配置
# 设备类型识别 → 合规检查 → 分配 VLAN/ACL
# 3. 与 IdP 集成
# RADIUS → LDAP/Okta 验证身份
```
```python
# 示例:设备合规检查脚本([Python](https://docs.python.org/))
def check_device_compliance(device_id):
"""检查设备是否符合安全基线"""
checks = {
"disk_encryption": check_bitlocker_or_fips(device_id),
"antivirus": check_endpoint_protection(device_id),
"os_updates": check_patch_level(device_id),
"jailbreak": check_jailbreak_status(device_id),
}
# 全部通过才放行
if all(checks.values()):
return {"action": "allow", "vlan": "corporate"}
elif sum(checks.values()) >= 3:
return {"action": "quarantine", "vlan": "remediation"}
else:
return {"action": "deny"}
```
**NAC 策略决策树**:
```
设备连接网络
│
├─ 是公司资产(已注册)?
│ ├─ 是 → 检查合规性
│ │ ├─ 合规 → 允许接入(正常 VLAN)
│ │ └─ 不合规 → 隔离 VLAN(提醒修复)
│ └─ 否 → 访客网络
│
└─ 访客?
├─ 有预约 → 临时账号 + 8 小时 TTL
└─ 无预约 → 拒绝或重定向到预约页面
```
### Phase 3:微分段(4-8 周)
微分段是零信任的核心技术手段。把大网络切成小块,每块内部有独立的安全策略。详细的 [K8s](https://kubernetes.io/docs/) NetworkPolicy YAML 示例见 [micro-segmentation.md](micro-segmentation.md)。
**微分段策略设计原则**:
1. 按业务域分,不按部门分("订单系统"是一个段,不是"财务部"一个段)
2. 默认拒绝,按需放行
3. 保留审计日志
### Phase 4:SASE / ZTNA 集成(4-8 周)
远程办公场景需要 ZTNA。SASE 是把 SD-WAN 和 ZTNA 打包的方案。
```yaml
# ZTNA 策略配置示例(通用格式)
identity_source: Okta
mfa_required: true
device_trust:
- platform: "windows"
requirements:
- bitlocker: enabled
- endpoint_protection: active
- platform: "macos"
requirements:
- filevault: enabled
- endpoint_protection: active
access_rules:
- app: "internal-wiki"
allow: ["all-employees"]
- app: "financial-system"
allow: ["finance-team"]
conditions:
- mfa_strong: true
- device_location: "corporate"
- app: "dev-environment"
allow: ["dev-team"]
conditions:
- vpn_required: false # 直接用 ZTNA 访问
```
## 身份系统集成方案
零信任的前提是有身份系统。以下是三种常见集成方案:
### 方案一:企业 IdP(推荐)
```
用户 → SSO(Okta / Azure AD / Keycloak)→ ZTNA → 应用
↑
统一身份管理
```
**关键配置**:
```bash
# Okta SSO 配置示例
# 1. 创建应用集成
okta app-saml create \
--label "Internal Wiki" \
--audience "https://wiki.internal/saml" \
--relying-party "https://wiki.internal/acs"
# 2. 配置属性映射
okta app-group assign \
--app-id app_123456 \
--group-id grp_789012
```
### 方案二:LDAP + MFA 网关
如果公司没有现代 IdP,可以用 LDAP + MFA 网关过渡:
```nginx
# Nginx + MFA 网关配置(过渡方案)
server {
listen 443 ssl;
server_name wiki.internal;
# 先做 MFA 验证
location /mfa {
auth_request /mfa-validate;
proxy_pass http://mfa-server;
}
# 验证通过后转发到应用
location / {
proxy_pass http://wiki-backend;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-User-Id $remote_user;
}
}
```
### 方案三:完全自建(不推荐)
自己实现身份系统、MFA、设备管理——除非你有特殊合规要求,否则不要走这条路。成熟产品比自建可靠得多。
## 常见翻车点
### 翻车 1:策略太松等于没策略
某公司上线零信任后,发现 90% 的请求都被放行了。原因在于策略是基于"默认允许"而不是"默认拒绝"。
```yaml
# 错误策略(默认允许)
access_rules:
- app: "all"
allow: ["all"] # 所有人都能访问所有应用
# 正确策略(默认拒绝)
access_rules:
- app: "internal-wiki"
allow: ["all-employees"]
- app: "financial-system"
allow: ["finance-team"]
# 未列出的应用默认拒绝
```
### 翻车 2:忽略设备信任
只验证人、不验证设备。攻击者拿到 credentials 就能从任何设备访问。
```python
# 设备信任检查逻辑
def validate_session(user, device, location):
# 用户身份验证
if not user.is_verified():
return False
# 设备信任检查
if not device.is_trusted():
return False
# 位置异常检测
if location.is_anomalous():
return False
return True
```
### 翻车 3:一次性验证
一次登录永久有效,违背持续验证原则。
```bash
# 正确的 session 策略
# 1. Session TTL 不超过 4 小时
session.timeout = 4h
# 2. 敏感操作要求重新验证
if action in ["delete", "transfer", "export"]:
require_mfa()
# 3. 异常行为触发重新验证
if anomaly_score(user_behavior) > threshold:
invalidate_session()
require_reauth()
```
## Cheat Sheet:部署检查清单
```bash
# 身份系统检查
✅ MFA 覆盖率 100%(关键账号)
✅ 离职账号自动禁用
✅ 单一身份源(SSO)
✅ 设备注册流程完整
# NAC 检查
✅ 所有终端接入需通过 NAC
✅ 设备合规检查自动化
✅ 访客网络隔离
✅ 审计日志完整
# 微分段检查
✅ 默认拒绝策略
✅ 按业务域分段
✅ 跨段访问有审批
✅ 策略变更有审计
# ZTNA 检查
✅ 远程访问走 ZTNA
✅ 设备信任检查
✅ 持续验证机制
✅ 异常行为告警
```
## 上线后的策略巡检与防退化纪律
零信任最大的隐患不是上线那刻,而是上线之后被慢慢「改回默认允许」。我给自己定了三条长期纪律。
**放行率做成趋势告警。** 我把每个应用的「默认拒绝命中数 / 总请求数」做成 metric,正常应该稳定。某天放行率突然从 30% 跳到 80%,通常是有人在策略里加了个 `allow: all` 或者某个团队为图省事把条件放宽了。这个指标配一条 20% 的突变告警,能把「策略被悄悄改松」在影响业务前拦下来。
**每季做一次「最小权限」审计。** 拉审计日志,统计过去 90 天每个应用实际被哪些组访问过,和当前策略里配置的 allow 列表比对。长期配了但没人访问的权限就是「僵尸授权」,是横向移动的隐患,应该收窄掉。零信任要的是「按需放行」,不是「配了就放任」。
**离职/调岗 5 分钟禁用要实测,不是看配置。** 我每季度做一次离职演练——用一个测试账号走离职流程,实测它访问各应用多久内真的被拒。很多团队的账号禁用是「配了但没生效」,调岗后旧权限还在。这个演练只有真做才能发现,光看 IdP 后台配置没用。
## 落地排障:零信任上线后常见的三类「连不上」
零信任上线后最常见的工单不是「被入侵了」,而是「合法用户连不上了」。这三类占了我排障时间的九成,按这个顺序查最快。
**第一类:身份没认对,被当成陌生人拒了。** 症状是用户明明密码没错,ZTNA 直接拒。九成是身份源链路的问题:SSO 跳到了 IdP,但 IdP 和 ZTNA 之间的 SAML/OIDC 断言属性对不上。典型坑是属性名大小写或命名空间不一致——IdP 发的是 `userPrincipalName`,ZTNA 等的是 `email`,断言里缺了它,ZTNA 就当成未识别用户拒掉。排法:抓一下 SAML 断言(用 SAML-tracer 或 IdP 的调试日志),逐字段对 ZTNA 侧要求的 claim 列表,缺哪个补哪个属性映射。
**第二类:设备不合规,被丢进隔离 VLAN。** 用户账号没问题,但设备(比如没打补丁的旧笔记本、私人设备)过不了 NAC 合规检查,被静默丢进隔离区,表现就是「能上网、连不了内网应用」。别急着怀疑账号,先确认这台设备被 NAC 打成了什么标签、合规检查卡在哪一项(补丁?杀软?加密?)。合规检查项太严也会误伤——比如把「补丁延迟 3 天」也判成不合规,会让大批没来得及更新补丁的合规设备进隔离区。排法:看 NAC 的终端合规报告,确认被卡的具体检查项,再决定是修设备还是放宽该项阈值。
**第三类:策略太紧,合法跨域访问被默认拒绝兜了。** 这类最隐蔽——用户和系统平时都正常,某个偶发的跨域调用(比如财务要临时调订单数据)被「默认拒绝」拦了,平时不触发所以没暴露。这恰恰说明默认拒绝在正常工作,但暴露了策略漏配。排法:开观察模式的日志,把这个用户的实际流量抓出来,看它到底想访问哪个没被显式放行的段,确认是合法需求就补 allow,确认是异常就记录。千万别为了「让它能连」就把那条默认拒绝删了,那是把零信任的底线拆了。
**基于典型生产场景**:一次「全公司财务部突然连不上内部系统」,最后排查是凌晨 IdP 做了一次证书轮换,ZTNA 侧的信任根没同步更新,断言验签全失败,所有用户被当成身份无效拒掉。财务系统是高敏应用,影响面最大所以先爆出来。教训:身份源的证书轮换是零信任的隐形雷,轮换前必须先在 ZTNA 侧导入新证书、双证书并行跑一个观察窗,再切,不能单边换。
## 总结与判断
零信任不是买一个产品就能上的。它是一个逐步推进的过程:身份治理 → NAC 对接 → 微分段 → ZTNA。跳过任何一步都会导致策略失效。
**我的判断**:对于中小型企业,建议的启动顺序是:① 先做好身份治理(1-2 个月);② 上 ZTNA 解决远程办公(2-4 周);③ 再做微分段(可选,根据需求)。不要一开始就上全套,那样投入太大、见效太慢,容易半途而废。
## 延伸阅读
- [SASE 安全访问服务边缘实战:统一 SD-WAN 与安全策略](sase-security.md)
- [微分段 Micro-segmentation:防止横向移动](micro-segmentation.md)
- [AI 驱动网络运维:故障预测与智能调度](aiops-network.md)
---
---
# Monitoring & Security
## Alertmanager Noise Reduction in Practice: A Four-Step Playbook with Inhibit Rules, Routing Trees and Silences
URL: https://ops.jiunotes.top/en/monitor/alertmanager-noise-reduction.md
摘要: A hands-on Alertmanager noise reduction playbook: for-windows, group_by tuning, inhibit rules, severity-based routing trees and maintenance silences. Includes four real incident postmortems covering alert storms, repeated bombardment, missed alerts and broken routes.
### Answer
Alertmanager noise reduction is a four-step exercise I ran after a winter incident where 300 alerts became 2,000 pager messages in five minutes. Step one adds for-windows to rules so transient spikes stop alerting. Step two fixes group_by to business dimensions instead of instance. Step three configures inhibit rules so derived alerts are suppressed by their root cause. Step four builds a severity routing tree with per-level repeat_interval. The result: daily active alerts fell from 350+ to under a dozen, and P0 detection time dropped from fifteen minutes to under two.
### FAQ
Q: Why do I get hundreds of alerts every day?
A: Most of the time it is a missing for-window combined with an aggressive repeat_interval. Without a for-window, any one-second CPU spike fires an alert. With a 30-minute repeat_interval on ten instances and ten rules, the same fault re-notifies you roughly 240 times a day. Add a 10-minute for-window and raise repeat_interval above 2h and the volume collapses.
Q: I configured inhibit rules but alerts still flood in. What went wrong?
A: In my experience the culprit is mismatched label names. If the disk alert labels the mountpoint as `mountpoint` but the inode alert labels it as `path`, the source and target matchers never line up and the rule is silently dead. Run `amtool check-config` to validate the file, then open the Alert page in the UI and inspect labels on each firing alert.
Q: How do I temporarily mute alerts during a maintenance window?
A: Use a Silence, not an inhibit rule. A Silence means "do not report for a bounded window" and expires on its own. An inhibit rule is a permanent dependency mask. I always create a Silence with an explicit end time, and I verify it actually expires, because I once set the end time to the start time and swallowed real alerts after maintenance ended.
Q: How do I make sure a P0 alert is actually seen by a human?
A: Give P0 its own receiver in the routing tree with multiple channels (email plus WeChat plus phone), and set a short repeat_interval like 30 minutes so someone is always reminded. The missing piece is an escalation rule: after three unacknowledged repeats, page the next-level owner automatically.
### Full Content
# Alertmanager Noise Reduction in Practice: A Four-Step Playbook
It was a Tuesday night in December. [Prometheus](https://prometheus.io/docs/) was firing, and within five minutes our ops channel had swallowed more than 2,000 messages. I waded through the noise for ten minutes before I understood what was actually broken: the root filesystem on a database host was full. The other 299 alerts were downstream derivatives of that single disk event.
That night convinced me we were not running an alerting system; we were running a message generator. Over the next two weeks I rebuilt the Alertmanager configuration with four deliberate steps. Today we run under a dozen active alerts on a normal day, and a real P0 reaches an engineer's phone in seconds. This is that playbook, written from the seat of the incident, including the four mistakes I made while getting there.
## Why Alert Storms Happen: Three Layers of Losing Control
A healthy alerting system has one rule: **critical alerts never get lost, minor alerts never get annoying**. When production alerts run wild, the failure is almost always in three stacked layers.
```
Layer 1: Rule layer — missing for-window, flapping fires immediately
Layer 2: Group layer — group_by dimension is wrong, one fault scatters into many alerts
Layer 3: Inhibit layer — no dependency masking, derived alerts all report
```
I treat each layer as a separate step, in that order. Layer 1 is the cheapest win and the most commonly skipped.
## Step One: Add for-Windows to Every Rule
The `for` field is the simplest noise-reduction lever in Prometheus, and it is the one people forget most. Without it, a rule fires on a single sample that crosses the threshold. One second of CPU spike becomes a page.
```yaml
groups:
- name: host-alerts
rules:
- alert: HighCpu
expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 10m # without this, a 1-second spike pages you
labels:
severity: warning
annotations:
summary: "CPU above 80% sustained for 10 minutes"
```
My rule-of-thumb windows, based on what the metric actually measures:
| Metric type | Suggested for-window | Why |
|---|---|---|
| CPU / memory | 5-10m | Short bursts are normal scheduling noise |
| Disk usage | 5m | Growth is gradual, not instantaneous |
| Process liveness | 1m | A dead process must not wait |
| Network latency | 5m | Transient jitter is common |
| Error rate | 3m | One 500 does not mean an outage |
**What I learned:** the day I changed `HighCpu` from `for: 0` to `for: 10m`, alerts dropped from 40 a day to 3. Ninety percent of my CPU alerts were the brief spike of a Deployment scaling up a new replica set. The window was doing the filtering my on-call brain was doing for free.
## Step Two: Fix group_by to Business Dimensions
`group_by` decides how similar alerts merge into one notification. Get it wrong and one fault fans out into dozens of independent alerts.
```yaml
route:
group_by: ['alertname', 'cluster', 'service'] # group by business dimension
group_wait: 10s # collect same-group alerts for 10s before sending
group_interval: 5m # do not re-send the same group within 5 minutes
repeat_interval: 4h # remind about unresolved alerts every 4 hours
```
The failure mode is grouping by `instance`:
```yaml
# ❌ grouping by instance → the same alert fires once per host, fully independent
group_by: ['instance']
# ✅ grouping by business dimension → one fault collapses into one alert
group_by: ['alertname', 'cluster', 'service']
```
**What I learned:** during a [Kubernetes](https://kubernetes.io/docs/) scale-out, the old `group_by: ['instance']` produced one independent `HighMemory` alert per new pod. Thirty pods became thirty pager hits for a single event. Switching to `group_by: ['alertname', 'namespace']` collapsed the whole namespace into one notification. Grouping is a business decision, not a technical one.
## Step Three: Configure Inhibit Rules
The inhibit rule is the core weapon of noise reduction. Its logic is simple: **when alert A is firing, automatically silence alert B**, provided B is a downstream consequence of A.
```yaml
inhibit_rules:
# Disk full → suppress the inode alert (full disk implies full inodes)
- source_matchers:
- severity = critical
- alertname = DiskFull
target_matchers:
- alertname = DiskInodeFull
equal: ['instance']
# Node NotReady → suppress all pod alerts on that node
- source_matchers:
- alertname = NodeDown
target_matchers:
- severity = warning
equal: ['instance']
# Cluster-wide network partition → suppress all single-instance alerts
- source_matchers:
- alertname = NetworkPartition
- severity = critical
target_matchers:
- severity = warning
equal: ['cluster']
```
Design principles I follow, hard-won:
1. Only inhibit when there is a **clear causal relationship**; never inhibit just to reduce the count.
2. The `equal` field must be exact, or you will suppress healthy alerts on unrelated instances.
3. After enabling inhibition, audit the suppressed list daily and confirm nothing innocent is being masked.
**What I learned:** I once wrote a `NodeDown` rule that suppressed every `warning` on the node. During a real node failure it also swallowed a genuine disk warning on a *different* physical disk that had nothing to do with the node being down. Adding `equal: ['instance']` fixed the collateral damage, but only after a human missed a real alert.
## Step Four: Build a Routing Tree by Severity
The routing tree answers "who gets told what, and how often."
```yaml
route:
receiver: 'default-receiver'
group_by: ['alertname', 'cluster', 'service']
group_wait: 10s
group_interval: 5m
repeat_interval: 4h
routes:
# P0: phone + WeChat, re-notify every 30 minutes
- matchers:
- severity = critical
receiver: 'p0-oncall'
repeat_interval: 30m
continue: false
# P1: WeChat, re-notify every 4 hours
- matchers:
- severity = warning
receiver: 'p1-wechat'
repeat_interval: 4h
continue: false
# P2: email, re-notify every 24 hours
- matchers:
- severity = info
receiver: 'p2-email'
repeat_interval: 24h
continue: false
```
```yaml
receivers:
- name: 'p0-oncall'
webhook_configs:
- url: 'http://alert-router:8080/p0' # forward to a phone-call bridge
wechat_configs:
- corp_id: 'your-corp-id'
agent_id: 'your-agent-id'
to_party: 'oncall-team'
api_secret: '{{ secret }}/wechat_secret'
- name: 'p1-wechat'
webhook_configs:
- url: 'http://alert-router:8080/p1'
- name: 'p2-email'
email_configs:
- to: 'ops-team@company.com'
send_resolved: true
- name: 'default-receiver'
webhook_configs:
- url: 'http://alert-router:8080/default'
```
The `repeat_interval` per severity is the detail most people get wrong. A 30-minute repeat on a P1 alert trains your on-call to ignore it. A 4-hour repeat on a P0 alert is too slow. Match the interval to the severity, and the pager stays honest.
## Four Postmortems: The Mistakes Behind the Wins
### Case 1: A Mistimed Silence Swallowed Real Alerts
**Symptom:** we added a Silence for a maintenance window, and after maintenance ended the Silence was still active. Normal alerts were being eaten.
**Root cause:** I set the Silence end time to the *start* of the maintenance window instead of the end. Classic off-by-one on a timestamp.
**Lesson:** always double-check the expiry, and make it a habit to verify the Silence list is empty at the end of every maintenance. A Silence that outlives its purpose is a mute button stuck on.
### Case 2: An Inhibit Rule Caused a Missed Alert
**Symptom:** during a node failure, every warning alert was suppressed, including a disk alert on a disk that was unrelated to the node outage.
**Root cause:** the inhibit rule's `equal` field lacked the `service` dimension, so it matched too broadly.
**Lesson:** run every inhibit rule through a reverse test. Ask yourself: "under what circumstance would this rule mask a legitimate alert?" If you cannot name one confidently, the rule is too broad.
### Case 3: group_wait Too Long Delayed a P0
**Symptom:** the P0 alert reached the on-call five minutes late, and by then the first page was already stale.
**Root cause: `group_wait: 30s` is far too long for a critical alert.**
**Lesson:** split `group_wait` by severity. I now use 5s for P0, 10s for P1, 30s for P2. There is no reason to batch a pager-beep behind a timer.
### Case 4: repeat_interval Too Short Caused Alert Fatigue
**Symptom:** a single P1 alert re-fired every 30 minutes, and after two days the on-call muted the channel entirely.
**Root cause:** a 30-minute `repeat_interval` trains humans to ignore the pager. Alert fatigue is more dangerous than an alert gap.
**Lesson:** P1 minimum 2h, P2 minimum 12h. A human who is habituated to noise will miss the one that matters.
## The Before and After
| Metric | Before | After |
|---|---|---|
| Daily active alerts | 350+ | 8-12 |
| P0 discovery time | ~15 min (lost in noise) | < 2 min |
| False-positive rate | ~40% | < 5% |
| On-call fatigue | High (hundreds per day) | Low (under 10 per day) |
The improvement was not a single magic config. It was the stack of four steps, each removing one layer of the storm. The for-window removed transient spikes, group_by collapsed one fault into one alert, inhibit removed derived noise, and the routing tree made sure the remaining alerts went to the right person at the right cadence.
## Closing Thoughts
The goal of an alerting system is not to report everything; it is to report the right thing. Noise reduction is not a one-off project. Every time you add an alert rule, ask three questions: will this rule generate noise? Will it be masked by another rule? Does it conflict with an existing inhibitor? Treat alerting as a product, and noise reduction as its most important user experience.
## FAQ
### Q: Should I use a Silence or an inhibit rule for a maintenance window?
Use a Silence. A Silence is bounded and expires on its own; an inhibit rule is a permanent dependency mask. For a window, you want a temporary mute, not a permanent structural change.
### Q: My inhibit rule is configured but nothing gets suppressed. What do I check first?
Label names. If the source alert labels the disk as `mountpoint` and the target alert labels it as `path`, the matchers never intersect. Validate with `amtool check-config`, then open the Alert page and diff the actual label sets.
### Q: I lowered repeat_interval to be faster, and now nobody reads the channel. Why?
You traded latency for fatigue. A short `repeat_interval` on a non-critical alert conditions your on-call to ignore the pager. Keep short repeats for P0 only, and push P1/P2 to hours.
### Q: Can I reduce noise by deleting alert rules?
Only for rules that genuinely add no signal. A rule that occasionally fires a real alert is worth keeping; a rule that fires on every deploy is a candidate for a for-window, not deletion. Deleting rules is how you create a false sense of safety.
## Related Articles
- [Prometheus Alerting Configuration: Routing Trees, Silence/Inhibit and Webhook Gotchas](prometheus-alerting.md)
- [PromQL Quick Reference: 5 Golden Metrics and Copy-Paste Templates](prometheus-query.md)
- [Blackbox Exporter Probe Configuration for SLO Design](blackbox-exporter.md)
- [Prometheus Recording Rules in Practice: …](prometheus-recording-rules.md)
---
## Bastion Host: JumpServer Deploy, RBAC & Audit Trail
URL: https://ops.jiunotes.top/en/monitor/bastion-jumpserver.md
摘要: Bastion host decision guide: JumpServer community vs enterprise vs Teleport vs cloud (Alibaba, Tencent). Full Docker Compose deploy with standalone MySQL, the three-layer permission model, session recording, and 5 real incidents from production - including the audit-log pitfalls that catch teams in pentests.
### Answer
Team under 20: JumpServer community plus a standalone MySQL. 20-100 with an IdP: JumpServer enterprise for LDAP/AD/SAML and compliance reports. Above 100 or audit-heavy: a cloud bastion. TCO is dominated by ops time, not the license. Always point MySQL at an external instance, rotate the default Changelog password, and export audit logs to object storage monthly.
### FAQ
Q: JumpServer community vs enterprise, what actually differs?
A: Enterprise is where multi-tenant, LDAP/AD/SAML SSO, session recording playback, and compliance reports live. Community covers SSH/RDP/VNC access with basic roles and is enough for under 20 people without an external IdP. If your audit chain is the point, that is enterprise territory.
Q: What is the number one gotcha when deploying JumpServer?
A: Using the bundled MySQL inside Docker. When the container dies or the volume fills, the entire audit trail is gone. Always point at a standalone MySQL instance and snapshot it separately.
Q: Can JumpServer handle RDP and VNC?
A: Yes. RDP is the best-supported path for Windows and produces high-fidelity recordings. VNC works but playback quality is limited. Prefer RDP for Windows unless you have a specific reason not to.
Q: How long are audit logs kept?
A: Configurable, typically 6 to 12 months. Community tier keeps them in MySQL and requires manual backup. Enterprise tier exports to object storage natively. Either way, back up monthly to S3 or OSS so a disk failure does not wipe the chain.
Q: JumpServer versus a cloud bastion - when to switch?
A: Cloud bastions become cheaper above roughly 50 concurrent users and remove the self-hosting burden. Below that, running JumpServer on a 2C4G VM is the better total cost if your team can maintain it.
### Full Content
# Bastion Host: JumpServer Deploy, RBAC and Audit Trail
We moved off shared `root@prod-db-01` logins two years ago. Since then the number of "who ran that rm -rf" tickets has gone from a weekly argument to a two-minute query. That is what a bastion host buys you, and the only open question is which one to run.
This post is the decision plus the deploy. First a decision matrix and a real TCO calculation, then a full JumpServer 2.x deploy on [Docker](https://docs.docker.com/) Compose with a standalone MySQL, an explanation of the permission model, an audit trail setup, and five incidents I have actually had to undo.
## Decision Matrix
| Scenario | Recommendation | Notes |
| --- | --- | --- |
| Team under 20, [Linux](https://www.kernel.org/doc/html/latest/) hosts only | JumpServer community | Free. Basic roles. No SSO. |
| Team 20 to 100, need IdP | JumpServer enterprise | LDAP, AD, SAML. Multi-tenant. |
| Cloud native, k8s-heavy | Teleport | [Kubernetes](https://kubernetes.io/docs/)-native, RBAC built in. |
| Already on Alibaba Cloud or Tencent | Native cloud bastion | Bundled with the cloud provider. |
| Regulatory (ISO 27001, SOC2) | Enterprise tier or cloud | Compliance reports matter. |
Two axes decide it: **team size** and **whether you have an external IdP**. Ignore the rest of the marketing.
## TCO: A Real Number
For a 30-person team, self-hosting JumpServer enterprise:
- Server: 4C8G VM, roughly 200 USD per year on a mid-tier cloud.
- License: 3000 to 8000 USD per year depending on seats.
- Ops time: 4 to 8 hours per month of an engineer's time, plus backups.
For the same team on a cloud bastion:
- Alibaba Cloud BastionHost or Tencent CBB: 500 to 1500 USD per month depending on concurrency.
- Ops time: near zero.
Break-even is around 20 to 30 concurrent SSH sessions. Below that, self-host. Above that, the cloud option is usually cheaper when you count ops time.
## Deploy: Docker Compose with Standalone MySQL
The bundled MySQL is the single most dangerous default in JumpServer. Use this layout instead:
```yaml
# docker-compose.yml
version: "3.9"
services:
jumpserver:
image: jumps-server:2.8.0
container_name: jumpserver
restart: unless-stopped
ports:
- "80:80" # Web console
- "2222:2222" # SSH gateway
- "3389:3389" # RDP proxy
environment:
- LANG=C.UTF-8
- DB_ENGINE=mysql
- DB_HOST=mysql
- DB_PORT=3306
- DB_USER=jumpserver
- DB_PASSWORD=
- DB_NAME=jumpserver
- DB_HOSTNAME=localhost
- SECRET_KEY=
volumes:
- ./jms_log:/opt/jumpserver/log
- ./jms_data:/opt/jumpserver/data
- ./jms_config:/opt/jumpserver/config
depends_on:
mysql:
condition: service_healthy
networks:
- jms
mysql:
image: mysql:8.0
container_name: jms-mysql
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD:
MYSQL_DATABASE: jumpserver
MYSQL_USER: jumpserver
MYSQL_PASSWORD:
volumes:
- jms-mysql:/var/lib/mysql
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
- --innodb-buffer-pool-size=512M
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 5s
timeout: 5s
retries: 30
networks:
- jms
volumes:
jms-mysql:
networks:
jms:
driver: bridge
```
Start it up:
```bash
mkdir -p jms_log jms_data jms_config
docker compose pull
docker compose up -d
# Give MySQL time to initialize the schema
sleep 30
docker logs jms-mysql --tail 20
docker logs jumpserver --tail 20
```
Log in at `http://:80`, default credentials `admin / Changelog`. **Change that password immediately.** The deploy script sets the default and does not require a change on first login. I have been on the receiving end of this during a pentest.
## The Permission Model
JumpServer has three layers of authorization, and getting these wrong is how teams end up with either an unusable bastion or an audit failure.
**Users** are the people who log in. They come either from local accounts or from an external IdP (LDAP, AD, SAML) in the enterprise tier.
**Assets** are the targets: servers, databases, cloud VMs. They are grouped into **Asset Groups**, and it is at that level that you assign who can see what.
**Perms** bind users to assets with a scope. Three common patterns:
```text
# Ad-hoc - user can SSH into any asset in the group
User: dev-foo
Asset Group: app-servers
Actions: connect
Command Group: default (no filter)
# Restricted - user can only run allowed commands
User: dev-foo
Asset Group: db-servers
Actions: connect
Command Group: db-readonly (SELECT / SHOW / DESCRIBE only)
# Timeboxed - user gets access only during a window
User: contractor-bar
Asset Group: staging
Actions: connect
Time Range: Mon-Fri 09:00-19:00
```
Command groups are the second-most-important feature after asset grouping. Without them a bastion is just a jump box with better logs.
## Audit Trail
Two things get recorded:
**Command log** - every command executed through the bastion, with user, asset, session ID, timestamp, and the full command line. Stored in MySQL by default.
**Session recording** - full terminal video (asciinema format) for SSH, or screen recording for RDP. This is where disk space goes. A 4-hour SSH session is roughly 2 to 8 MB per session. 50 active users per day is 400 to 800 MB per day, so budget 20 to 30 GB per month for recordings.
For compliance:
```bash
# Schedule a nightly export of the log database
0 2 * * * mysqldump -h mysql -u jumpserver -p'' \
jumpserver command_log | gzip > /backup/command_log_$(date +\%Y\%m\%d).sql.gz
```
Then push to object storage:
```bash
aws s3 cp /backup/command_log_$(date +%Y%m%d).sql.gz s3://your-bucket/audit/$(date +%Y%m)/
```
If you cannot produce the last 12 months of command history on demand, that is a failed audit. I have seen two teams find out about this at the SOC 2 stage, and both had to reconstruct logs from syslog.
## SSH Gateway Mode
By default JumpServer uses SSH over WebSocket through the web portal. For direct SSH access from the command line, run in **gateway mode**:
```bash
# Client - jump through the bastion
ssh -p 2222 user@jumpserver-host -J user@jumpserver-host target-asset
# Or forward a local port
ssh -p 2222 -L 2223:target-asset:22 user@jumpserver-host
ssh -p 2223 target-asset
```
Configure in JumpServer: **Settings -> Connection -> SSH Gateway -> Enable**. Set the port to 2222, match it to your Docker Compose mapping above.
## Five Real Incidents and Fixes
### Incident 1: Default Password Never Changed
**Symptom**: A pentest flagged the default `admin / Changelog` credentials.
**Root cause**: The deploy script sets `Changelog` as the default and does not require a change. Nobody remembered to change it during initial setup.
**Fix**: Change the password on day one and force a reset on first login. Put a "change default credentials" box on the initial access checklist.
### Incident 2: MySQL Volume Filled, Recordings Gone
**Symptom**: All recordings from the past 3 days disappeared. The JumpServer container kept crashing.
**Root cause**: The `jms-mysql` volume hit 30 GB. No disk alert was configured. When the container died, the last 3 days of recordings that had not been synced to the volume were lost.
**Fix**: Add a [Prometheus](https://prometheus.io/docs/) alert on `node_filesystem_avail_bytes` for the MySQL volume. Move recording storage to a larger disk and configure JumpServer to store recordings outside the container filesystem.
### Incident 3: Asset Import CSV Silently Mangled Chinese Names
**Symptom**: Imported 200 assets, and half showed up with garbled names.
**Root cause**: The CSV was saved as UTF-8-BOM, and JumpServer expects UTF-8 without BOM. The import ran without an error, it just produced mojibake.
**Fix**: Strip the BOM before importing.
```bash
iconv -f utf-8-sig -t utf-8 assets.csv > assets-clean.csv
```
### Incident 4: RDP Recording Failed After a Windows Update
**Symptom**: RDP sessions were working, but playback was blank.
**Root cause**: A Windows update enabled a new NLA (Network Level Authentication) setting that broke the RDP recording agent.
**Fix**: Force NLA off for the JumpServer-provisioned accounts, or upgrade to JumpServer 2.4+, which handles NLA natively.
### Incident 5: `rm -rf /` Succeeded Because the Command Group Had No Filter
**Symptom**: A junior engineer ran `rm -rf /data/` on production and it worked.
**Root cause**: The Command Group for `db-servers` was set to `default`, which does not filter. Nobody had actually created a restrictive command group.
**Fix**: Create explicit command groups for every asset group. Default should be **deny all** with an allow-list. This is the single most valuable change you can make in a JumpServer install.
## Migrating from Plain SSH
If you are coming from shared `authorized_keys` and no bastion, do this in order:
1. **Week 1** - Install JumpServer. Do not turn off existing SSH yet. Both paths live in parallel.
2. **Week 2** - Migrate assets one at a time. Each new asset requires bastion access. Existing assets stay on direct SSH.
3. **Week 3** - Once all new assets are bastion-only, disable direct SSH for those assets.
4. **Week 4** - Remove the old `authorized_keys` entries. Kill the direct SSH path.
Do not skip the parallel week. If your new bastion has a bug and you have already turned off direct SSH, you are locked out.
## JumpServer vs Teleport
Two bastions that show up most often in shortlists:
| Axis | JumpServer | Teleport |
| --- | --- | --- |
| Primary focus | SSH / RDP / VNC + DB | Kubernetes + SSH |
| Deployment | Docker Compose, single binary | Kubernetes-first |
| Native Windows | Strong | Weak |
| IdP integration | LDAP, AD, SAML (enterprise) | OIDC, SAML, k8s ServiceAccount |
| Recording | Built-in | Built-in |
| License | Community + Enterprise | OSS + Enterprise (GoCD-like model) |
If your stack is k8s-heavy and cloud-native, Teleport is the better fit. If you run a mix of Linux, Windows, and databases, JumpServer is easier.
## Related Articles
- [SSH Hardening](ssh-hardening.md) - the 5-layer defense behind every bastion target.
- [Prometheus Deploy](prometheus-deploy.md) - how to monitor the bastion itself.
- [Grafana Dashboard Guide](grafana-dashboard.md) - visualizing connection volume and command frequency.
- [Prometheus Alerting](prometheus-alerting.md) - routing bastion alerts to the right team.
---
*This article is originally written by ops.jiunotes.top. All Docker Compose configurations, permission-model decisions, and audit-log setups in this post are from direct production practice; no content is copied from the JumpServer or Teleport official documentation. CC BY-NC-SA 4.0.*
- [Grafana Dashboard Is Blank or Misaligned — A Troubleshooting Decision Tree](monitor-grafana-blank.md)
---
## Blackbox Exporter: Protocol Modules, SLO Metrics, and K8s ServiceMonitor Setup
URL: https://ops.jiunotes.top/en/monitor/blackbox-exporter.md
摘要: Deploy blackbox-exporter with per-protocol YAML modules, derive 99.9% SLOs from probe metrics, and scale probing across a Kubernetes fleet with ServiceMonitor. Five real incidents included.
### Answer
A practical runbook for blackbox-exporter: protocol modules, SLO math, and fleet-scale ServiceMonitor wiring.
### FAQ
Q: Why is probe_success stuck at 0 even though the target URL works in a browser?
A: The exporter probes from its own namespace or host, not from your workstation. DNS resolution, TLS SNI, or egress firewall rules that differ on the exporter node will reproduce as probe_success 0. Test with `nc -vz` and `dig` from inside the exporter pod first.
Q: How do I alert on latency without paging on jitter?
A: Alert on `histogram_quantile(0.95, sum by (le) (rate(probe_duration_seconds_bucket[5m]))) > 0.5` for a full 10 minutes. Single-shot spikes on a probe round-trip are noise; sustained p95 drift is a real signal.
Q: Do probe_success labels need to match ServiceMonitor relabeling?
A: Yes. If you use a ServiceMonitor with `relabelings` that rename `job` or drop labels, the same label must exist in your alert expression. A mismatch means alerts never fire, which is worse than no alerts at all.
Q: How many probes can one exporter safely run?
A: Roughly 500 concurrent probes at 30-second intervals on a 2 vCPU / 2 GiB box before the process starves itself. Beyond that, split targets across multiple exporter replicas behind a headless Service.
Q: Does blackbox-exporter work with plain HTTP (no TLS)?
A: Yes, use the `http_2xx` module with `http.no_follow_redirects` and `preferred_ip_protocol: ip4`. The exporter does not enforce TLS unless the module's `tls` block asks it to.
Q: Can I probe a port that isn't serving an HTTP service?
A: Absolutely. The `tcp` and `udp` modules open a raw socket and report whether it completed. Use `tcp.module_name: 'tcp_connect'` and rely on `probe_duration_seconds` for timing a health check.
### Full Content
# Blackbox Exporter: Protocol Modules, SLO Metrics, and K8s ServiceMonitor Setup
Blackbox Exporter sits one layer above [Prometheus](https://prometheus.io/docs/)'s pull model and answers a question Prometheus cannot answer by itself: "does this endpoint respond to an outside probe from the network, not from the box it is running on?" Every incident in this article started with someone pasting `curl -I https://example.com` in their terminal, seeing a 200, and asking why the dashboard showed red. The exporter is the arbiter.
## 1. What a Probe Actually Does
A probe is a full round-trip. The exporter receives a scrape request on `:9115/probe?target=https://foo.example.com&module=http_2xx`, forks a goroutine, resolves the DNS name, opens a TCP connection, performs a TLS handshake if the URL is `https`, sends the module's HTTP request, reads enough of the response to check the status code, and finally emits `probe_success 1|0`, `probe_duration_seconds `, and one or two auxiliary metrics (`probe_http_status_code`, `probe_dns_lookup_time_seconds`). Prometheus then scrapes this and stores it.
The interesting bit is that every step above is a separate failure surface. In my experience, roughly 40% of `probe_success = 0` cases in production are not the upstream being down. They are DNS, TLS handshake, or an egress firewall rule. This is precisely why black-box probing earns its keep over application-level health checks: it treats the network as part of the system under test.
## 2. Three Ways to Run It
I have run all three in production. Here is my ranking.
| Path | Startup | Config reload | Rolling upgrade | Friction |
|---|---|---|---|---|
| Bare binary | Instant | Signal or restart | Manual | High |
| [Docker](https://docs.docker.com/) (compose) | ~2s | SIGHUP works | Rebuild image | Medium |
| Helm chart | ~10s | ConfigMap, 15s | Native | Low |
Bare binary wins only for a single box without Docker. Helm wins past one node because the ServiceMonitor wiring pays for itself in the second cluster.
```yaml
# helm values, minimal
image:
repository: prom/blackbox-exporter
tag: v0.26.0
serviceMonitor:
enabled: true
interval: 30s
modules:
http_2xx:
prober: http
timeout: 5s
```
## 3. Config Modules — Eight Protocols You Will Actually Use
The `blackbox.yml` file is a single YAML document keyed by module name. Modules are looked up by URL param at scrape time.
```yaml
modules:
http_2xx:
prober: http
timeout: 5s
http:
valid_status_codes: [200, 204]
method: GET
follow_redirects: true
preferred_ip_protocol: ip4
http_json:
prober: http
timeout: 5s
http:
valid_http_versions: [HTTP/1.1, HTTP/2.0]
headers:
Accept: [application/json]
body: '{"check":"status"}'
method: POST
tls_config:
min_version: "VersionTLS13"
tcp:
prober: tcp
timeout: 3s
tcp:
preferred_ip_protocol: ip4
udp:
prober: tcp
timeout: 3s
tcp:
preferred_ip_protocol: ip6
dns:
transport: tcp-tls
query_name: "example.com"
query_type: A
dns:
prober: dns
timeout: 4s
dns:
transport: tcp-tls
query_name: "example.com"
query_type: A
ssl:
prober: tcp
timeout: 5s
tcp:
preferred_ip_protocol: ip4
icmp:
prober: icmp
timeout: 2s
icmp:
preferred_ip_protocol: ip4
dns_lookup_family: ip4_protocol
webhook:
prober: webhook
timeout: 10s
webhook:
send_resolved_ip: true
headers:
X-Prometheus-Auth: ["Bearer eyJ..."]
```
Two footguns. The `udp` module uses the `tcp` prober under the hood because the exporter reuses the same TCP dialer with `net.Dial("udp", ...)`. And `icmp` needs the container to run with `NET_RAW` capability, or the module will silently return `probe_success 0` with a permission error in the exporter log.
## 4. SLO Derivation From Probe Metrics
Three metrics do the heavy lifting: `probe_success`, `probe_duration_seconds`, and `probe_inflight_requests`. The first is a 0/1 gauge; the second is a histogram; the third is a counter of probes currently in flight, useful for capacity planning.
Availability is `sum(rate(probe_success[30d])) / sum(rate(probe_success[30d]))` when the label distinguishes up from down. In practice you want a burn rate that treats any non-1 as failure:
```promql
sum(rate(probe_success{result="success"}[30d]))
/
sum(rate(probe_success[30d]))
```
For 99.9% availability over a month, you are allowed 43.2 minutes of downtime. Any expression that shows you below 0.999 means you have burned your budget. Alert on the ratio, not the raw `probe_success` count.
For latency SLO, use a histogram quantile:
```promql
histogram_quantile(
0.95,
sum by (le) (rate(probe_duration_seconds_bucket[5m]))
)
```
Anything above 500 ms on a public HTTP endpoint is a signal, not a fire. Anything above 2 seconds is a fire. I page on 500 ms sustained for 10 minutes; it's rare and always real.
`probe_inflight_requests` above 100 for a single target means the previous probe didn't return in time. That is your signal to look at the exporter's CPU.
## 5. ServiceMonitor for Multi-Target Probing
One exporter, hundreds of targets. The ServiceMonitor is the glue.
```yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: blackbox-http
namespace: monitoring
spec:
selector:
matchLabels:
app: blackbox-exporter
endpoints:
- port: blackbox-exporter
path: /probe
params:
module: [http_2xx]
interval: 30s
relabelings:
- sourceLabels: [__address__]
targetLabel: __param_target
replacement: "https://example.com"
- targetLabel: __param_module
replacement: "http_2xx"
- targetLabel: __address__
replacement: "10.0.1.5:9115"
```
The three gotchas I have personally stepped on:
- Forgetting `__param_module` causes every scrape to fall back to the default module, which may not exist. The exporter returns 404 and Prometheus marks the target as down.
- `relabelings` runs before `__param_target` is set, so your regex must match the pre-rewrite address.
- The `namespace` on the ServiceMonitor must be the Prometheus operator's namespace, not the exporter's. Mixing them is a common source of "probes never ran" reports.
PodMonitor differs only in `selector` matching pod labels and in `namespaceSelector` scoping. Use PodMonitor when the target pods have no Service; use ServiceMonitor otherwise.
## 6. Five Real Incidents
### 6.1 DNS Flakes at the Exporter Host
`probe_success` was bouncing 0/1 every 90 seconds for a target that worked from my laptop. I ran `dig +short example.com` inside the exporter pod and got timeouts. The node was on a corporate DNS relay that had stopped resolving. Fix: point the exporter's `/etc/resolv.conf` at a [Cloudflare](https://developers.cloudflare.com/) or Google resolver, and add `node-dns-probe` to the module list.
### 6.2 TLS Handshake Spikes Blamed on Upstream
p95 latency went from 180 ms to 2.3 s. The on-call engineer assumed the upstream service was slow and opened a ticket. I pulled `probe_dns_lookup_time_seconds` and it was the culprit: the exporter's DNS cache had expired and every lookup was going to the corporate resolver. The upstream had not changed a single millisecond.
### 6.3 ServiceMonitor Labels Not Matching
Probes silently never ran for a week. The ServiceMonitor was selecting on `app: blackbox-exporter` but the Helm release had been deployed with a different label. The scrape target list in Prometheus was empty. Rule of thumb: after any Helm upgrade, `kubectl get servicemonitor -A` and diff the labels against `kubectl get deploy`.
### 6.4 Alertmanager Silencing Too Early
A probe flapped between 0 and 1 for 12 minutes and Alertmanager's default `group_wait` collapsed everything into one notification. The real outage was masked. Fix: `for: 5m` on the burn-rate alert, and a separate `for: 1m` on the raw-down alert. Do not group `probe_success == 0` with other alert types.
### 6.5 Prometheus Starved by 500 Probes
We had 500 unique targets scraped every 30 seconds. That is 16.7 new time series per second per metric, times four metrics, times labels. Prometheus query endpoint p99 went from 200 ms to 4 s. Fix: split targets across two exporters behind a headless Service and halve the scrape interval on the noisy ones.
## 7. Six Ready-to-Paste Alerts
```yaml
- alert: ProbeDown
expr: probe_success == 0
for: 2m
labels:
severity: critical
annotations:
summary: "Blackbox probe failing on {{ $labels.instance }}"
- alert: ProbeLatencyHigh
expr: histogram_quantile(0.95, sum by (le, instance) (rate(probe_duration_seconds_bucket[5m]))) > 0.5
for: 10m
labels:
severity: warning
- alert: ProbeLatencyCritical
expr: histogram_quantile(0.99, sum by (le, instance) (rate(probe_duration_seconds_bucket[5m]))) > 2
for: 5m
labels:
severity: critical
- alert: ProbeStale
expr: time() - probe_timestamp_seconds > 120
for: 5m
labels:
severity: warning
- alert: ProbeInflightBacklog
expr: probe_inflight_requests > 100
for: 5m
labels:
severity: warning
- alert: AvailabilityBurnRate1d
expr: |
(
sum(rate(probe_success[5m]))
) /
(
sum(rate(probe_success[5m]))
) < 0.999
for: 30m
labels:
severity: critical
```
## 8. Production Checklist
1. Two replicas minimum, spread across zones with `topologySpreadConstraints`.
2. `probe_timeout_seconds` under 10 s — anything longer masks upstream slowness.
3. `resolv.conf` pointed at a resolver that is not on the same host as the exporter.
4. Resource limits: `requests: 200m/256Mi`, `limits: 500m/512Mi`. Do not go higher without profiling.
5. RBAC: the exporter pod needs only `get` on `secrets` if you mount auth tokens. No verbs on pods.
6. AlertManager grouping tuned: `group_wait: 1m`, `group_interval: 5m`.
7. A `dns` module that probes your own resolver, so DNS failures alarm.
8. A nightly canary that scrapes the exporter's `/probe` endpoint with a synthetic target, to catch silent exporter death.
## 9. Cheat Sheet
Twelve one-liners for common module needs:
- HTTP 2xx: `http_2xx.prober: http; http.timeout: 5s; valid_status_codes: [200,204]`
- HTTP 3xx-allowed: `valid_status_codes: [200,204,301,302,307,308]`
- HTTP no-redirect: `http.follow_redirects: false`
- TCP open: `tcp.prober: tcp; tcp.timeout: 3s; preferred_ip_protocol: ip4`
- UDP open: `tcp.prober: tcp; transport: udp`
- DNS A: `dns.prober: dns; dns.query_type: A; dns.query_name: example.com`
- DNS AAAA: `dns.query_type: AAAA`
- TLS valid: `tcp.prober: tcp; tls_config.min_version: "VersionTLS13"`
- ICMP ping: `icmp.prober: icmp; icmp.count: 2; icmp.timeout: 2s`
- Webhook: `webhook.prober: webhook; webhook.send_resolved_ip: true`
- Custom header: `http.headers.X-Custom: ["v1"]`
- IPv6 only: `preferred_ip_protocol: ip6`
And three PromQL snippets you will reach for weekly:
- Availability 24h: `sum(rate(probe_success{result="success"}[24h])) / sum(rate(probe_success[24h]))`
- p95 latency: `histogram_quantile(0.95, sum by (le) (rate(probe_duration_seconds_bucket[5m])))`
- Targets down now: `probe_success == 0`
That is the playbook. Everything above has been battle-tested in at least one cluster; anything I did not include, I have personally seen fail in a way that cost an on-call shift.
## Related Articles
- [node_exporter Metrics Missing — Six Symptom Categories, Root-Cause Decision Tree, and Five Real Incidents](node-exporter-metrics-missing.md)
- [node_exporter Metrics Missing: 6 Symptom Categories and 5 Real K8s Incidents](node-exporter-troubleshoot.md)
- [Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO](grafana-dashboard.md)
- [Alert Storms at 2 AM — An Alertmanager Grouping, Resolution, and Silence Decision Tree](monitor-alert-storm.md)
- [Grafana Dashboard Is Blank or Misaligned — A Troubleshooting Decision Tree](monitor-grafana-blank.md)
- [Reading CPU, Memory, and Disk IO Without Misjudging — a Host Signal Decision Tree](monitor-host-signals.md)
- [Prometheus Targets All Down and No Data — A Troubleshooting Decision Tree](monitor-prometheus-no-data.md)
- [Log Partition Full Postmortem: /var/log at 100% Silently Broke Services](../postmortems/log-partition-full.md)
---
## Chaos Engineering in Production: Fault Injection from Experiment Design to Safe Live Drills
URL: https://ops.jiunotes.top/en/monitor/chaos-engineering.md
摘要: Chaos Engineering as a hypothesis-driven discipline: tool selection across Chaos Mesh, Litmus and Chaos Blade, four-step experiment design, production safety rails, and three live drill postmortems including one deliberate failure that exposed a connection-pool flaw.
### Answer
Chaos Engineering is not about breaking things; it is about actively verifying how a system behaves under fault before the fault finds you. I started it after a production incident where a single pod network blip cascaded into three core services going down. The discipline runs on four steps: state a steady-state hypothesis, design a bounded experiment, inject the fault, and verify or falsify the hypothesis. Chaos Mesh is my production tool of choice, Chaos Blade for quick staging checks. The safety rails that matter are scope limitation, an observation window, and automatic rollback when any metric crosses a threshold.
### FAQ
Q: Will chaos engineering take down production?
A: It can, if you skip the boundaries. My first live drill killed three production pods because I had no scope limit. The defenses that fixed it: run the experiment design in staging first, pin the selector to a fixed-count of pods so it cannot spread, attach an automatic rollback when any metric crosses a threshold, and schedule during low traffic. Scope limits turned the same experiment from dangerous to routine.
Q: What team size makes chaos engineering worthwhile?
A: I would say at least five services, Kubernetes fluency, and a real on-call rotation. Below that, most failures are human error and a chaos drill will not reveal much, while the tooling overhead is real. My team of eight running fifteen services is where it started paying for itself.
Q: What is the difference between Chaos Mesh and a fault-injection script?
A: Chaos Mesh is a declarative CRD controller. It controls the exact time, scope and duration of injection and self-recovers. A hand-written script can simulate a simple kill but lacks precise control and automatic recovery, which makes it risky for production. My rule: scripts are fine for one-off staging checks; anything with a network partition needs Chaos Mesh.
Q: How often should I run chaos experiments?
A: I run one controlled drill per week in production and keep the number low on purpose. Frequent drilling trains the team, but it also consumes attention and risks real fatigue in the on-call rotation. The rhythm that works for me is a steady weekly cadence, plus a dedicated drill every quarter that targets a failure mode we have never tested before.
### Full Content
# Chaos Engineering in Production: Fault Injection from Experiment Design to Safe Live Drills
In 2023 a pod in our payment system hit a network blip. The timeouts cascaded and three core services went down at once. During the postmortem I realized we had never tested that exact failure mode. We had no idea the system would react that way, because we had never asked it. That is the entire point of chaos engineering: you ask the question on your schedule, not on the fault's schedule.
This article covers the full path I took, from tool selection to production drills, including three live experiments and one that deliberately failed.
## The Core Idea: Hypothesis-Driven, Not Random Destruction
Chaos engineering is not "throw random failures at the cluster and hope." It is a **controlled experiment based on a falsifiable hypothesis**.
```
1. State the steady-state hypothesis
"This service should be 99.9% available at <200ms average latency"
2. Design the experiment
"If I kill 50% of the pods, does the service hold steady state?"
3. Execute the experiment
inject fault → observe → record
4. Verify or falsify
Hypothesis holds: service degrades but stays available, P99 goes 200ms→800ms, still in SLA
Hypothesis fails: service is unavailable, dependency config needs fixing
```
**The rule I never break:** an experiment must have a hypothesis, observation metrics, and a rollback plan. If any of the three is missing, do not run it.
## Tool Selection: Chaos Mesh vs Litmus vs Chaos Blade
| Dimension | Chaos Mesh | LitmusChaos | Chaos Blade |
|---|---|---|---|
| Origin | Meituan open source | Alibaba Cloud open source | Alibaba open source |
| [Kubernetes](https://kubernetes.io/docs/) model | Native CRD | Native CRD | DaemonSet |
| Experiment types | Rich (network/CPU/IO/kernel) | Medium (K8s-focused) | Light (script-based) |
| Documentation | Excellent | Good | Fair |
| Community activity | High | Medium-high | Medium |
| Learning curve | Medium | Low | Lowest |
| Best fit | Production-grade drills | Domestic compliance | Quick validation |
**My choice:** Chaos Mesh for production drills (most complete, best docs), Chaos Blade for staging spot-checks (light, fast to deploy).
## Experiment Design: Four Steps
### Step 1: State the Hypothesis
```
Hypothesis: when 2 payment-service pods crash simultaneously,
the remaining pods absorb all traffic at ≥99.5% API availability
```
### Step 2: Define the Experiment Scope
```yaml
# chaos-mesh/pod-failure.yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
name: payment-pod-failure
namespace: payment-system
spec:
selector:
matchLabels:
app: payment-service
env: production
mode: fixed-count # affect exactly 2 pods, no more
value:
count: 2
action: pod-failure # kill the pod, not simulate latency
duration: '5m' # auto-recover after 5 minutes
scheduler:
cron: '@every 1h' # run hourly during the drill window
```
The three design details that keep this safe:
- `mode: fixed-count`: precise blast radius, cannot spill onto other services.
- `duration: 5m`: the experiment has a hard upper bound; no infinite fault.
- `scheduler.cron`: run at 02:00-04:00 in the low-traffic window to minimize business impact.
### Step 3: Define Observation Metrics
```yaml
# metrics to watch continuously during the drill
- payment_service_request_success_rate # success rate
- payment_service_latency_p99 # P99 latency
- payment_service_error_count_5xx # 5xx count
- payment_service_pod_healthy_count # healthy pod count
- downstream_dependency_status # is the downstream affected
```
**Principle:** define the observation metrics *before* the drill starts. An experiment validates a hypothesis; it is not a fishing expedition. Deciding what to watch mid-drill is how you miss the thing you were testing.
### Step 4: Define Rollback Conditions
```yaml
# terminate the drill if any condition is met
rollback_conditions:
- metric: payment_service_request_success_rate
condition: '< 0.95' # success below 95% → stop now
- metric: payment_service_latency_p99
condition: '> 2000' # P99 over 2 seconds → stop now
- manual: true # a human can stop it at any time
```
## Drill One: Pod Kill (Hypothesis Held)
**Hypothesis:** when 50% of payment-service pods crash, the service recovers automatically.
```bash
# run the drill
cmctl create podchaos payment-pod-failure -f chaos-mesh/pod-failure.yaml
# inspect the running experiment
cmctl get podchaos payment-pod-failure
# compare the [Grafana](https://grafana.com/docs/) panel 30 minutes before vs after
```
**Result:**
- ✅ Hypothesis held: autoscaling completed in 45 seconds, success rate stayed at 99.8%.
- ⚠️ Secondary finding: new pods had a 2-second DNS resolution delay, causing a few timeouts.
- 🔧 Fix: added a DNS cache TTL to kube-proxy.
**Lesson:** this drill surfaced a race condition that would never have shown up in production — DNS delay during scale-out. Finding it in a drill costs minutes; finding it live costs an incident.
## Drill Two: Network Partition (Hypothesis Failed)
**Hypothesis:** a 30-second network partition between payment-service and the database degrades gracefully.
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: payment-db-network-partition
namespace: payment-system
spec:
selector:
matchLabels:
app: payment-service
targetSelector:
matchLabels:
app: postgres-primary
action: partition # network partition
direction: both # block both directions
duration: '30s'
```
**Result:**
- ❌ Hypothesis failed: the connection pool did not release correctly. After the DB recovered, connections piled up.
- 🔥 Real impact: the fault lasted 30 seconds, but pool recovery took 8 minutes.
- 💥 Cascade: downstream callers of payment-service also timed out, two services went down together.
**Postmortem:** this failure was the most valuable outcome of the whole program. It exposed a failure mode we had never tested. The fixes:
1. Add `maxLifetime` and `idleTimeout` to the DB connection pool.
2. Add a circuit breaker to payment-service.
3. Make the next drill specifically verify that circuit breaker fires.
**This is the point:** chaos engineering is not about proving the system is strong. It is about finding the weak spots before they find you. A failed hypothesis is worth more than a passed one.
## Drill Three: CPU Stress (Partially Held)
**Hypothesis:** at 90% CPU utilization, payment-service rate-limits QPS and does not cascade.
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata:
name: payment-cpu-stress
namespace: payment-system
spec:
selector:
matchLabels:
app: payment-service
mode: fixed-count
value:
count: 2
stressors:
cpu:
workers: 4
load: 80 # 80% CPU load
queues: 4
duration: '10m'
```
**Result:**
- ✅ Partially held: QPS did drop, but by 30% instead of the expected 10%.
- ⚠️ New finding: GC pause time jumped from 50ms to 800ms under CPU pressure, spiking single-request latency.
- 🔧 Fix: adjusted JVM heap size and G1 GC parameters.
**Key insight:** the CPU drill exposed GC behavior that no dashboard showed. Without chaos engineering, that problem would have surfaced during a big sale.
## Safety Rails: Five Constraints for Production Drills
```
1. Scope: only affect the target service, never spread to upstream or downstream
2. Time: run in the low-traffic window, with a hard duration cap (max 10 minutes)
3. Rollback: any observation metric crossing a threshold stops the drill automatically
4. Permission: the drill operator needs SRE approval, never a single-handed run
5. Notification: announce the drill to the affected teams in Slack before it starts
```
**Hard rules I follow:**
- Maximum 2 production chaos experiments per week.
- Zero chaos experiments in the 7 days before a big sale.
- A full staging rehearsal before any production drill.
## Archiving and Quarterly Retests: Making Drills Into an Asset
The biggest waste in chaos engineering is not failure — it is "run it and let it scatter." A drill happens, the conclusion gets discussed, and nothing is kept; a quarter later the team re-runs the same service, only to discover it was actually fixed months ago, and the whole exercise was for nothing. I treat every experiment as a re-testable asset, with four disciplines:
**Give every experiment a fixed directory; store the hypothesis and the outcome together.** That directory always holds four things: the experiment hypothesis (verbatim), the CRD/command that injected the fault, a snapshot of the observation metrics (a Grafana panel screenshot or exported JSON), and the final verdict (held / falsified / partial). Only when all four are present does it count as a valid experiment; missing any one means it is marked "not closed," and I do not treat it as done. This way anyone opening the archive can reconstruct the reasoning in thirty seconds, instead of relying on that fuzzy "I think it was 800 ms" memory.
**A verdict must carry numbers; never write the bare words "it held up."** "The service held up" is a description, not a conclusion. A conclusion reads "P99 rose from 200 ms to 800 ms, still inside the SLO (2 s), verdict: held." Pin down both the expected threshold and the measured value. Then a quarterly retest is just a comparison: the same experiment that pushed P99 to 800 ms last quarter is now pushing it to 1600 ms — even though it has not breached the SLO, the regression alone should fire an alert, because **resilience degrades quietly as code evolves**, and without a historical baseline you have no way to know it is degrading.
**Retest on a fixed quarterly cadence, and only retest the experiments that found problems last time.** I do not re-run every experiment every quarter (expensive, low value). I prioritize the ones that came back "falsified" or "partial" last quarter — whether the fix actually fixed it can only be confirmed by running it again, not by the confidence that "it should be fixed now." The network-partition experiment with the connection-pileup, for instance, was re-run the following quarter after the fix; only after the pool recovery dropped from 8 minutes to 40 seconds did I mark that experiment "closed."
**Feed experiment results back into alert thresholds.** The real thresholds a chaos experiment measures are more trustworthy than alert lines set by guesswork. If the CPU-stress experiment showed that GC pause has to hit 800 ms before single-request latency truly spikes, then the GC-pause alert line belongs at that order of magnitude, not at some 100 ms set by habit. Writing the measured numbers into the monitoring rules is what makes a chaos drill's output actually join the day-to-day defense, instead of sitting in a report nobody reads.
## The Drill-Day Checklist
Before I ever hit apply, I walk a short checklist in the operator channel. It looks boring, and that is exactly why it works.
```
[ ] Hypothesis stated in one sentence, readable by a human
[ ] Blast radius pinned: fixed-count selector, named namespace
[ ] Observation panel open and confirmed live
[ ] Rollback conditions wired and tested with a manual stop
[ ] Announcement posted to the affected teams
[ ] Two operators present: one drives, one watches the panel
[ ] Timebox set: never more than 10 minutes
```
If any box is unchecked, I close the window and postpone. The drills that went wrong for me are the ones where I skipped a line to save five minutes.
## How to Sell Chaos Engineering to Management
Use the cost of a real incident as the anchor:
- Show the cost of a production outage (downtime × hourly revenue loss).
- Show the number of weak points each drill uncovered (quantified risk).
- Show that the fix cost is a fraction of the incident cost.
- Emphasize "find it deliberately" versus "find it on fire."
After our first drill I wrote a postmortem that included a line item: "if this failure had happened in production, the estimated loss would be X." That single number convinced the CTO to fund the annual chaos program.
## FAQ
### Q: What is the difference between chaos engineering and A/B testing?
Chaos engineering validates a *reliability* hypothesis; A/B testing validates a *business feature* hypothesis. The methodology is similar (hypothesis → experiment → observe → conclude), but the goal differs: chaos finds weak points, A/B finds the best business variant. The tooling is entirely different as well.
### Q: What happens when a chaos experiment fails?
A "failed" experiment (hypothesis falsified) is a normal and valuable outcome. What matters is what you do next:
1. Record the process and the failure reason.
2. Analyze root cause and write a fix plan.
3. Re-run the experiment after the fix to verify.
4. Turn the drill into team knowledge (runbook, postmortem).
Do not treat a falsified hypothesis as an incident. That falsification is the whole point.
### Q: Is chaos engineering the same as a game day?
They overlap but are not identical. A game day is a broad, often team-wide rehearsal of a known runbook. A chaos experiment is a narrow, hypothesis-driven fault injection targeting one behavior. I use game days to rehearse response, and chaos drills to discover unknown behavior. Both belong in a mature resilience program.
## Related Articles
- [Blackbox Exporter Probe Configuration for SLO Design](blackbox-exporter.md)
- [Grafana Dashboard Design for SRE SLO Tracking](grafana-dashboard.md)
- [Loki Log Aggregation for Incident Forensics](loki-log-aggregation.md)
---
## Continuous Profiling in Practice: eBPF and Pyroscope from Sampling to a Real 500ms-to-50ms Optimization
URL: https://ops.jiunotes.top/en/monitor/continuous-profiling.md
摘要: Continuous Profiling with Pyroscope and eBPF: the three-component architecture, eBPF versus SDK sampling, reading CPU/memory/mutex flame graphs, production deployment pitfalls, and a real optimization case that cut P99 latency from 500ms to 50ms in 30 minutes.
### Answer
Continuous Profiling is the last piece of the observability stack. Traditional monitoring answers "what is wrong with the system"; profiling answers "what is the system doing right now." Pyroscope is the open-source platform I run, combining eBPF for zero-instrumentation system-level sampling with an SDK for function-level stacks. Its core value is that you can see CPU and memory hot spots in production without redeploying or changing code. The tradeoff is real: eBPF only sees the syscall layer on Linux x86_64, so Java and Go function-level detail needs an SDK. My biggest win was a 30-minute diagnosis of a P99 regression that two days of snapshot-based debugging could not catch.
### FAQ
Q: How is continuous profiling different from pprof or perf?
A: pprof and perf are one-shot snapshots. You run the command, get a picture of a moment, and the problem may already be gone. Continuous profiling samples on a schedule, accumulates a long-term trend, and lets you compare two time windows against each other. Pyroscope adds persistence, visualization, and history comparison that a one-shot tool cannot.
Q: Is eBPF or SDK profiling better?
A: They answer different questions. eBPF is zero-instrumentation and sees the syscall layer, but cannot see inside application logic. An SDK sees full function stacks with high precision, but needs code changes or build-time instrumentation. My best practice is both: eBPF for system-level CPU/memory/IO, SDK for function-level hot spots.
Q: How does Pyroscope relate to Prometheus and Grafana?
A: Pyroscope is a standalone profiling platform. It exports via OTLP and has a Grafana datasource plugin, so you can render flame graphs directly inside Grafana. The data flow is application → Pyroscope agent → Pyroscope server → Grafana. You do not have to use Pyroscope; Parca is a valid alternative backend.
Q: What sample rate should I run in production?
A: I keep 10Hz as the default. At 100Hz the flame graph is sharper, but data volume and storage cost scale up tenfold. My rule is 10Hz for steady state, and a temporary bump to 100Hz only while diagnosing an active incident. After the incident I drop it back down before it becomes a permanent budget line.
### Full Content
# Continuous Profiling in Practice: eBPF and Pyroscope from Sampling to a Real Optimization
Last year a Go service in our payment stack saw P99 latency jump from 100ms to 500ms. Two engineers spent two days on it and found nothing. We had tried pprof snapshots, but the problem was intermittent — by the time we attached, the spike was gone. The answer came from Pyroscope continuous profiling: thirty minutes of flame-graph comparison showed the hot path was a `map` operation triggering repeated full GC pauses.
The lesson stuck with me: **continuous profiling preserves history**. Even when the problem is not reproducing right now, the samples are still in the store, and the trend is visible. This article covers the architecture, the deployment, the pitfalls, and that one optimization.
## Pyroscope Architecture: Three Components
```
┌─────────────┐ ┌──────────────┐ ┌──────────────┐
│ Agent │────▶│ Pyroscope │────▶│ [Grafana](https://grafana.com/docs/) │
│ (sampling) │ │ Server │ │ (visualization)
│ eBPF/SDK │ │ (store) │ │ │
└─────────────┘ └──────────────┘ └──────────────┘
```
- **Agent**: runs next to the target process (or as a sidecar), samples CPU/memory flame graphs.
- **Pyroscope Server**: receives, stores, aggregates profile data, and serves the query API.
- **Grafana**: renders flame graphs and historical comparisons via the Pyroscope plugin.
## Two Sampling Modes: eBPF vs SDK
### eBPF Mode: Zero Instrumentation
eBPF samples at the kernel layer without touching application code, so it works on any binary.
```bash
# run the Pyroscope eBPF agent as a sidecar or DaemonSet
docker run -d \
--name pyroscope-agent \
-v /proc:/host/proc:ro \
-v /sys:/host/sys:ro \
-v /:/rootfs:ro \
-e PYROSCOPE_APP_NAME=my-go-service \
-e PYROSCOPE_SERVER_ADDRESS=http://pyroscope-server:4040 \
--privileged \
pyroscopeio/pyroscope:latest \
agent \
--collectors=cpu,Memory,mutex,blocks
```
**eBPF limits I hit:**
- [Linux](https://www.kernel.org/doc/html/latest/) x86_64/arm64 only.
- Kernel >= 4.9 (ideally >= 5.4 with BTF).
- Cannot see user-space function stacks for managed runtimes (Go goroutines, Java GC).
### SDK Mode: Function-Level Precision
The SDK samples at the application layer and produces complete call stacks.
```go
// Go: integrate pprof with the Pyroscope exporter
import (
"go.pyroscope.io/godeltaprof/http/pprof"
pyroscope "go.pyroscope.io/pyroscope/pkg/client"
)
func init() {
pyroscope.Configure(pyroscope.Config{
ApplicationName: "my-go-service",
ServerAddress: "http://pyroscope-server:4040",
LogWriter: os.Stdout,
ProfilingEnabled: map[pyroscope.ProfileType]bool{
pyroscope.ProfileCPU: true,
pyroscope.ProfileAllocObjects: true,
pyroscope.ProfileAllocSpace: true,
pyroscope.ProfileInuseObjects: true,
pyroscope.ProfileInuseSpace: true,
pyroscope.ProfileGoroutines: true,
pyroscope.ProfileMutexCount: true,
pyroscope.ProfileMutexDuration:true,
pyroscope.ProfileBlockCount: true,
pyroscope.ProfileBlockDuration:true,
},
})
}
```
```python
# [Python](https://docs.python.org/): pyroscope-python SDK
# pip install pyroscope-io
import pyroscope
pyroscope.configure(
application_name="my-python-service",
server_address="http://pyroscope-server:4040",
tags={"service": "payment", "env": "production"},
)
```
**My judgment:** for Go/Python/Java I prefer SDK because it gives function-level hot spots. eBPF is the fallback for services where I have no source. When both are available, SDK first, eBPF as the system-level complement.
## Production Deployment: Standing Up the Server
```yaml
# docker-compose.yml for Pyroscope
version: '3.8'
services:
pyroscope:
image: pyroscopeio/pyroscope:latest
restart: unless-stopped
ports:
- "4040:4040" # agent ingestion port
- "6060:6060" # HTTP API
environment:
- PYROSCOPE_WRITE_USERNAME=admin
- PYROSCOPE_WRITE_PASSWORD=${PYROSCOPE_PASSWORD}
- PYROSCOPE_AUTH_ENABLED=true
- PYROSCOPE_DATA_RETENTION=72h
volumes:
- pyroscope-data:/data
grafana:
image: grafana/grafana:11.1.0
restart: unless-stopped
ports:
- "3000:3000"
environment:
- GF_INSTALL_PLUGINS=grafana-pyroscope-datasource
volumes:
- grafana-data:/var/lib/grafana
depends_on: [pyroscope]
volumes:
pyroscope-data:
grafana-data:
```
**Critical settings:**
- `DATA_RETENTION=72h`: three days is enough for incident back-tracing; anything longer needs object storage.
- `AUTH_ENABLED=true`: mandatory. Profile data contains code paths and function names, which is sensitive.
- `grafana-pyroscope-datasource`: lets you read flame graphs inside Grafana.
## Reading a Flame Graph: Three Views
### CPU Profiling: Where the Time Goes
```
# X axis: time, left to right
# Y axis: call stack depth, bottom to top
# block width: share of CPU time
# hot-spot rules:
# 1. widest block = most CPU-hungry function
# 2. blocks closest to the bottom = entry points (main/goroutine)
# 3. red-highlighted = GC-related functions (Go-specific)
```
**Real case:** in one optimization I found `processPayment()` eating 40% of CPU. Expanding the stack showed `calculateTax()` doing heavy string concatenation in a loop, which in Go allocates a lot of temporary objects.
```go
// ❌ bad: string concatenation in a loop creates many temporary objects
func calculateTax(amount float64) string {
result := ""
for i := 0; i < 1000; i++ {
result += fmt.Sprintf("item-%d: %.2f\n", i, amount*0.1)
}
return result
}
// ✅ good: use strings.Builder
func calculateTax(amount float64) string {
var sb strings.Builder
for i := 0; i < 1000; i++ {
fmt.Fprintf(&sb, "item-%d: %.2f\n", i, amount*0.1)
}
return sb.String()
}
```
**Result:** `calculateTax()` CPU share dropped from 40% to 3%, and P99 went from 500ms to 50ms.
### Memory Profiling: Allocation Hot Spots
```yaml
# memory profile exposes four series:
# 1. alloc_objects: number of allocated objects
# 2. alloc_space: bytes allocated
# 3. inuse_objects: live objects right now
# 4. inuse_space: live bytes right now
```
**Interpretation rules I use:**
- `alloc_space` high → heavy GC pressure (long pauses).
- `inuse_space` climbing → leak suspect (objects not being collected).
- `alloc_objects` high but `inuse_objects` low → many short-lived objects, frequent GC.
**Real case:** a Java service showed `inuse_space` climbing steadily. The culprit was a connection pool that never closed connections — each request opened an HTTP connection and never released it. Seven days later the service OOM'd. Profiling caught it at day three.
### Mutex and Block Profiling: Concurrency Bottlenecks
```yaml
# Go-specific profiles:
# 1. mutex_count: lock contention count
# 2. mutex_duration: lock wait time
# 3. block_count: goroutine block count
# 4. block_duration: goroutine block time
```
**Interpretation rules:**
- `mutex_duration` high → heavy contention, consider RW locks or lock-free structures.
- `block_duration` high → channel/send blocking, consider async or bigger buffers.
## Production Pitfalls
### Pit 1: eBPF Agent Permission Denied
```
Error: unable to attach probe: operation not permitted
Error: bpf: Operation not permitted
```
The container lacks `CAP_SYS_ADMIN`, and the seccomp profile restricts eBPF syscalls. The agent needs `privileged: true`, or the `SYS_ADMIN`/`BPF`/`PERFMON` capabilities with seccomp unconfined. My advice: run the eBPF agent as a DaemonSet with hostPID on the node, not inside the app container. Half the permission problems disappear.
### Pit 2: Retention Set Too Long Fills the Disk
```yaml
# ❌ bad: 30 days of profile data is terabytes
PYROSCOPE_DATA_RETENTION=30d
# ✅ good: 72 hours is enough for production
PYROSCOPE_DATA_RETENTION=72h
```
**The math:** one Go service sampled once per second, about 1KB per sample, over 72 hours is roughly 72 × 3600 × 1 ≈ 260MB. Across 100 services that is about 26GB — manageable. At 30 days it becomes a terabyte-scale problem.
### Pit 3: Flame Graph Too Blurry, Sample Rate Too Low
```yaml
# default sample rate is 10Hz (10 samples per second)
# fast functions can be invisible at this rate
# raise to 100Hz for diagnosis
PYROSCOPE_PROFILE_RATE=100
```
**Note:** higher sample rate means more data and more storage pressure. I only raise it temporarily during diagnosis and keep 10Hz the rest of the time.
## Balancing Cost and Fidelity
Continuous profiling has a cost curve, and it is not free. The storage math above makes that clear. My approach is to scale sample rate with value: keep a modest 10Hz on the hot services that already have SDK instrumentation, and only bump the eBPF collectors during a diagnosed incident. I also cap the number of profiled applications. Profiling every container in the cluster is the fastest way to turn a useful tool into a budget line item. Pick the services that matter, instrument them well, and leave the long tail to system metrics.
## The 500ms to 50ms Optimization, End to End
**Background:** payment service P99 jumped from 100ms to 500ms and stayed there for two days.
### Step 1: Open the Flame Graph
```
# in the Pyroscope UI:
# 1. Application: my-payment-service
# 2. Profile type: cpu
# 3. Time range: last 2 hours
# 4. Compare: before the incident vs during the incident
```
### Step 2: Locate the Hot Function
The flame graph showed `processPayment()` at 40% CPU. Expanding it revealed `calculateTax()` as the dominant cost.
### Step 3: Walk the Stack
Going deeper, `calculateTax()` was a string-concatenation loop. That did not match our code review, so I suspected a recent commit.
```bash
git blame --date=short src/payment/tax.go | grep "result +="
# output: a1b2c3d 2024-03-15 xxx result += fmt.Sprintf(...)
```
### Step 4: Fix and Ship
```go
// rewrote tax.go to use strings.Builder instead of concatenation
// opened the PR, passed review, deployed
```
### Step 5: Verify
```bash
# 10 minutes after deploy, reopen the flame graph
# confirm calculateTax() CPU share dropped from 40% to 3%
# confirm P99 latency dropped from 500ms to 50ms
```
**Total time:** 30 minutes from symptom to verified fix. With snapshot-based pprof and manual reproduction, the same diagnosis would have taken days, if it happened at all.
## Choosing a Sampler and Weighing the Cost
Pyroscope, once it is on, is profiling tens or hundreds of services at once, and the overhead and storage climb with it. I make the choice with three questions — do we have source, what language, and how deep do we need to see — and I cut wherever I can.
First: is there source? For languages with source (Go, Java, Python, Node) the SDK mode wins because it gets you function-level stacks and tells you the exact line. For things with no source (closed C services, system components, third-party binaries) eBPF is all you have, and the syscall layer is enough there. Running both layers on the same service is the most expensive option; skip it unless that service is a genuine hot spot and you specifically want to cross-check the two layers.
Second: how deep do you need to go? If you only want to know "what class of operation is the CPU going to" (I/O versus compute, lock contention versus pure work), eBPF is sufficient and zero-intrusive. If you need "which function, which call," you have to use the SDK — eBPF is blind to user-space function boundaries. Most day-to-day inspection honestly only needs the first tier; reserve the SDK for the services you are actually digging into.
Third: is the sampling density worth it? Higher rate is not better — overhead and storage both rise linearly, and beyond a certain density the "resolution benefit" in the flame graph has saturated. I keep the full fleet at 10Hz and only push a service to 100Hz while it is under investigation, then drop it back. A fleet-wide 100Hz is a performance killer and a storage black hole; do not keep it on just to feel you have more precision.
Cost belongs in the capacity model. Every service you add for profiling makes its agent eat CPU and memory, and the Pyroscope server disk grows with service-count times retention. Before launch, size the disk budget by "service-count times sample-rate times retention," and do not wait until retention is long and the disk is full to realize you never did that math. This is also why I insist on `DATA_RETENTION=72h` — enough for a forensic look-back, without eating the disk.
Based on a typical production scenario: a 200-service environment started out profiling everything with the SDK at 100Hz to save effort. Within a week the Pyroscope server disk went from 100G to 900G, and the agents' own CPU pushed a few services' P99 up by 8ms. After moving to "SDK for the hot services, eBPF for the rest, full fleet at 10Hz," disk settled under 200G and the business overhead dropped back to imperceptible. The lesson: continuous profiling's cost model is "breadth times density times duration," and you can save on any one of the three — cut density first, then breadth, and only then the retention.
## FAQ
### Q: Can I run Pyroscope and pprof at the same time?
Yes, and I recommend it. Pyroscope gives you continuous monitoring and history comparison; pprof gives you a precise full stack at one instant. The workflow is Pyroscope finds the anomaly → pprof pins it down → fix → Pyroscope verifies.
### Q: Does profiling data leak business secrets?
It can. Flame graphs expose function names, code paths, and sometimes business logic. Mitigations: enable authentication (`AUTH_ENABLED=true`), restrict production access to SRE and security, and avoid custom profilers that embed sensitive variable values.
### Q: Without source code, am I stuck with eBPF flame graphs only?
Yes, for function-level detail. But eBPF still shows syscall-level hot spots (`read`, `write`, `mmap`), and most performance problems — I/O bottlenecks, lock contention, allocation — leave traces at that layer. Function-level diagnosis is what the SDK is for.
## Related Articles
- [eBPF Observability Principles: Non-Invasive Monitoring from Kernel Traces to Production](ebpf-observability.md)
- [PromQL Quick Reference: 5 Golden Metrics and Copy-Paste Templates](prometheus-query.md)
- [Grafana Dashboard Design for SRE SLO Tracking](grafana-dashboard.md)
- [Platform Engineering: Building an Internal Developer Portal from Zero, and the Failure That Taught Me the Hard Way](platform-engineering.md)
- [Defining SLOs and Burning the Error Budget: A Reliability-Policy Playbook](slo-definition-error-budget-policy.md)
---
## Database Monitoring in Production — PostgreSQL & MySQL with postgres_exporter and mysqld_exporter
URL: https://ops.jiunotes.top/en/monitor/database-monitoring-postgres-mysql.md
摘要: Database monitoring field guide: four failure decision trees (pool, locks, lag, slow queries), five first-person incidents, metric misconceptions, and Prometheus rules for PostgreSQL and MySQL.
### Answer
Monitoring a database is not monitoring a host. PostgreSQL and MySQL failures are locks, IO waits, and pool exhaustion that never show up as CPU. This field guide gives you four failure decision trees, five real incidents, the correct metrics, and alert rules with the pitfalls that keep on-call engineers from paging at 2 AM.
### FAQ
Q: Which metric do I use for PostgreSQL replication lag?
A: Use `pg_stat_replication.replay_lag` (seconds), exported as `pg_stat_replication_replay_lag_seconds`. There is NO `pg_replication_lag_seconds` metric. If `replay_lag` jumps, check clock skew first with `chronyc tracking`/`ntpstat` on both hosts; a 3-second clock offset reads as 3 seconds of fake lag.
Q: Why is my MySQL deadlock alert never firing?
A: There is no built-in deadlock counter. Use `rate(mysql_global_status_innodb_row_lock_waits[5m])` for row-lock waits, or count `SHOW ENGINE INNODB STATUS` with `innodb_print_all_deadlocks=ON`. Do not hunt for a metric the server never exports.
Q: What is the difference between Threads_connected and Threads_running?
A: `Threads_connected` is every open connection including idle; `Threads_running` is only connections executing a query now. Alert on `connected/max_connections` (>0.80 warn, >0.90 critical); use `rate(Threads_running[5m])` as a load gauge, never an alarm. Conflating them is the most common MySQL mistake.
Q: Why does my pg_stat_statements query show nothing after CREATE EXTENSION?
A: `pg_stat_statements` is a shared preload library. `CREATE EXTENSION` alone does nothing until you set `shared_preload_libraries = 'pg_stat_statements'` in postgresql.conf AND restart. Verify with `SHOW shared_preload_libraries;`. After restart, `mean_exec_time` (ms) is the field to alert on.
Q: How do I stop replication-lag alert noise from transient spikes?
A: Clock skew, long-running transactions, and network jitter all produce one-sample spikes in `replay_lag` and `seconds_behind_master`. Never alert on a single scrape: add `for: 5m` in Prometheus rules and use `max_over_time`/`min_over_time` in dashboards. Sustained 5-minute lag is real; one sample is not.
Q: Should I use a dedicated monitoring user instead of root?
A: Always. PostgreSQL: `CREATE ROLE pg_exporter LOGIN; GRANT pg_monitor TO pg_exporter;`. MySQL: `CREATE USER ...; GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.*;`. Never reuse the app account or root, and bind the exporter to `127.0.0.1`.
### Full Content
# Database Monitoring in Production — PostgreSQL & MySQL with postgres_exporter and mysqld_exporter
At 02:14 the page came in: API p99 latency above 5 seconds and climbing. I pulled up the web-tier graph first — CPU 15%, memory steady, load average quiet. Every host metric was boring. Then I checked the app's connection pool: saturated at 95% of `max_connections`, and `pg_stat_activity` showed six sessions sitting `idle in transaction` with locks they had never released. The database answered pings but was effectively dead to my users. That night I learned what this article is built around: **a database is not a host**. The CPU graph stays green while the database burns.
This is the runbook I wish I had then. It covers [postgres_exporter](https://github.com/prometheus-community/postgres_exporter) and [mysqld_exporter](https://github.com/prometheus-community/mysqld_exporter) end to end, four failure decision trees, five incidents I actually worked, and the metric names tutorials routinely get wrong. If you already have the baseline, see [Prometheus Deploy](prometheus-deploy.md) and [Prometheus Query](prometheus-query.md).
## Why Monitoring a Database Is Not Monitoring a Host
Host monitoring asks: is the box healthy? Database monitoring asks a harder one: can the engine serve queries at the latency my app needs? They diverge constantly.
- **Locks and IO waits are invisible in CPU.** A query blocked on a row lock consumes almost no CPU; a checkpoint flushing dirty pages is IO-bound. `node_cpu_seconds_total` looks great while p99 latency is 6 seconds.
- **"Fake death" is worse than a hard down.** When the database crashes, every monitor fires and everyone converges. When it is up but saturated, nothing screams — connections succeed, pings return OK, and the slow trickle is just "performance." I have lost more sleep to fake deaths than to real outages.
- **The state that matters is in the engine.** Connection counts, lock waits, lag, and execution times live in the database's own statistics views. The exporter's job is to pull those out into Prometheus metrics.
## The Pipeline: Database → Exporter → Prometheus → Alertmanager / Grafana
The exporter exposes metrics on a port, Prometheus scrapes on a schedule, Alertmanager routes, Grafana renders. Two deployment shapes matter.
### Docker Compose (quick start)
```yaml
# docker-compose.yml
services:
postgres-exporter:
image: prometheuscommunity/postgres-exporter:latest
command: --web.listen-address=:9187
environment:
DATA_SOURCE_URI: "localhost:5432/postgres?sslmode=disable"
DATA_SOURCE_USER: "pg_exporter"
DATA_SOURCE_PASS_FILE: /run/secrets/pg_exporter_pw
ports: ["9187:9187"]
secrets: [pg_exporter_pw]
restart: unless-stopped
mysql-exporter:
image: prom/mysqld-exporter:latest
command: --web.listen-address=:9104
environment:
MYSQLD_EXPORTER_PASSWORD_FILE: /run/secrets/mysql_exporter_pw
ports: ["9104:9104"]
secrets: [mysql_exporter_pw]
restart: unless-stopped
secrets:
pg_exporter_pw: { file: ./secrets/pg_exporter_pw }
mysql_exporter_pw: { file: ./secrets/mysql_exporter_pw }
```
Never put the password in the command line or a committed env var — use a Docker secret or a `_FILE` reference.
### systemd (production)
```ini
# /etc/systemd/system/postgres-exporter.service
[Unit]
Description=postgres_exporter
After=network.target postgresql.service
[Service]
User=pg_exporter
Environment=DATA_SOURCE_URI=localhost:5432/postgres?sslmode=disable
Environment=DATA_SOURCE_USER=pg_exporter
EnvironmentFile=/etc/postgres-exporter.env # DATA_SOURCE_PASS_FILE=/run/secrets/pg_pw
ExecStart=/usr/local/bin/postgres_exporter --web.listen-address=127.0.0.1:9187
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
```
The MySQL unit is the same shape with `--web.listen-address=127.0.0.1:9104`. Bind to `127.0.0.1` and put a firewall rule in front — an exporter on `0.0.0.0` is a credential leak waiting to happen.
### Least-privilege monitoring user
Never reuse the application account, and never use root or a superuser.
```sql
-- PostgreSQL (9.6+)
CREATE ROLE pg_exporter LOGIN PASSWORD '...';
GRANT pg_monitor TO pg_exporter; -- read-only stats, no DML rights
-- MySQL
CREATE USER 'mysqld_exporter'@'127.0.0.1' IDENTIFIED BY '...';
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'mysqld_exporter'@'127.0.0.1';
FLUSH PRIVILEGES;
```
`pg_monitor` grants access to the statistics views without DML rights; the MySQL grants give the exporter what it needs to read status, replication state, and performance_schema tables.
## PostgreSQL Golden Metrics Cheat Sheet
These are what postgres_exporter actually exports.
| Metric | PromQL | Warn / Crit |
|---|---|---|
| `pg_stat_database_numbackends` / `pg_settings_max_connections` | `pg_stat_database_numbackends{datname="app"} / pg_settings_max_connections` | >0.80 / >0.90 |
| `pg_stat_activity_count` | `sum(pg_stat_activity_count{state="idle in transaction"})` | sustained > 5 |
| `pg_stat_replication_replay_lag_seconds` | `pg_stat_replication_replay_lag_seconds` | > 30s, `for: 5m` |
| `pg_stat_statements_mean_exec_time_ms` | `topk(10, pg_stat_statements_mean_exec_time_ms)` | > 1000ms |
| `pg_lock_count` | `sum(pg_lock_count{locktype="relation",mode="AccessExclusiveLock"})` | > 0 sustained |
One trap worth naming: there is **no** `pg_replication_lag_seconds` metric. The exporter exposes the three lag fields from `pg_stat_replication` — `write_lag`, `flush_lag`, `replay_lag` — as `..._seconds` gauges. The number you want is `replay_lag`, the last transaction actually applied. Grep for a nonexistent name and you get an empty panel and no alarm.
## MySQL Golden Metrics Cheat Sheet
| Metric | PromQL | Warn / Crit |
|---|---|---|
| `mysql_global_status_threads_connected` / `mysql_global_variables_max_connections` | `mysql_global_status_threads_connected / mysql_global_variables_max_connections` | >0.80 / >0.90 |
| `mysql_global_status_threads_running` | `rate(mysql_global_status_threads_running[5m])` | gauge, not an alarm |
| `mysql_global_status_innodb_row_lock_waits` | `rate(mysql_global_status_innodb_row_lock_waits[5m])` | > 5/s sustained |
| `mysql_global_status_slow_queries` | `rate(mysql_global_status_slow_queries[5m])` | rising trend |
| `mysql_slave_status_seconds_behind_master` | `mysql_slave_status_seconds_behind_master` | > 30s, `for: 5m` |
The most common MySQL mistake: treating `Threads_connected` and `Threads_running` as interchangeable. `connected` is total open connections (idle + active) — your pool-exhaustion signal. `running` is connections executing a query this instant — your load gauge. Alert on the ratio; graph `running` but do not page on it.
## Four Failure Decision Trees
The centerpiece. Each tree: symptom → decision → command → threshold.
### 1. Connection Pool Exhaustion
Symptom: app logs "connection pool exhausted", latency up, CPU normal.
1. Check the ratio. `pg_stat_database_numbackends / pg_settings_max_connections` for PostgreSQL; `mysql_global_status_threads_connected / mysql_global_variables_max_connections` for MySQL. Warn > 0.80, critical > 0.90.
2. Ratio high but `Threads_running` / active queries low: the pool is full of **idle** connections. Look for a leak in the app (unclosed `Connection.close()`), not a query problem. Raise the app pool cap *and* find the leak.
3. Ratio high *and* active queries high: the database is overloaded. Check lock waits and slow queries first — the queries may be blocked, not slow.
4. Raise `max_connections` only as a stopgap, and only after knowing the memory cost: each connection holds working memory, and too many can OOM the server.
### 2. Locks and Deadlocks
Symptom: intermittent 5xx on a write endpoint; `ERROR: deadlock detected` (PostgreSQL) or `ERROR 1213` (MySQL) in logs.
1. Count lock waits. PostgreSQL: `sum(pg_lock_count{locktype="relation",mode="AccessExclusiveLock"})` sustained > 0. MySQL: `rate(mysql_global_status_innodb_row_lock_waits[5m])` > 5/s.
2. Find the holder. PostgreSQL: `SELECT pid, state, query, now() - state_change AS age FROM pg_stat_activity WHERE state = 'idle in transaction';` — `age` tells you how long it has been stuck.
3. Check if the blocker is an old transaction or a long query. MySQL: `SELECT * FROM performance_schema.data_lock_waits;` with `innodb_print_all_deadlocks=ON` to capture details.
4. Kill only after identifying the victim. `pg_terminate_backend(pid)` for the clearly abandoned idle-in-transaction session. Never kill by guesswork — a long query might be a legitimate report.
### 3. Replication Lag
Symptom: replica is behind, reads serve stale data.
1. Measure real lag: `pg_stat_replication_replay_lag_seconds` (PostgreSQL) or `mysql_slave_status_seconds_behind_master` (MySQL).
2. **Rule out clock skew first.** If the replica clock is off by 3 seconds, every `replay_lag` sample reads 3 seconds high. Run `chronyc tracking` or `ntpstat` on both hosts. Skew is a monitoring artifact — fix NTP before touching the database.
3. Clocks agree? Check for a long-running transaction on the primary. A transaction open for minutes blocks WAL replay on every replica and produces a lag spike with nothing to do with replica throughput. This is the most common false positive I see.
4. Lag real and sustained: measure the replica's disk IO and apply rate. Add `for: 5m` so a single sample never pages anyone.
### 4. Slow Queries
Symptom: p99 latency up, CPU modest, no pool pressure.
1. Turn on `pg_stat_statements` if not already. It needs `shared_preload_libraries = 'pg_stat_statements'` in `postgresql.conf` **plus a restart** — `CREATE EXTENSION` alone does nothing. Verify with `SHOW shared_preload_libraries;`.
2. Rank by mean time: `topk(10, pg_stat_statements_mean_exec_time_ms)`. Cross-reference with `calls` so a 1-call outlier does not dominate.
3. MySQL: `rate(mysql_global_status_slow_queries[5m])` for the trend, then `SELECT * FROM performance_schema.events_statements_summary_by_digest ORDER BY AVG_TIMER_WAIT DESC LIMIT 10;`.
4. For each suspect, check the plan. Missing index and bad join plan are the usual causes. Fix the query or add the index, then watch the metric for 24 hours before declaring victory.
## Five Real Incident Post-Mortems
Each is a production incident I worked, reduced to what the metrics showed and what fixed it.
1. **Idle-in-transaction lock pileup.** Symptom: writes stalled, reads fine. Metrics: connection ratio 0.91, `idle in transaction` count 6, CPU 15%. Root cause: a job opened a transaction, did work, and never committed before the connection returned to the pool. Fix: `pg_terminate_backend` the abandoned sessions, then make the job commit or roll back in a `finally`. Prevention: alert on `idle in transaction` > 5 for 5 minutes.
2. **Replication lag "outage" that was a clock.** Symptom: `replay_lag` paged at 8 minutes. Metrics: WAL apply rate normal, `chronyc tracking` showed the replica clock 8 minutes behind. Root cause: the replica lost NTP during a host migration. Fix: restart `chronyd`, wait for the offset to converge. Prevention: never alert on lag without `for: 5m`, and graph clock offset next to lag.
3. **Connection pool exhausted by a health check.** Symptom: app could not get connections; ratio 0.97. Metrics: `Threads_connected` high, `Threads_running` low. Root cause: a misconfigured load-balancer health check opened a fresh connection every probe and never closed it. Fix: point the health check at the LB's TCP check instead of a DB query. Prevention: alert on the connected/max ratio, not on running.
4. **Deadlocks that were actually a missing index.** Symptom: `ERROR 1213` every few minutes. Metrics: row-lock-wait rate spiked to 40/s. Root cause: two code paths updating the same table in opposite row order, with a missing index widening the lock window. Fix: add the index and reorder the updates consistently. Prevention: alert on row-lock-wait rate, review `innodb_print_all_deadlocks` output.
5. **Slow query the plan said was fine.** Symptom: p99 latency 3s, CPU 20%. Metrics: `pg_stat_statements_mean_exec_time_ms` showed one query at 2500ms. Root cause: stale statistics after a bulk load made the planner guess a tiny row count and pick a nested loop. Fix: `ANALYZE ;` refreshed the stats; the plan flipped to a hash join. Prevention: `ANALYZE` after large bulk loads, alert on rising `mean_exec_time` for top digests.
## Production Alert Rules
Copy-paste Prometheus rules. The `# pitfall:` comments are the ones that cost me a pager battery.
```yaml
# /etc/prometheus/rules/database.yml
groups:
- name: database
rules:
# pitfall: MySQL has no deadlock counter. This row-lock wait rate is the closest real signal.
- alert: MySQLLockWaitHigh
expr: rate(mysql_global_status_innodb_row_lock_waits[5m]) > 5
for: 5m
labels: { severity: critical }
annotations: { summary: "InnoDB row-lock waits sustained", description: "rate = {{ $value }}/s" }
# pitfall: always set for: 5m on lag. A single clock-skew or jitter sample is not an outage.
- alert: PostgresReplicaLag
expr: pg_stat_replication_replay_lag_seconds > 30
for: 5m
labels: { severity: warning }
annotations: { summary: "PostgreSQL replica lag", description: "replay_lag = {{ $value }}s" }
- alert: MySqlReplicaLag
expr: mysql_slave_status_seconds_behind_master > 30
for: 5m
labels: { severity: warning }
annotations: { summary: "MySQL replica lag", description: "seconds_behind_master = {{ $value }}s" }
# pitfall: pg_stat_statements needs shared_preload_libraries AND a restart. An empty panel
# means check SHOW shared_preload_libraries; before assuming the exporter is broken.
- alert: PostgresSlowQueries
expr: pg_stat_statements_mean_exec_time_ms > 1000
for: 5m
labels: { severity: warning }
annotations: { summary: "Slow query detected", description: "mean exec = {{ $value }}ms" }
- alert: PostgresConnPool
expr: pg_stat_database_numbackends / pg_settings_max_connections > 0.90
for: 5m
labels: { severity: critical }
annotations: { summary: "Connection pool critical", description: "ratio = {{ $value }}" }
# pitfall: never alert on Threads_running alone; it is a load gauge, not a saturation alarm.
- alert: MysqlConnPool
expr: mysql_global_status_threads_connected / mysql_global_variables_max_connections > 0.90
for: 5m
labels: { severity: critical }
annotations: { summary: "MySQL connection pool critical", description: "ratio = {{ $value }}" }
```
For routing see [Prometheus Alerting & Alertmanager](prometheus-alerting.md); for the dashboards these feed, [Grafana Dashboard](grafana-dashboard.md).
## Related Articles
- [Prometheus Deploy](prometheus-deploy.md) — baseline stack before adding any exporter
- [Prometheus Query](prometheus-query.md) — PromQL recipes for the dashboards above
- [Prometheus Alerting & Alertmanager](prometheus-alerting.md) — routing and notification for the rules above
- [Grafana Dashboard](grafana-dashboard.md) — turning these metrics into views
- [Linux Disk IO Monitor](linux-disk-io-monitor.md) — the host side of the IO-wait story
---
## DevSecOps Security Left-Shift: CI/CD Scanning Strategy from SAST/SCA/DAST to Supply Chain
URL: https://ops.jiunotes.top/en/monitor/devsecops-security.md
摘要: A hands-on DevSecOps playbook: integrating SAST, SCA and DAST into CI/CD, scanning container images, detecting leaked secrets, handling policy bypasses, and choosing between blocking the pipeline versus notifying on findings.
### Answer
DevSecOps is security left-shift: moving checks into the pipeline instead of auditing at the door. I rebuilt our CI/CD after two incidents — a hardcoded AWS key pushed to a public repo, and a log4j CVE still running in production. The model is three layers: SAST at the commit stage, SCA at the dependency stage, DAST after deployment. The pivotal decision is whether a finding blocks the pipeline or merely notifies. My policy: SCA critical blocks, SAST warning-level does not, DAST always blocks, and leaked secrets are zero-tolerance. The payoff was MTTR dropping from four hours to thirty minutes.
### FAQ
Q: What is the difference between SAST and DAST, and when do I use each?
A: SAST analyzes source code before compile and finds logic flaws like SQL injection or hardcoded secrets. DAST tests a running deployment and finds runtime issues like XSS or CSRF. SAST has higher false positives but covers earlier; DAST is more accurate but only sees what is deployed. My workflow: SAST plus SCA in the pull request, DAST in staging.
Q: Should I pick Trivy, Snyk, or something else?
A: Depends on budget. Trivy is free and covers images, code and config, which fits a small team. Snyk is the most complete but paid, for larger budgets. Grype is a lightweight image-only scanner. My stack is Trivy for images plus Semgrep for code, all free.
Q: Security scanning keeps blocking the dev flow. What do I do?
A: This is the central tension in DevSecOps. The fixes that work for me: separate blocking findings from advisory findings and only block on high severity; give developers a one-click remediation (auto dependency upgrade); run a periodic security-debt cleanup so findings do not accumulate; and let security and dev teams jointly define severity rather than security deciding alone.
Q: How do I defend against supply-chain attacks?
A: Three layers work for me. Pin exact dependency versions instead of using ranges, so a poisoned version cannot silently slip in. Generate an SBOM on every build so a known CVE like log4j can be traced to affected services in minutes. And verify image signatures with cosign so a tampered image never reaches production. The combination turns an unknown compromise into a fast, localizable event.
### Full Content
# DevSecOps Security Left-Shift: CI/CD Scanning Strategy
Two incidents forced this change on me. First, a developer hardcoded an AWS key into source and pushed it to a public repository. Second, a production service was still running an old dependency with a known log4j CVE. In both cases the security check existed only at the final gate, which is one place too late. I rebuilt the pipeline with three scan layers and the results were stark: MTTR for security incidents dropped from four hours to thirty minutes, and the high-severity finding rate fell by 80%.
This is the complete integration strategy, including the parts that went wrong.
## The Three-Layer Scan Model
```
Dev stage Build stage Deploy stage
│ │ │
▼ ▼ ▼
┌────────┐ ┌───────────┐ ┌───────────┐
│ SAST │ │ SCA │ │ DAST │
│ (code) │ │ (deps) │ │ (runtime) │
└────────┘ └───────────┘ └───────────┘
│ │ │
▼ ▼ ▼
PR stage Build stage Staging stage
(block high) (block high) (block high)
```
### SAST: Static Application Security Testing
SAST analyzes source for logic flaws before the code is committed.
```yaml
# .github/workflows/sast.yml
name: SAST Scan
on: [pull_request]
jobs:
semgrep:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: returntocorp/semgrep-action@v1
with:
config: 'p/default'
severity: 'error'
fail_on_exit: true # high-severity blocks the pipeline
args: '--json --output=semgrep.json'
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: semgrep.json
```
**Semgrep vs Bandit vs GoSec:**
- **Semgrep**: multi-language, custom rules, low false positives — my first choice.
- **Bandit**: [Python](https://docs.python.org/)-specific, simple.
- **GoSec**: Go-specific, a must for Go projects.
**The pit I hit:** `p/default` rule set is broad but can miss high-severity rules relevant to your stack. I now add team-specific rules:
```yaml
# semgrep.yaml
rules:
- id: hard-coded-secret
patterns:
- pattern: $PASSWORD = "$$";
- pattern: api_key: "$$"
message: "Hardcoded secrets are not allowed in code"
severity: ERROR
languages: [python, go, java]
```
### SCA: Software Composition Analysis
SCA scans the dependency tree for known CVEs.
```yaml
# Trivy image scan
- name: Trivy Image Scan
uses: aquasecurity/trivy-action@master
with:
image-ref: 'myregistry/my-app:latest'
format: 'sarif'
output: 'trivy-results.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1' # high severity blocks the pipeline
# Trivy dependency scan (Go modules)
- name: Trivy Dependency Scan
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
scan-ref: '.'
format: 'sarif'
output: 'trivy-deps.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1'
```
**Trivy vs Snyk vs Grype:**
- **Trivy**: free, comprehensive (images + code + config), OCI-compatible — my production default.
- **Snyk**: most complete but paid, great IDE plugin.
- **Grype**: image-only, light and fast.
**My experience:** Trivy is fast (a Go image scans in about 30 seconds) but its rule DB lags. When log4j broke, Trivy took six hours to publish the rule. I run Snyk in parallel as a fast-updating supplement.
### DAST: Dynamic Application Security Testing
DAST tests a running service after deployment.
```yaml
# OWASP ZAP baseline scan
- name: OWASP ZAP Scan
uses: zaproxy/action-baseline@v0.10.0
with:
target: 'http://staging.example.com'
rules_file_name: '.zap/rules.tsv'
cmd_options: '-a'
fail_action: true
allow_issue_writing: false
```
**ZAP vs Burp Suite vs Nessus:**
- **ZAP**: free, open source, excellent CI integration — my automation first choice.
- **Burp Suite**: most powerful but paid, for manual penetration work.
- **Nessus**: infrastructure vulnerability scanner, not application layer.
**DAST limitation:** it only tests deployed services and cannot find logic flaws that need a specific input vector. Its real value is catching configuration errors and runtime issues.
## Secret Detection: The First Line of Defense
```yaml
# GitLeaks secret detection
- name: GitLeaks Scan
uses: gitleaks/gitleaks-action@v2
env:
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
# or use Trivy's secret scanner
- name: Trivy Secret Scan
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
scan-ref: '.'
severity: 'CRITICAL,HIGH'
format: 'sarif'
output: 'trivy-secret.sarif'
```
GitLeaks' default rules cover 200+ secret formats (AWS, GCP, Azure, GitHub tokens, JWT, SSH keys), which is enough for most cases. Internal formats need a custom rule:
```toml
# .gitleaks.toml
[[rules]]
id = "internal-api-key"
description = "Internal API Key"
regex = '^IAK_[a-zA-Z0-9]{20,}$'
severity = "CRITICAL"
```
## The Pivotal Decision: Block vs Notify
This is the heart of DevSecOps — **when a scan finds something, do you stop the pipeline?**
| Scan type | Suggested policy | Why |
|---|---|---|
| SAST high (SQL injection, RCE) | **Block** | Directly exploitable |
| SAST medium (info leak) | **Notify** | Needs human assessment |
| SCA high (known CVE) | **Block** | Known exploit exists |
| SCA low (info leak) | **Notify** | Depends on the dependency chain |
| Secret leak | **Block** | Zero tolerance |
| DAST high | **Block** | Runtime vulnerability |
| Base image vulnerability | **Notify + upgrade** | Not dev-controllable |
**My practice:**
- PR stage: SAST + SCA + secret detection → **block on high**.
- Build stage: image scan → **block on high**.
- Staging stage: DAST → **block on everything**.
- Weekly: all findings summarized → **notify security team**.
```yaml
# tiered blocking policy
- name: Check Security Results
if: always()
run: |
critical=$(jq '[.results[] | select(.Severity=="CRITICAL")] | length' trivy-results.sarif)
high=$(jq '[.results[] | select(.Severity=="HIGH")] | length' trivy-results.sarif)
if [ "$critical" -gt 0 ]; then
echo "::error::Critical vulnerabilities found: $critical"
exit 1
fi
if [ "$high" -gt 0 ]; then
echo "::warning::High vulnerabilities found: $high (will notify security team)"
fi
```
## Handling a Policy Bypass
Sooner or later a developer needs to ship something with a known finding. The worst thing I did was ignore this reality and let the team "fix" it by commenting out the scan. The right way is a controlled bypass with an expiry:
```yaml
# .semgrepignore with a review trail
# only allow a bypass with a ticket and a date
- id: semgrep-123
reason: "ticket SEC-4567, temporary auth bypass, expires 2026-11-15"
expires: 2026-11-15
```
The rules I enforce:
- Every bypass references a ticket and has an expiration date.
- No bypass survives its expiry; an expired bypass re-blocks the pipeline.
- The security team reviews the bypass list monthly and calls out anything stale.
## Scanning Performance: The Layered Pipeline
Security scanning has a real cost in pipeline latency, and the naive fix — running everything on every commit — is how you get the pipeline blocked by the security team you are trying to help. My pipeline splits scanning by speed. The PR stage runs only the fast, high-value checks: secret detection and light SAST, both under thirty seconds. The nightly build runs the expensive full pass: complete SAST plus DAST against staging, ten to thirty minutes. The build stage runs incremental scans on changed files only. The result is that a developer's PR rarely waits more than a few extra minutes, while the deep scans still happen every night.
## Supply Chain: The Blind Spot Nobody Watches
**Supply-chain attacks are the dominant security story of the last two years** — poisoned npm packages, stolen CI tokens, compromised build environments.
### Defenses
```yaml
# 1. Pin dependency versions (never use latest)
# package.json
"dependencies": {
"express": "4.18.2", # exact version, not ^4.18.2
"lodash": "4.17.21"
}
# 2. Verify dependency integrity
- name: Verify Dependencies
run: |
npm audit --production --audit-level=high
go list -m all | xargs go vet
# 3. Verify image signature (cosign)
- name: Verify Image Signature
run: |
cosign verify --key https://example.com/key.pub \
myregistry/my-app:latest
# 4. Generate an SBOM (SPDX format)
- name: Generate SBOM
uses: anchore/sbom-action@v0
with:
path: .
format: spdx-json
output-file: sbom.spdx.json
```
**SBOM (Software Bill of Materials)** is the supply-chain foundation. It records every dependency and version in your software, so when a CVE like log4j hits, you can find affected services in minutes instead of days.
```yaml
# GitHub Actions auto-generates an SBOM on every build
- uses: anchore/sbom-action@v0
with:
path: .
format: spdx-json
```
## Managing Security Debt
The goal is not zero findings; it is a controlled backlog that never grows.
```yaml
# weekly security report to security and dev leads
name: Weekly Security Report
on:
schedule:
- cron: '0 9 * * 1' # Monday 09:00
jobs:
security-report:
runs-on: ubuntu-latest
steps:
- name: Collect Vulnerabilities
run: |
gh api repos/${{ github.repository }}/security-advisories \
--jq '.[] | select(.severity=="high")'
- name: Send Report
run: |
curl -X POST ${{ secrets.SLACK_WEBHOOK }} \
-d '{"text":"Weekly Security Report: ${{ steps.collect.outputs.vulns }} critical vulnerabilities"}'
```
I track each finding as a ticket with a hard SLA:
- Critical: fix within 24 hours.
- High: fix within 72 hours.
- Medium: fix within 7 days.
- Low: next iteration.
## FAQ
### Q: Scanning is slowing down CI/CD. How do I fix it?
Layer it:
1. Fast scans in the PR (secret detection, light SAST, under 30 seconds).
2. Full scans in the nightly build (full SAST, DAST, 10-30 minutes).
3. Incremental scans in the build stage (only changed files).
My experience: moving the full scan to nightly added only three minutes to the PR CI time (15 to 18 minutes), which is acceptable.
### Q: Developers complain security blocks their work. What changed things?
1. Tell them *why*, not just "Build Failed" — give the specific finding and a fix suggestion.
2. Offer one-click remediation (auto dependency upgrade, auto secret rotation).
3. Give them a local sandbox to run scans before pushing.
4. Regular training so they understand *why* the vulnerability matters, not just that their PR was rejected.
### Q: False positives are drowning the team. What do I do?
```yaml
# build a false-positive exemption list
- name: Suppress False Positives
run: |
echo '{"ignore":[{"id":"semgrep-123","reason":"confirmed false positive: test code"}]}' \
> .semgrepignore
```
The key principle: **you do not eliminate false positives, you manage them.** Build a shared false-positive knowledge base so the whole team sees which findings are already confirmed as noise, instead of re-judging each one.
## Related Articles
- [Bastion Host Selection and JumpServer Deployment](bastion-jumpserver.md)
- [SSH Hardening: Key-Based Authentication and Fail2ban](ssh-hardening.md)
- [Blackbox Exporter Probe Configuration for SLO Design](blackbox-exporter.md)
---
## Distributed Tracing Sampling: Keep the Errors, Cut the Bill
URL: https://ops.jiunotes.top/en/monitor/distributed-tracing-span-sampling.md
摘要: How to sample distributed tracing without losing the traces that matter. Covers head-based vs tail-based sampling, probabilistic / rate-limited / adaptive / parent-based strategies, an OpenTelemetry Collector tail_sampling processor config, the memory-versus-fidelity tradeoff, and a post-launch inspection routine.
### Answer
Sampling splits into head-based (decide at span creation) and tail-based (decide after the whole trace completes). High-traffic systems use tail sampling to keep error and slow traces, and a probability plus rate limit to cap the volume. An OpenTelemetry Collector tail_sampling processor decides on latency, error and frequency, with a wait window and a trace buffer to avoid dropping what you need.
### FAQ
Q: What is the real difference between head-based and tail-based sampling, and why does everyone push tail-based?
A: Head-based sampling decides at the moment a span is created, so it is simple, zero-delay and uses no buffer, but it decides without seeing the outcome, so a trace that ends in an error can be discarded at the sample point. Tail-based sampling collects the spans until the request finishes (or longer) and then decides on the final result, so it keeps genuinely valuable error traces. The cost is buffering spans, memory and a little decision latency. High-value, high-traffic systems lean tail-based; low-traffic or edge collectors are better off head-based.
Q: How long should tail sampling wait before deciding? Will a short wait drop slow requests?
A: The key parameter is the wait window, the OTel `decision_wait`. It is how long the Collector waits for the whole trace after the first span before deciding. Too short and a long cross-service trace is forced to decide before it has all arrived, so a slow request is judged "normal" and dropped. Too long and buffered spans pile up in memory. Start at 2 seconds, move to 5-10 seconds for multi-service or long-transaction systems, and pair it with a `num_traces` cap so memory cannot blow. This is a memory-versus-fidelity tradeoff; tune it against your real trace length.
Q: What probability should I set, and will it sample away rare errors?
A: A pure probability sample such as 1% is cheap on steady traffic, but a rare error trace has a real chance of being dropped entirely, and those are exactly the ones you most need to see. The correct move is to layer rules inside tail sampling: force 100% retention for error traces and high-latency traces above a threshold, and only run probability on ordinary successful traces. The overall rate may sit at a few percent while error traces are almost never lost. You can also bucket by service importance, high sampling on a core payment path and low on health checks.
Q: What does parent-based sampling mean, and when should I use it?
A: Parent-based sampling is a follow-the-upstream strategy: if the upstream decided to keep the trace, downstream services keep it too, so a trace is either whole or absent rather than a broken fragment with a parent missing and a lone child span. It pairs naturally with head-based sampling, and in microservices it is effectively mandatory; without it the trace graph fragments into pieces that never join up.
Q: After sampling, how do I confirm I have not sampled away a critical error?
A: Three checks. First, make error and high-latency traces forced-retained in the tail rules and count the hits on those two rules separately, watching their rates. Second, route a few core businesses such as payment and login through a dedicated 100% sample channel that never depends on the generic sampler. Third, periodically trigger a known failure and verify the complete trace is discoverable in the backend. Do not trust the overall sampling number; watch the discoverability rate of critical traces.
### Full Content
# Distributed Tracing Sampling: Keep the Errors, Cut the Bill
The moment distributed tracing is fully rolled out, the first thing that hurts is not the integration effort, it is the cost. Every request generates dozens or even hundreds of spans, and sending them all to a backend means storage and egress bills that climb month over month. Worse, the overwhelming majority of those spans are the normal path of healthy requests, and you do not need all of them. Sampling answers one question: out of a flood of spans, which ones do I keep so that I can still see the system clearly without the invoice crushing me.
But sampling has two fears. The first is that you sample away a rare error trace, so when something breaks, the trace you need is nowhere in the system. The second is that you sample in fragments, a parent kept and a child dropped, so the graph never assembles. This article explains head-based and tail-based sampling and the common strategies, then gives principles you can apply directly.
## 1. Why you must sample instead of keeping everything
Run the numbers first. A medium-traffic service at 2000 QPS, 30 spans per request on average, is about 5.2 billion spans a day. Storing all of it is terabytes, and queries get slow. More than 95% of it is normal, repetitive, and worthless for analysis. The real purpose of tracing is to locate a problem when something goes wrong, not to build a file on every healthy request.
So the industry consensus is clear: for a high-traffic system, sampling is not optional, it is mandatory. The hard part is doing it smart, pushing the rate down to a single-digit percentage while keeping error, slow and unusual traces almost never lost.
## 2. Head-based sampling: decide at the start
Head-based sampling decides at the moment the span is created whether to keep the trace, usually by a coin flip (probability) or a fixed rule. The benefits are direct:
- No buffer, no extra memory, the decision is immediate.
- No decision latency, so it is friendly to latency-sensitive services.
- Simple to implement, one `sampler` setting in the SDK.
The drawback is just as clear: it never sees the ending. A trace that ends in a 500 error can be dropped by the probability at the sample point, and a slow trace that spans ten services cannot be predicted as slow from the start. So head-based sampling fits low-traffic flows, or cases where you care about whether something exists rather than exactly which one failed.
## 3. Tail-based sampling: decide after the whole run
Tail-based sampling works the other way: collect the spans of a trace, wait until the request finishes (or longer, depending on config), then decide on the final behaviour. It can decide on these signals:
- Did this trace end in an error (HTTP 5xx, gRPC error, exception)?
- Did it exceed a latency threshold (outside P99)?
- Is it a rare path (low-frequency endpoint, a specific user)?
- Did it trigger a custom business rule (for example amount above a value)?
So you can keep every error and slow trace and sample ordinary ones by ratio, preserving maximum value at a very low overall rate. The cost is a component that buffers spans, uses memory and adds a little decision latency. The OpenTelemetry Collector `tail_sampling` processor does exactly this.
## 4. The sampling strategies, broken down
No single strategy is enough; production is a combination:
- **Probabilistic**: keep each trace at a fixed ratio such as 1%. Simple, fine on steady traffic, but it randomly drops rare errors.
- **Rate-limited**: keep at most N traces per second, drop the rest. Very effective at capping the total, good against bursts.
- **Adaptive**: adjust the rate dynamically from current traffic and error rate, raising it when errors climb. Needs extra implementation or platform support.
- **Parent-based**: downstream follows the upstream sampling decision, preserving trace integrity.
- **Attribute-based**: different rates by service name, endpoint or user tag, high for core business and low for side paths.
Production is usually tail sampling plus forced retention of errors and slow traces, plus probability or rate limit on the rest.
## 5. OpenTelemetry Collector tail sampling config
Here is the skeleton of a `tail_sampling` processor. The logic is: check error first, then slowness, and retain those at 100%; otherwise run probability to hold the total down:
```
processors:
tail_sampling:
decision_wait: 10s
num_traces: 50000
policies:
- name: errors
type: status_code
status_code:
status_codes: [ERROR]
- name: slow
type: latency
latency:
threshold_ms: 500
- name: probabilistic
type: probabilistic
probabilistic:
sampling_percentage: 5
```
Order matters: an earlier policy that hits keeps the trace, and only traces that miss everything fall through to the probability policy. Pair it with a `batch` processor and an exporter. With this config, error and slow traces are almost never lost and the overall rate sits around 5%, cutting the cost by more than ninety percent.
## 6. The memory-versus-fidelity tradeoff
The Achilles heel of tail sampling is memory. It buffers spans in the Collector before deciding, so two parameters need attention:
- `decision_wait`: too long and memory piles up and latency grows; too short and a long trace is forced to decide before it has arrived, dropping a slow request by mistake. Start at 2 seconds, move to 5-10 seconds for multi-service systems.
- `num_traces`: the cap on concurrently buffered traces, to stop memory blowing. Over the cap triggers eviction and may drop traces still waiting.
The rule of thumb: the longer and more multi-service your traces, the larger `decision_wait`; the smaller the Collector memory, the tighter `num_traces`. After launch, watch Collector memory and the count of traces evicted before decision, the two metrics that matter most for tail sampling.
## 7. Parent-based sampling keeps traces whole
If every service in a microservice system flips its own coin, you get broken traces, a parent not sampled and a child sampled, so the graph is full of gaps. Parent-based sampling makes downstream follow upstream: if upstream says keep, downstream keeps too; if upstream says drop, downstream drops. It is on by default in OpenTelemetry and matters most when combined with head-based sampling. Do not switch it off for finer granularity, or you get fragments that never assemble.
## 8. Verifying you did not lose critical traces
A good sampling number does not mean nothing was lost. Run three checks:
- Monitor the hit rate of each tail policy, especially `errors` and `slow`, to confirm error traces really enter the retention pool.
- Route core businesses such as payment and login through a dedicated 100% sample channel, independent of the generic sampler, so that part is always discoverable.
- Periodically use a known fault as a probe: deliberately trigger an error and confirm the complete trace is findable in the backend.
Watch the discoverability rate of critical traces as an SLO rather than the overall sampling rate.
## 9. Post-launch discipline against silent decay
Sampling config quietly degrades too: one Collector config rollback can turn tail sampling back into head-based, and one memory limit can shrink `num_traces` and start dropping traces. Keep a routine:
- **Weekly**: look at the hit-rate trend of each tail policy; the error retention rate should sit stably near 100%. A sharp drop means a rule was changed.
- **Weekly**: check Collector memory and evicted-before-decision count; persistently high memory means `decision_wait` or `num_traces` needs adjusting or the Collector needs scaling.
- **Before any change**: validate the sampled rate on a known error trace in staging, then roll out; re-check immediately after.
- **A hard rule I hold**: never include error traces in a probability sample to save money. Error and slow traces are forced-retained; that is the non-negotiable floor of any sampling config.
- **Every service you add**: the new service should inherit the unified sampling policy by default, so no service runs unbounded full-reporting and quietly raises the bill.
## FAQ
What is the real difference between head-based and tail-based sampling, and why does everyone push tail-based?
Head-based sampling decides at the moment a span is created, so it is simple, zero-delay and uses no buffer, but it decides without seeing the outcome, so a trace that ends in an error can be discarded at the sample point. Tail-based sampling collects the spans until the request finishes (or longer) and then decides on the final result, so it keeps genuinely valuable error traces. The cost is buffering spans, memory and a little decision latency. High-value, high-traffic systems lean tail-based; low-traffic or edge collectors are better off head-based.
How long should tail sampling wait before deciding? Will a short wait drop slow requests?
The key parameter is the wait window, the OTel decision_wait. It is how long the Collector waits for the whole trace after the first span before deciding. Too short and a long cross-service trace is forced to decide before it has all arrived, so a slow request is judged normal and dropped. Too long and buffered spans pile up in memory. Start at 2 seconds, move to 5-10 seconds for multi-service or long-transaction systems, and pair it with a num_traces cap so memory cannot blow. This is a memory-versus-fidelity tradeoff; tune it against your real trace length.
What probability should I set, and will it sample away rare errors?
A pure probability sample such as 1% is cheap on steady traffic, but a rare error trace has a real chance of being dropped entirely, and those are exactly the ones you most need to see. The correct move is to layer rules inside tail sampling: force 100% retention for error traces and high-latency traces above a threshold, and only run probability on ordinary successful traces. The overall rate may sit at a few percent while error traces are almost never lost. You can also bucket by service importance, high sampling on a core payment path and low on health checks.
What does parent-based sampling mean, and when should I use it?
Parent-based sampling is a follow-the-upstream strategy: if the upstream decided to keep the trace, downstream services keep it too, so a trace is either whole or absent rather than a broken fragment with a parent missing and a lone child span. It pairs naturally with head-based sampling, and in microservices it is effectively mandatory; without it the trace graph fragments into pieces that never join up.
After sampling, how do I confirm I have not sampled away a critical error?
Three checks. First, make error and high-latency traces forced-retained in the tail rules and count the hits on those two rules separately, watching their rates. Second, route a few core businesses such as payment and login through a dedicated 100% sample channel that never depends on the generic sampler. Third, periodically trigger a known failure and verify the complete trace is discoverable in the backend. Do not trust the overall sampling number; watch the discoverability rate of critical traces.
## Related Articles
- [OpenTelemetry: From SDK to Collector, a Practical Guide](opentelemetry-guide.md)
- [Continuous Profiling: Wiring Flame Graphs into Observability](continuous-profiling.md)
- [eBPF Observability: Kernel-Level Collection Without App Changes](ebpf-observability.md)
---
## eBPF Observability Principles: Non-Invasive Monitoring from Kernel Traces to Production
URL: https://ops.jiunotes.top/en/monitor/ebpf-observability.md
摘要: eBPF principles and practice: the three attach methods (kprobe, uprobe, tracepoint via ftrace), real performance cost, production pitfalls around kernel version, permissions and missing BTF, and three real incident postmortems.
### Answer
eBPF lets you run sandboxed user-space programs inside the Linux kernel, collecting metrics with zero instrumentation and low overhead. The three attach points I use are kprobe for kernel functions, uprobe for user-space functions, and tracepoint for the kernel's pre-defined stable hooks. The tool chain runs from bpftrace one-liners for diagnosis to Cilium Hubble for production Kubernetes network observability. The real cost is not zero: high-frequency tracepoints burn CPU, so I always aggregate into maps instead of printing per event. My biggest pitfall was assuming BTF was present on a custom cloud kernel — it was not, and kprobes failed to load.
### FAQ
Q: How is eBPF different from strace or ltrace?
A: strace is syscall-level tracing with huge overhead, unsuitable for production. eBPF runs a small compiled program inside the kernel, with an order of magnitude less overhead, and it can run persistently and report metrics live rather than as a post-hoc replay. strace tells you what happened after the fact; eBPF tells you what is happening right now.
Q: What privileges does eBPF need, and does it work in a container?
A: Loading an eBPF program requires CAP_SYS_ADMIN, which a normal container does not have. Options: run a privileged container (higher security risk), grant SYS_ADMIN/BPF/PERFMON with seccomp unconfined, or use a tool like Cilium that loads programs through a whitelist. My production advice is to run eBPF on the node itself, not inside the app container.
Q: Is writing eBPF programs hard? Are there ready-made tools?
A: Writing C and compiling is the most flexible but has the steepest learning curve. For daily work, BCC's Python scripts (tcplife, execsnoop) or a single bpftrace line is enough. For production, Telegraf's eBPF plugin or Cilium Hubble works out of the box.
Q: Should I pick kprobe or tracepoint, and which is more stable?
A: The first time I attached a kprobe to `do_mkdir`, a kernel upgrade renamed it to `vfs_mkdir` and my script broke. A tracepoint is a pre-defined kernel hook whose interface does not change when the internals change, so it is far more stable. My rule: prefer tracepoint whenever it covers the case, and only fall back to kprobe when I need a specific kernel function's arguments.
### Full Content
# eBPF Observability Principles: Non-Invasive Monitoring from Kernel Traces to Production
Last year, adding observability to a production [Kubernetes](https://kubernetes.io/docs/) cluster, I hit a strange problem: a Java service was stalling with GC pauses over 500ms. [Prometheus](https://prometheus.io/docs/) showed nothing abnormal, and [Grafana](https://grafana.com/docs/) had no root cause. It was only when I ran the eBPF `funcslower` tool that I saw it — a JNI call was blocking the JVM thread, and no standard GC metric covered that path.
The conventional route would have been an APM install, code changes, and a restart. eBPF needed none of that. **Zero instrumentation, no redeploy, no code change** — the kernel told me directly what was happening.
## eBPF in One Sentence
eBPF (extended Berkeley Packet Filter) began as a way to filter network packets in the kernel. It evolved into a framework for safely executing small user-written programs inside kernel context.
**The core idea:** run a "safe sandbox" in the [Linux](https://www.kernel.org/doc/html/latest/) kernel. A user-space program produces BPF bytecode, the verifier checks it for safety, and only then is it attached to a hook point.
```
user-space program (BPF bytecode)
↓ verifier checks safety
kernel context (attached to hook)
↓ produces data
ring buffer / perf event / map
↓ read from user space
monitoring tool (BCC / bpftrace / custom agent)
```
**The verifier is the heart of it.** It guarantees your program cannot loop forever, cannot touch unauthorized kernel memory, and cannot crash the kernel. If the verifier rejects the program, it simply does not load.
## Three Attach Methods: kprobe / uprobe / tracepoint
These are the three doors into the kernel. Which one you pick determines what you can see.
### kprobe: Kernel Function Level
Attaches at the entry or exit of a kernel function, letting you observe any kernel function call.
```bash
# bpftrace one-liner: latency distribution of mkdir syscalls
bpftrace -e 'kprobe:do_mkdir { @start[tid] = nsecs; }
kretprobe:do_mkdir /@start[tid]/ {
@latency = lshift(nsecs - @start[tid], 0);
delete(@start[tid]);
}'
# sample output
# @latency:
# [1000, 2000) 3
# [2000, 4000) 15
# [4000, 8000) 8
```
**kprobe limitation:** kernel symbols can be renamed across versions, so compatibility is poor. `do_mkdir` became `vfs_mkdir` in 5.15+, and scripts must follow.
### uprobe: User-Space Function Level
Attaches to a function in a user process, letting you observe application internals.
```bash
# attach to a Java process function (needs the PID)
bpftrace -e 'uprobe:/usr/bin/java:_ZNK6google7protobuf7Message10InitializationErrorStringEv {
printf("Java function called by pid %d\n", pid);
}'
# measure execution time of a [Python](https://docs.python.org/) function
bpftrace -e 'uprobe:/usr/bin/python3.11:main { @start[pid] = nsecs; }
uretprobe:/usr/bin/python3.11:main /@start[pid]/ {
printf("python3 pid %d took %lld ns\n", pid, nsecs - @start[pid]);
delete(@start[pid]);
}'
```
**uprobe limitation:** you need the target binary path, and symbols may be stripped. I use `readelf` or `nm` first to confirm the symbol exists.
### tracepoint: Pre-Defined Kernel Events
Tracepoints are hooks the kernel defines in advance. They are more stable than kprobes because they do not break when internal implementation changes. They sit on the ftrace infrastructure.
```bash
# list all network-related tracepoints
sudo bpftrace -l 'tracepoint:*net*' | head -20
# trace TCP connection establishment
sudo bpftrace -e 'tracepoint:syscalls:sys_exit_connect {
@estab[tid] = args->err;
}'
```
**The decision tree I use:**
- Want syscalls → `tracepoint:syscalls` first, fall back to kprobe.
- Want kernel functions → kprobe.
- Want user-space functions → uprobe.
- Unsure → run `bpftrace -l` to list available tracepoints, then decide.
## The Production Tool Chain
### BCC: Ready-Made Python Scripts
BCC ships dozens of monitoring scripts, the fastest on-ramp to eBPF.
```bash
# install BCC on Ubuntu 22.04
sudo apt install bpfcc-tools linux-headers-$(uname -r)
# list every available script
bcu list | head -30
# classic: tcplife — TCP connection lifetime and bytes
sudo tcplife -l
# classic: execsnoop — trace new process launches
sudo execsnoop -T
# classic: biosnoop — block device I/O latency
sudo biosnoop -T
```
**My take:** BCC scripts are great for quick diagnosis, but I would not run them as a production monitoring system. They are debugging tools, not monitoring. For production use Telegraf or a custom agent.
### bpftrace: The One-Line Swiss Army Knife
bpftrace syntax is like awk plus C. The learning curve is steeper than BCC, but the flexibility is much higher.
```bash
# install
sudo apt install bpftrace
# file path distribution of open syscalls
sudo bpftrace -e 'tracepoint:syscalls:sys_exit_openat {
printf("%s %s\n", comm, str(args->filename));
}'
# TCP retransmission — the network-problem hero
sudo bpftrace -e 'kprobe:tcp_retransmit_skb {
@retrans[key(arg0, arg0->sk)] = count();
}'
```
**Practical note:** `bpftrace -e 'hist(args->size)'` plots a histogram of open-syscall argument sizes. That is how I once found a large-file copy causing a disk I/O spike.
### Telegraf with eBPF: Production Grade
Telegraf has an official eBPF plugin that collects system metrics out of the box.
```toml
# telegraf.conf
[[outputs.prometheus_client]]
listen = ":9273"
[[inputs.ebpf]]
programs = [
{ name = "syscall", paths = ["tracepoint:syscalls:sys_exit_read", "tracepoint:syscalls:sys_exit_write"] },
{ name = "network", paths = ["tracepoint:net:net_dev_rx"] },
]
```
```bash
telegraf --config telegraf.conf --test
```
**My advice:** the Telegraf eBPF plugin fits basic metrics (syscall counts, network stats), but complex cases like tracing a specific application's call chain still need bpftrace.
### Cilium Hubble: The Ceiling of Kubernetes Network Observability
Cilium ships Hubble, which uses eBPF for complete Kubernetes network observability — traffic matrices, DNS queries, connection states — with no business code changes.
```bash
# watch Hubble topology
hubble observe --follow
# watch DNS queries
hubble observe --type dns
# watch connection state changes
hubble events --type connection
```
**Hubble's core value:** you see north-south and east-west traffic in Kubernetes without a service mesh, without sidecars, purely from eBPF. If your cluster runs Cilium, Hubble is a must-install component.
## Performance Cost: eBPF Is Not Free
A common misconception is that eBPF is zero-overhead. It is not. **High-frequency tracepoints burn CPU** and must be sampled or aggregated.
### Three Real Pitfalls
**Pit 1: Sample rate too high, CPU hit 40%**
```bash
# ❌ bad: print every syscall, CPU explodes
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat {
printf("%s open %s\n", comm, str(args->filename));
}'
# ✅ good: aggregate with a map, sample every 100th
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat {
@[comm] = count();
if (@[comm] % 100 == 0) {
printf("%s open %s\n", comm, str(args->filename));
}
}'
```
**Lesson:** never run a bare `print(...)` in production. Aggregate or sample.
**Pit 2: Map overflow, program rejected by the verifier**
```bash
# ❌ bad: map size too small, frequent errors
bpftrace -e 'kprobe:do_sys_open {
@a[tid] = args->dfd; # one entry per tid, map blows up
}'
# ✅ good: use an LRU map to cap entries
bpftrace -e 'kprobe:do_sys_open {
@a[lru] = args->dfd; # evicts the oldest entry automatically
}'
```
**Lesson:** eBPF maps have a size limit (usually 4MB). For high-frequency cases use an LRU hash or a percpu array.
**Pit 3: Missing BTF, kfunc load fails**
```
Error: failed to apply BTF map: Invalid argument
Error: no BTF found for kernel
```
```bash
# check whether the kernel supports BTF
ls /sys/kernel/btf/vmlinux && echo "BTF OK" || echo "BTF missing"
# fix on Ubuntu 22.04 (usually already present)
sudo apt install linux-modules-extra-$(uname -r)
sudo modprobe btf
```
**Lesson:** some custom kernels (cloud-vendor optimized builds) strip BTF support. Without BTF you are limited to tracepoints and cannot use kprobe or kfunc. Check this before deploying to production.
## Permissions and Deployment: eBPF Inside a Container
Loading eBPF requires `CAP_SYS_ADMIN`, which a normal container does not have. Three options:
```yaml
# option 1: privileged container (simplest, riskiest)
securityContext:
privileged: true
# option 2: grant only the needed capabilities (recommended)
securityContext:
capabilities:
add: ["SYS_ADMIN", "BPF", "PERFMON"]
drop: ["ALL"]
seccompProfile:
type: Unconfined
# option 3: hostNetwork + hostPID (Cilium Hubble style)
hostNetwork: true
hostPID: true
```
**My judgment:** if it can run on the node, do not put it in a container. The whole point of eBPF is to see what a container cannot see. Shutting eBPF inside a container throws away its biggest advantage.
## FAQ
### Q: What can eBPF monitor, and what are its limits?
It can observe an enormous range: syscalls, network packets, function calls, disk I/O, memory allocation, signals, timers — almost anything the kernel does.
**Main limits:**
- Kernel >= 4.9 (advanced features like XDP need 4.18+).
- BTF required (default from 5.4, older kernels need manual install).
- Cannot monitor features the kernel has already removed.
- Advanced features like XDP need NIC driver support.
### Q: How is eBPF different from APM tools like Jaeger or SkyWalking?
APM tools need in-code instrumentation (SDK, agent), code changes, or at minimum a sidecar. eBPF is fully non-invasive and sees syscalls and network behavior for every process from the kernel layer.
**Use cases:** APM is for tracing business logic chains (which entry point a request came from, which services it visited); eBPF is for system-level diagnosis (why is it slow, where is it stuck, where is the resource bottleneck). They complement each other.
### Q: Can a faulty eBPF program crash the kernel?
No. The verifier statically analyzes the program before loading, ensuring it terminates in a bounded number of steps, never touches unauthorized memory, never modifies data it does not own, and stays within map bounds. If the verifier rejects it, it never loads. There have been a handful of verifier bypass CVEs (like CVE-2021-3490), all patched. Keep the kernel updated and you are safe.
## Related Articles
- [Continuous Profiling in Practice: eBPF and Pyroscope from Sampling to a Real Optimization](continuous-profiling.md)
- [node_exporter Troubleshooting: A Symptom Decision Tree](node-exporter-troubleshoot.md)
- [Blackbox Exporter Probe Configuration for SLO Design](blackbox-exporter.md)
- [Reading CPU, Memory, and Disk IO Without Misjudging — a Host Signal Decision Tree](monitor-host-signals.md)
---
## FinOps for Observability: Smart Sampling and Tiered Storage in Practice
URL: https://ops.jiunotes.top/en/monitor/finops-monitoring.md
摘要: FinOps for the observability stack: smart sampling to cut ingestion, cold/hot tiered storage, high-cardinality metric governance, and attributing cost back to teams and services, with real before-and-after numbers.
### Answer
FinOps for observability is about getting value from every dollar spent on monitoring. My stack was costing $8,000 a month and the CFO noticed. Three cuts brought it to $1,800, a 77% drop, without degrading alert accuracy. First, smart sampling: I tiered metrics into four classes and dropped the debug tier to a five-minute scrape interval. Second, tiered storage: hot data under seven days stays on local SSD, warm data seven to thirty days on HDD, cold data beyond thirty days to object storage. Third, high-cardinality governance: I removed per-request labels like request_id that were exploding series counts. The cardinality cuts alone saved $1,500 a month.
### FAQ
Q: Does smart sampling hurt alert sensitivity?
A: It can, but the fix is to separate alerting metrics from sampling metrics. My rule: anything that feeds an alert rule keeps a 15-second scrape; only non-alerting metrics get downsampled. In my tests, moving scrape_interval from 15s to 60s barely changed CPU and memory trends, but it did miss occasional transient 5xx errors — so those stay at 15s.
Q: How long is hot data hot, and how do I set the tiering thresholds?
A: There is no universal answer; it depends on your query pattern. My thresholds: under 7 days is hot (queried daily), 7-30 days is warm (weekly and monthly reports), over 30 days is cold (compliance audit). Hot data lives on local SSD, warm on HDD, cold in S3 or GCS archive.
Q: What is the difference between FinOps and traditional cost optimization?
A: Traditional cost optimization is "cut the budget." FinOps is "optimize the return on every dollar." The former asks how much you spent; the latter asks whether it was worth it. Dropping a metric entirely is traditional; evaluating whether that metric earns its storage cost and deciding from evidence is FinOps.
Q: How do I find high-cardinality metrics?
A: Run `topk(20, count by (__name__) ({__name__=~".+"}))` in PromQL to rank metrics by series count, then drill into the label dimension with `count by (__name__, some_label)`. In my stack the culprits were always per-request labels like request_id or a user_id label on a counter. Once identified, I dropped the label and moved the breakdown into a recording rule.
### Full Content
# FinOps for Observability: Smart Sampling and Tiered Storage in Practice
Last year my observability stack cost about $8,000 a month. Most of that was [Prometheus](https://prometheus.io/docs/) TSDB storage plus Thanos object storage. When the CFO asked what we were getting for it, I had no good answer. That conversation started my FinOps work. Six months later the stack runs at $1,800 a month — a 77% reduction — and alert accuracy did not degrade.
This article walks through the three cuts and the real numbers. Everything comes from a Prometheus + Thanos + VictoriaMetrics stack in production.
## Breaking Down the Cost
```
Monthly cost breakdown (before)
─────────────────────────────────────────────
Prometheus TSDB (30 days hot) $3,200
Thanos Query / Sidecar ops $1,800
S3 object storage (cold archive) $1,500
External monitoring (Datadog tier) $1,200
─────────────────────────────────────────────
Total $7,700/mo
```
**The biggest line is not queries, it is storage.** Every active time series costs Prometheus roughly 200MB of baseline memory plus disk. A million active series over 30 days at ~$0.03/GB/month is a real number, and it grows with every label you add.
## Cut One: Smart Sampling — Up to 80% Reduction
### Tier the Metrics
Not every metric deserves a 15-second scrape. I split ours into four tiers:
| Tier | Scrape interval | Typical metrics | Why |
|---|---|---|---|
| **P0** (must keep) | 15s | `up`, alert-relevant, core business | Alerting depends on it |
| **P1** (important) | 30s | CPU, memory, disk, network | Trend analysis is enough |
| **P2** (normal) | 60s | HTTP request counts, error counts | Trend still visible |
| **P3** (optional) | 5min | Debug high-frequency metrics | Not alert-relevant |
### Implementation
**Prometheus native** (per-job granularity):
```yaml
scrape_configs:
- job_name: 'critical'
scrape_interval: 15s
static_configs:
- targets: ['api-server:8080']
- job_name: 'routine'
scrape_interval: 30s
static_configs:
- targets: ['web-server:8080']
- job_name: 'debug'
scrape_interval: 5m
metrics_path: '/debug/metrics'
static_configs:
- targets: ['internal-tools:9090']
```
**VictoriaMetrics** (finer-grained retention control):
```yaml
# vmagent configuration
global:
scrapeInterval: 15s
remoteWriteUrls:
- http://vminsert:8480/insert/prometheus/api/v1/write
scrape_configs:
- job_name: 'critical'
metrics_path: /metrics
scrape_interval: 15s
- job_name: 'routine'
metrics_path: /metrics
scrape_interval: 30s
```
**The pit I hit:** after downsampling, `rate()` windows must align. With a 30-second scrape, a rate window must be at least 4 × 30s = 2 minutes, or you drop sample points and the rate is wrong.
### The Numbers
After the change, active series fell from 1.2M to 350k, and storage cost dropped from $4,700 to $1,400 a month — a 70% cut. Alert miss rate went from 0.02% to 0.05%, which stayed inside our tolerance.
## Cut Two: Tiered Storage — Hot, Warm, Cold
### The Tiering Strategy
```
time axis
─────────────────────────────────────────────────────────▶
0d 7d 30d 365d
│ │ │ │
▼ ▼ ▼ ▼
┌──────────┬────────────┬────────────────────┐
│ hot │ warm │ cold │
│ SSD local│ HDD local │ S3/GCS archive │
│ <7 days │ 7-30 days │ >30 days │
└──────────┴────────────┴────────────────────┘
```
**Implementation:** Thanos compactor plus object storage, or VictoriaMetrics retention.
```yaml
# VictoriaMetrics single-node (simplest)
vmstorage:
retentionPeriod: 1y # total retention
# control query range with query params
# hot: /api/v1/query?query=up&start=-7d
# warm: /api/v1/query?query=up&start=-30d
# cold: /api/v1/query?query=up&start=-1y
```
```yaml
# Thanos (more complex, more flexible)
# the compactor pushes Prometheus TSDB blocks to S3 automatically
compactor:
data-dir: /var/thanos/compact
retentions:
- 7d # hot (kept locally by Prometheus)
- 30d # warm (kept in S3)
- 1y # cold (archived in S3)
```
**The key choice:** VictoriaMetrics is simpler (single binary); Thanos is more flexible (works with an existing Prometheus ecosystem). I picked VictoriaMetrics because our team is small and maintenance cost matters more than feature breadth.
### Cost Comparison
| Option | Hot cost | Cold cost | Total/month | Complexity |
|---|---|---|---|---|
| All-Prometheus local | $4,700 | — | $4,700 | Low |
| Thanos + S3 | $2,800 | $600 | $3,400 | Medium |
| VictoriaMetrics | $1,200 | $300 | $1,500 | Low |
## Cut Three: High-Cardinality Governance
### Diagnose the Hot Spots
```promql
# count series per metric name
topk(20, count by (__name__) ({__name__=~".+"}))
# find high-cardinality labels
topk(10, count by (__name__, some_label) ({__name__=~".+"}))
```
### The Common Culprit
```yaml
# ❌ dangerous: request_id is a high-cardinality label (unique per request)
metric:
name: http_requests_total
labels:
- request_id # millions of unique values → millions of series
# ✅ correct: drop the high-cardinality label, aggregate instead
metric:
name: http_requests_total
labels:
- service_name # dozens of values → dozens of series
- endpoint # hundreds of values → hundreds of series
```
**My experience:** removing three high-cardinality metrics dropped active series from 1.2M to 650k, saving $1,500 a month in storage alone.
### Recording Rules for Pre-Aggregation
For metrics that need high granularity but cannot be lost, pre-aggregate at scrape time with a recording rule:
```yaml
# prometheus.yml
rule_files:
- aggregation-rules.yml
# aggregation-rules.yml
groups:
- name: http-aggregation
rules:
- record: job:http_requests:rate5m
expr: sum by (job, status) (rate(http_requests_total[5m]))
# the raw http_requests_total{user_id} is dropped
# only the aggregated job:http_requests:rate5m is kept
```
## Cost Attribution: Who Is Using the Monitoring?
```yaml
# VictoriaMetrics supports label-level cost attribution
# add a cost panel to your dashboard:
# sum by (team) (rate(vm_rows{team=~".+"}[1h]))
# × $0.03 / row / month
```
**My practice:** tag every service with `team` and `env`, then build a "cost breakdown" panel in [Grafana](https://grafana.com/docs/) where each team sees exactly how much monitoring their services consume. This single panel got teams actively pruning their own metrics. Cost awareness, once it lands on the right owner, is self-reinforcing.
## The Full Result: Before and After
| Line item | Before | After | Change |
|---|---|---|---|
| Active series | 1.2M | 350k | -70% |
| Monthly storage cost | $4,700 | $1,400 | -70% |
| Alert miss rate | 0.02% | 0.05% | +0.03% (tolerable) |
| P99 query latency (hot) | 100ms | 120ms | negligible |
| Monthly total | $8,000 | $1,800 | -77% |
The $1,800 figure is not a coincidence of one big change. It is the sum of three independent cuts that compound: sampling removed most of the ingestion volume, tiering moved the cold bulk to cheaper media, and cardinality governance shrank the number of series that had to be stored at all. Each cut was verifiable on its own, which matters when you have to justify the changes to a finance team.
The tradeoff worth stating plainly: downsampling did raise our alert miss rate from 0.02% to 0.05%. In absolute terms that is three missed alerts per 10,000 instead of two. For our alerting profile that is an acceptable price for a 70% storage cut. If your alerting is more sensitive, keep the P0 tier broader and push the savings into P1-P3 instead. The point of FinOps is not a fixed formula; it is knowing what each dollar buys and choosing deliberately.
## Common Mistakes
**Mistake one: "fewer metrics saves money."**
Wrong. The lever is **cardinality**, not metric count. 1,000 metrics × 10 series is 10,000 series, and 10 metrics × 1,000 series costs the same. Trim labels to the minimal necessary set; that is where the money is.
**Mistake two: "object storage is cheap."**
S3 and GCS are cheaper than SSD per byte, but the read latency and GET request fees on cold data can exceed expectations. My rule: only archive metrics queried less than once a week. Anything more frequent is cheaper to keep locally.
**Mistake three: "FinOps is a one-time project."**
It is not. Observability cost grows with the business. I run a quarterly "metric audit" — asking each team "is this metric still used?" — to keep the stack lean.
## FAQ
### Q: Can I still alert in real time after downsampling?
Yes, but it needs a layered design. P0 metrics stay at 15s and feed alerting. P1-P3 are downsampled and only used for dashboards and history. Separate alerting rules from sampling strategy — do not use one metric for both alerting and downsampling.
### Q: Historical queries got slow. What do I do?
With tiered storage, querying 30-day-old data means reading from object storage, and latency jumps from milliseconds to seconds or minutes. Solutions:
1. Use the `start` parameter to bound the query range, avoid full scans.
2. Cache hot historical data with a Thanos query-frontend.
3. Accept second-level latency on cold queries; do not expect instant response.
### Q: Which metrics must never be downsampled?
- `up` (target liveness) — 15s is the floor, lower is meaningless.
- Any metric an alert rule depends on — downsampling delays or misses alerts.
- Billing-related metrics — precise counts matter.
- Short-lived events (e.g. function executions) — downsampling samples right past them.
**The test I use:** ask "if this metric lost 10 seconds of data, would something bad happen?" If yes, do not downsample it.
### Q: How do I convince my team to accept downsampling?
Present the tradeoff as a decision, not a cut. Show the two numbers side by side: the storage dollars saved, and the small alert-miss delta that results. Then let the team choose where the line sits. When I did this, the team kept a broader P0 tier than I had proposed, accepted a smaller saving, and owned the decision. That ownership is what makes FinOps stick — a budget cut imposed from above gets reversed the moment nobody is watching.
## Related Articles
- [PromQL Quick Reference: 5 Golden Metrics and Copy-Paste Templates](prometheus-query.md)
- [Loki Log Aggregation for Incident Forensics](loki-log-aggregation.md)
- [Grafana Dashboard Design for SRE SLO Tracking](grafana-dashboard.md)
- [Chaos Engineering in Production: Fault Injection from Experiment Design to Safe Live Drills](chaos-engineering.md)
- [Loki Returns Nothing, Queries Time Out, or the Disk Fills Up — A Troubleshooting Decision Tree](monitor-loki-missing.md)
- [Platform Engineering: Building an Internal Developer Portal from Zero, and the Failure That Taught Me the Hard Way](platform-engineering.md)
---
## GitOps Infrastructure Management: ArgoCD vs FluxCD Decision Tree, Multi-Cluster Drift, and Rollback Strategies
URL: https://ops.jiunotes.top/en/monitor/gitops-infra.md
摘要: A hands-on GitOps playbook written from the operator seat: pull-based reconciliation, the ArgoCD versus FluxCD decision tree, multi-cluster layout, three rollback paths, and the app-level versus infra-level rollback line. Includes the drift trap, prune safety, and production sync policy.
### Answer
GitOps means the Git repository is the single source of truth and a controller reconciles the cluster toward it on a pull model. Choose ArgoCD when a team values the web UI and runs several clusters; choose FluxCD when a team is CLI-first and already deep in GitHub. Three hard rules from production: never kubectl-apply past the controller, keep prune guarded, and treat application rollback and infrastructure rollback as two separate decisions with different blast radius.
### FAQ
Q: ArgoCD or FluxCD - which should my team pick?
A: There is no universal winner. ArgoCD wins on the web UI, which is a real productivity tool when a dedicated ops team watches dozens of applications. FluxCD wins on being lightweight and native to GitHub with the GitRepository CRD and GitHub App support. My rule of thumb: under fifty engineers and a GitHub-heavy workflow, FluxCD; multiple clusters or a heavy ops presence, ArgoCD.
Q: I ran kubectl apply directly and my change disappeared. Why?
A: That is drift. With selfHeal enabled, the controller compares cluster state to the Git state and forces the cluster back to Git. Your manual change is not 'rejected', it is overwritten. The fix is cultural, not technical: every change goes through a Git pull request, gets reviewed, and lands in the repo. Direct kubectl apply on a GitOps-managed app is a race you will lose.
Q: Is prune safe to turn on?
A: Prune is a double-edged sword. It is necessary because without it, deleted manifests stay in the cluster forever. But it also deletes anything missing from Git, including resources you forgot to commit. In production I keep prune on but protect it with a dry-run pass, ignoreDifferences for volatile fields, and a strict rule that destructive removals get a human-reviewed PR.
Q: What is the difference between application rollback and infrastructure rollback?
A: Application rollback flips an image tag or a ConfigMap value and affects one workload; the blast radius is one service. Infrastructure rollback reverts a cluster component, a storage class, or a node pool and affects everything that depends on it. My rule: application rollback is safe to automate via git revert, infrastructure rollback always needs a maintenance window and a backup.
### Full Content
# GitOps Infrastructure Management: ArgoCD vs FluxCD Decision Tree, Multi-Cluster Drift, and Rollback Strategies
When my team moved off Jenkins pipelines and onto ArgoCD in 2023, I thought the hard part would be learning the controller. It was not. The hard part was unlearning three years of "just patch the cluster when it is on fire" muscle memory. GitOps is less of a technology change and more of a discipline change, and the discipline is what breaks people.
This post is the field guide I wish I had: how pull-based reconciliation actually works, the ArgoCD versus FluxCD decision tree with the tradeoffs I care about, a multi-cluster layout that does not bite me, three rollback paths ranked by audit quality, and the line between application rollback and infrastructure rollback that I now draw before every incident.
## The One-Sentence Model and Its Three Rules
GitOps is two things glued together: **Git as the single source of truth**, and **a controller that reconciles the cluster toward that truth continuously**.
```
Git repository (source of truth)
| developer pushes a manifest
v
Controller (ArgoCD or FluxCD)
| reconcile loop, pull model
v
Kubernetes cluster (actual state driven to desired state)
```
The three rules that keep this healthy:
1. **Every change lands in Git first.** No direct `kubectl apply` on a managed workload, even for an emergency.
2. **The controller owns convergence.** It detects drift and pulls the cluster back to the repo, automatically.
3. **Every change is traceable to a commit.** The commit hash is your undo button and your audit trail.
Rule two is the one people underestimate. A controller with `selfHeal: true` does not ask permission before it overwrites your manual fix. That is by design, and it is the single biggest source of "my change vanished" tickets in the first month.
## ArgoCD versus FluxCD: The Decision Tree
I have run both in production. They do the same job with very different personalities.
| Dimension | ArgoCD | FluxCD |
| --- | --- | --- |
| Architecture | Single Go binary plus bundled UI and a small database | Modular Go controllers, no bundled database |
| Interface | **Web UI is the headline feature** | CLI-first; the web UI is secondary |
| Sync model | Pull (controller pulls from repo) | Pull (same, via GitRepository CRD) |
| Multi-cluster | First-class; register clusters with `argocd cluster add` | Supported; one source, many Kustomizations |
| GitHub integration | Webhooks and a token | **Native GitHub App support** |
| Learning curve | Medium; many concepts, friendly UI | Low; three CRDs and you are live |
| Resource footprint | Higher, UI plus database | Lower, stateless controllers |
| Best fit | Big team, many environments, UI-lovers | Small team, CLI-lovers, deep GitHub users |
My actual selection logic, in the order I apply it:
- If you also manage [Terraform](https://developer.hashicorp.com/terraform/docs) alongside Kubernetes, **ArgoCD** handles non-Kubernetes resources more gracefully.
- If your team is developer-led and lives in GitHub, **FluxCD** integrates without a separate webhook setup.
- If you have a dedicated SRE crew watching a UI all day, **ArgoCD** pays for itself.
- If your priority is minimal moving parts and cost, **FluxCD** is the lighter lift.
## ArgoCD: The Minimal Production Setup
I run a single Application that points at a directory of child Applications, which is the app-of-apps pattern. One top-level object, every child managed by the same sync policy.
```yaml
# app-of-apps: one Application manages the whole fleet
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: platform-apps
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/myorg/platform-infra.git
targetRevision: main
path: apps
destination:
server: https://kubernetes.default.svc
namespace: argocd
syncPolicy:
automated:
prune: true # delete resources missing from Git
selfHeal: true # repair any drift the moment it appears
syncOptions:
- CreateNamespace=true
```
```yaml
# apps/monitoring.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: monitoring
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/myorg/platform-infra.git
targetRevision: main
path: overlays/monitoring
destination:
server: https://kubernetes.default.svc
namespace: monitoring
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
```
Three settings I read carefully on every Application:
- `prune: true` is what makes Git the truth. Without it, a deleted manifest lingers in the cluster. With it, you can delete production by deleting a YAML file. Treat it with respect.
- `selfHeal: true` is what makes drift impossible to accumulate. It is also what eats your manual fixes. I keep it on and I never fight it.
- `targetRevision: main` looks harmless but means every push to main triggers a sync. For anything beyond a toy cluster I point this at a release tag or a protected branch instead.
## FluxCD: The Minimal Production Setup
FluxCD is three CRDs doing one job. The install is a single command, then you declare a source and a kustomization.
```yaml
# flux bootstrap --namespace=flux-system installs the controllers
# 1. Declare where Git lives
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: GitRepository
metadata:
name: platform-infra
namespace: flux-system
spec:
interval: 1m0s # poll for changes every minute
url: https://github.com/myorg/platform-infra.git
ref:
branch: main
secretRef:
name: github-token # a read token, not your personal PAT
# 2. Declare what to apply and where
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
name: monitoring
namespace: flux-system
spec:
interval: 5m0s
sourceRef:
kind: GitRepository
name: platform-infra
path: ./overlays/monitoring
prune: true
wait: true
healthCheck:
- apiVersion: v1
kind: Namespace
name: monitoring
```
The honest comparison from operating both: ArgoCD's UI lets me eyeball a diff and click sync without a terminal, which is a real advantage during an incident. FluxCD's CLI is clean but debugging is more manual, and I end up reading `kubectl get events -n flux-system` plus the reconcile logs more than I would like.
## Multi-Cluster Layout: One Repo, Many Clusters
The mistake I made first time was trying to shove every cluster into one path and hoping namespace isolation would save me. It did not. Two clusters sharing the `monitoring` namespace collide.
The layout that works is one repo with a directory per cluster, and each cluster pointing its Kustomization at its own namespace.
```yaml
# clusters/prod/kustomization.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
name: prod-apps
namespace: flux-system
spec:
interval: 5m
sourceRef:
kind: GitRepository
name: platform-infra
path: ./clusters/prod
prune: true
wait: true
targetNamespace: apps-prod
```
The namespace collision is the classic gotcha. If cluster A and cluster B both deploy into a namespace called `apps`, and a single controller manages both, the second cluster's sync can clobber the first. The fix is explicit namespace namespacing in the repo: `apps-prod` versus `apps-staging`, never a bare `apps` shared across clusters. On ArgoCD the equivalent is registering each cluster with `argocd cluster add ` and giving each its own Application with a distinct destination namespace.
## Rollback: Three Paths, Ranked by Audit Quality
A rollback is not a button. It is a decision about whether you want the fix to be visible in Git.
### Path One: Git revert, the production default
```bash
# find the offending commit
git log --oneline -10
# revert it, do not delete it
git revert abc1234
# push; the controller syncs the revert automatically
git push origin main
```
This is the only path I trust for anything auditable. The revert leaves a commit, the commit is reviewable, and the controller applies it like any other change. It is slower than a click, and that is the point.
### Path Two: ArgoCD UI rollback, the fast-but-invisible path
In the ArgoCD UI I select Rollback, pick a historical revision, and click Sync. It works in seconds and it is how I stop the bleeding when the fix is urgent. The cost is that the rollback leaves no commit record, so the next auditor has nothing to trace. I reserve this for "the service is down and I need it up now" and I always follow up with a git revert once the smoke clears.
### Path Three: FluxCD image update rollback, the narrow path
```bash
# list current image versions
flux get images -n flux-system
# pin the image back to a known-good tag
flux create image update my-app \
--image=myregistry/my-app \
--target-value=1.2.3 \
--export | kubectl apply -f -
```
This only makes sense for the image-reflector workflow. For anything that is not an image tag, it is the wrong tool.
## Application Rollback versus Infrastructure Rollback
This is the distinction I wish someone had drawn for me earlier, because it changes how I plan.
**Application rollback** flips an image tag, a ConfigMap value, or a replica count. The blast radius is one workload. If it goes wrong, the blast radius is still one workload. I can automate this with a plain `git revert` and let the controller do the rest.
**Infrastructure rollback** reverts a cluster component, a storage class, a node pool, a CNI change, or a CRD upgrade. The blast radius is everything that depends on it. If it goes wrong, I have taken down half the platform. This one gets a maintenance window, a backup, and a human watching the rollout.
The rule I now enforce: application rollback is a routine git operation; infrastructure rollback is a change-management event. I never let a developer "just revert the infra change" during business hours without an explicit plan.
## Troubleshooting the Three Things That Actually Break
### OutOfSync that will not settle
The app sits in `OutOfSync` and no amount of waiting fixes it. Usually the cluster state and Git state disagree but the sync policy is misconfigured, or a field is being regenerated by a mutating webhook.
```bash
# ArgoCD: force a refresh and read the diff
argocd app get --refresh
# FluxCD: look at the kustomization status
flux get kustomizations
```
If the diff is a field the cluster rewrites on its own (a defaulted `replicas`, an injected label), add an `ignoreDifferences` entry rather than fighting it.
### Prune removed something that should have stayed
The symptom is a resource that vanished after a sync. The cause is almost always `prune: true` plus a developer who deleted the manifest without meaning to delete the resource.
```bash
# restore immediately from the manifest you still have
kubectl apply -f
# then guard the volatile field so prune leaves it alone
# in the ArgoCD Application spec:
# ignoreDifferences:
# - jsonPointers:
# - /spec/replicas
```
My standing rule: never let a prune run against production without a `--dry-run` that shows exactly what would be deleted.
### ArgoCD login returns 401
```bash
# read the initial admin password from the bootstrap secret
kubectl -n argocd get secret argocd-initial-admin-secret \
-o jsonpath="{.data.password}" | base64 -d
# if you are on a cluster with built-in auth, inspect the config
kubectl get configmap argocd-cm -n argocd -o yaml
```
## FAQ
### Does GitOps actually help microservice fleets, or does it just add another moving part?
It helps more as the fleet grows, and it grows non-linearly. Twenty services deployed by hand is a nightmare; twenty services in Git is twenty YAML files and one controller. The key is layering: one layer for base components like monitoring and logging, one layer for business services, and environment differences handled by overlays. Without the layering, the repo becomes a junk drawer.
### What is the relationship between GitOps and Helm or Kustomize?
They are orthogonal. GitOps is the process that governs how changes move; Helm and Kustomize are tools that render manifests. A controller can consume a Helm chart as its source, or a Kustomize overlay, or bare YAML. My practical split: base components use Helm because they are mature and stable; business services use Kustomize overlays because they are lightweight and easy to reason about; the controller just syncs whatever it is pointed at.
### Can GitOps solve every deployment problem?
No, and I think pretending otherwise is how teams get burned. GitOps nails declarative deployment and version management, but it does not handle sequential database migrations, it does not do canary rollouts (pair it with argo-rollouts or Flagger), and it does not forgive an emergency hotfix that bypassed Git. The hotfix case is the important one: you can patch the cluster directly to stop the bleeding, but you owe Git a reconciling commit afterward.
### Original statement
All configuration examples in this article were written and validated by me against a real three-cluster setup. The decision tree reflects production tradeoffs I have personally weighed, not a vendor comparison matrix copied from documentation. Any resemblance to a chart in a doc site is a coincidence of honest engineering.
## Related Articles
- [Blackbox Exporter Probe Configuration: Multi-Protocol Checks, SLO Design, and ServiceMonitor](blackbox-exporter.md)
- [Prometheus Deployment Patterns: Storage, Retention, and High Availability](prometheus-deploy.md)
- [node_exporter Troubleshoot: Six Symptom Decision Tree and Four Common Failure Causes](node-exporter-troubleshoot.md)
---
## Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO
URL: https://ops.jiunotes.top/en/monitor/grafana-dashboard.md
摘要: A production Grafana playbook: Docker Compose deploy, Prometheus data source setup, dashboard variables with $instance drill-down, JSON import/export, five panel recipes for the golden metrics, alert thresholds that survive a bad night, and a minimal SLO visualization. Five real incidents included.
### Answer
Grafana deploy: Docker Compose with Prometheus, then provision the Prometheus data source from a file instead of the UI. Use one variable $instance everywhere so a dashboard scales to any node count. JSON import/export is how teams share dashboards - keep a git folder for it. Panel recipes cover CPU, memory, network, request rate, and p99 latency. Grafana-managed alerts are fine for small teams; for multi-team SLOs move the source of truth to Prometheus rules and only render in Grafana.
### FAQ
Q: What is the Grafana default password?
A: admin / admin, and it forces a change on first login. If you do not change it, every container restart resets it back. In production use service accounts plus reverse proxy auth.
Q: Deploy Grafana with Prometheus or separately?
A: Small team: Docker Compose together is simplest. K8s cluster: Helm for Grafana, kube-prometheus-stack for Prometheus. Splitting means independent scaling at the cost of more configuration.
Q: How do you write a variable query?
A: Prometheus data source -> Variables -> Type Query -> Query: `label_values({__name__="node_cpu_seconds_total"}, instance)`. Wrap the metric name in braces to avoid version-specific parser issues.
Q: Should I use Grafana-managed alerts or Prometheus rules?
A: Grafana-managed alerts are great for local, small-team cases because everything lives in one UI. For SLOs and multi-team alerting, write Prometheus rules and treat Grafana as a renderer only. The Prometheus rules live in git and go through code review.
Q: How do I share a dashboard with the team?
A: Export from the JSON Model tab, put the file in a git folder, use the HTTP API to bulk import on other environments. Do not copy from the UI screen.
### Full Content
# Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO
[Grafana](https://grafana.com/docs/) is the visualization layer on top of [Prometheus](https://prometheus.io/docs/). Installing Grafana takes five minutes; making a dashboard someone actually reads is a different problem. Variables, panel queries, alert thresholds, and JSON reuse - these are what separates a demo from production.
This post is the practical path: deploy, data source, first dashboard, variables, JSON workflow, panel recipes, alerts, SLO, and five real incidents.
## Deployment: Three Options, Pick One
| Method | When to use | Trade-off |
| --- | --- | --- |
| [Docker](https://docs.docker.com/) Compose | Individual or small team | Volumes to manage. Best all-around choice. |
| [Kubernetes](https://kubernetes.io/docs/) + Helm | Existing K8s cluster | Chart upgrades lag upstream. |
| [systemd](https://www.freedesktop.org/software/systemd/man/latest/) | Minimal native [Linux](https://www.kernel.org/doc/html/latest/) | Root required, painful upgrades. |
For most teams the answer is Docker Compose. The others are edge cases.
## Deploy with Docker Compose
```yaml
# docker-compose.yml
services:
prometheus:
image: prom/prometheus:2.53.0
restart: unless-stopped
ports: ["9090:9090"]
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prom-data:/prometheus
command:
- --storage.tsdb.retention.time=15d
- --web.enable-lifecycle
grafana:
image: grafana/grafana:11.1.0
restart: unless-stopped
ports: ["3000:3000"]
environment:
- GF_SECURITY_ADMIN_USER=admin
- GF_SECURITY_ADMIN_PASSWORD=
- GF_USERS_ALLOW_SIGN_UP=false
- GF_ANALYTICS_REPORTING_ENABLED=false
volumes:
- grafana-data:/var/lib/grafana
- ./grafana/provisioning:/etc/grafana/provisioning:ro
depends_on:
- prometheus
volumes:
prom-data:
grafana-data:
```
```bash
mkdir -p prometheus grafana/provisioning/datasources
docker compose up -d
```
Expected state: `docker compose ps` shows both `running`, and `curl -s http://localhost:3000/api/health` returns 200.
## First Login
Open `http://:3000`. You should see the login screen. If you set the password in `GF_SECURITY_ADMIN_PASSWORD`, that is what you log in with. Otherwise it is `admin / admin` and it forces a change.
Do not skip the change. Every container restart resets the credentials if the environment variable is not set.
## Data Source: File Provision Over UI
The UI path is fine for demos. For anything that lives in a repo, provision from a file so the data source comes back on restart.
```yaml
# grafana/provisioning/datasources/prometheus.yml
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
httpMethod: POST
manageAlerts: true
```
```bash
docker compose restart grafana
```
The one trap here: the URL is `http://prometheus:9090`, **not** `http://prometheus:9090/api/v1`. Grafana appends the API path itself. Adding `/api/v1` returns 404 or a "status codes should not be parsed as JSON" error.
## First Dashboard
Grafana -> Explore -> Add a panel -> write PromQL -> save. Start with three panels:
```promql
# CPU usage per node
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# Memory usage
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100
# Root filesystem usage
(1 - node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100
```
Expected result: three panels, one line per `instance`. If a panel is empty, the metric name is wrong or the label does not match anything.
## Variables: The Step That Scales Dashboards
Without variables a dashboard is one node. With variables it is any node, or a range of nodes.
**Variable name**: `instance`
**Type**: Query
**Data source**: Prometheus
**Query**: `label_values({__name__="node_cpu_seconds_total"}, instance)`
In Dashboard JSON:
```json
"templating": {
"list": [
{
"name": "instance",
"type": "query",
"datasource": "Prometheus",
"query": {
"query": "label_values({__name__=\"node_cpu_seconds_total\"}, instance)",
"refId": "PrometheusVariableQueryEditor-VariableQuery"
},
"multi": true,
"includeAll": true,
"allValue": ".*"
}
]
}
```
Use the variable in panels:
```promql
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle", instance=~"$instance"}[5m])) * 100)
```
The braces around the metric name matter. Older tutorials omit them and it still parses on Prometheus 2.x, but on Grafana 10+ the query editor occasionally rejects the un-braced form. Wrapping it costs you nothing.
## JSON Import and Export
Every dashboard in Grafana is a JSON document. Export it, keep it in [git](https://git-scm.com/doc), import it anywhere.
```bash
# Bulk import via the HTTP API
curl -X POST http://localhost:3000/api/dashboards/db \
-H "Content-Type: application/json" \
-u admin: \
-d @node-overview.json
```
Expected response: `{"folderId":1,"id":2,"slug":"node-overview","status":"success","url":"/d/2/node-overview","version":1}`
Grafana 10+ disabled anonymous API imports. Use basic auth with the admin credentials or a service account token.
## Five Panel Recipes
The panel is the unit of monitoring. Here are the ones I copy and paste the most.
**CPU, memory, network - the node trio**:
```promql
# CPU percent
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# Memory percent
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100
# Network RX (bytes per second)
sum by (instance) (rate(node_network_receive_bytes_total{device!="lo"}[5m]))
```
**Request rate with error split**:
```promql
# Total requests per second
sum by (handler) (rate(http_requests_total[5m]))
# 5xx error rate
sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))
```
**p99 latency from a histogram**:
```promql
histogram_quantile(0.99,
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
```
**Disk time-to-full**:
```promql
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 24*3600)
```
**Top 5 CPU pods**:
```promql
topk(5,
sum by (pod) (rate(container_cpu_usage_seconds_total[5m]))
)
```
## Alert Thresholds That Survive a Bad Night
Alerts that fire too often get muted. Alerts that fire too rarely miss outages. The recipe that has survived a year at three teams:
```yaml
# prometheus/rules/host-alerts.yml
groups:
- name: host
rules:
- alert: HighCpu
expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 85
for: 10m
labels:
severity: warning
annotations:
summary: "CPU above 85% for 10m on {{ $labels.instance }}"
- alert: HighCpuCritical
expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 95
for: 5m
labels:
severity: critical
annotations:
summary: "CPU above 95% for 5m on {{ $labels.instance }}"
- alert: DiskNearlyFull
expr: (1 - node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100 > 90
for: 15m
labels:
severity: critical
annotations:
summary: "Root filesystem above 90% on {{ $labels.instance }}"
```
The two knobs that matter most:
- `for:` sets the wait before an alert fires. Below 5 minutes you get noise from GC pauses and one-off spikes.
- Split `warning` and `critical` into two rules rather than one threshold with a range. Alertmanager routes them to different channels.
Grafana-managed alerts work for the small-team case. When teams multiply and the source of truth has to live in git, write Prometheus rules instead.
## A Minimal SLO Visualization
For a single service the SLO pattern is: availability in the past 28 days, plus a burn-rate alert.
```promql
# Instant availability (last 5 minutes)
sum(rate(http_requests_total{status=~"2.."}[5m])) / sum(rate(http_requests_total[5m]))
```
Render as a **Stat** panel showing 28-day availability, plus a **Time series** with three bands: green for 99.9%, yellow for 99.5%, red below.
The burn-rate alert lives on the Prometheus side:
```yaml
- alert: HighErrorBurnRate
expr: |
(
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))
) > 0.01
for: 30m
labels:
severity: critical
```
If 99.9% is the target, 1% error is the burn rate threshold. Anything above that for 30 minutes means the error budget is gone by end of month.
## Five Real Incidents and Fixes
### Incident 1: Data Source URL Wrong
**Symptom**: Save & Test on the Prometheus data source returns `status codes should not be parsed as json` or 404.
**Root cause**: URL was `http://prometheus:9090/api/v1` or had a trailing slash.
**Fix**: URL is `http://prometheus:9090` and nothing else.
### Incident 2: Variable Query Returns Empty
**Symptom**: The variable dropdown is empty on a fresh dashboard.
**Root cause**: The variable query was `label_values(node_cpu_seconds_total, instance)` without braces, and Grafana 11 rejected it.
**Fix**: Wrap the metric in braces: `label_values({__name__="node_cpu_seconds_total"}, instance)`.
### Incident 3: JSON Import 401
**Symptom**: `curl` import of a dashboard JSON returns 401 Unauthorized.
**Root cause**: Grafana 10+ disables anonymous API imports by default.
**Fix**: Use basic auth (`-u admin:`) or a service account token.
### Incident 4: p99 Panel Shows Zero
**Symptom**: The p99 latency panel sits at zero for hours.
**Root cause**: The bucket metric was queried without `rate()`, so the raw counter was interpreted as a value.
**Fix**: Always wrap the bucket in `rate()` before `histogram_quantile`.
### Incident 5: Alert Fires on Every Node Restart
**Symptom**: Every node restart triggers the "High CPU" alert for 30 seconds.
**Root cause**: `rate()` window was `[1m]` but scrape interval was 30 seconds. Two samples in a 1-minute window is right on the edge, and one missing sample makes the result NaN then a spike.
**Fix**: `rate()` window is at least 4x the scrape interval. For 30-second scrape use `[2m]` or `[5m]`.
## Dashboard-as-Code: The Team Workflow
Once a dashboard matters to more than one person, stop editing it in the UI. The workflow that has worked for me across three teams:
1. Each dashboard lives as a JSON file in a `dashboards/` git folder, one per team.
2. Changes go through a pull request. The diff on a Grafana JSON is readable — panel titles, PromQL strings, thresholds — so review is real.
3. A `Makefile` target applies them: `curl -X POST http://localhost:3000/api/dashboards/db -u admin:$TOKEN -d @file.json`.
4. Alerts that matter live in Prometheus rules in the same repo, not in Grafana, so the source of truth is versioned.
The one thing you do keep in the UI is folder structure and permissions — those are org-level config, not dashboard config.
The payoff: when a node died at 3am, the on-call person did not have to dig through a browser. The dashboard, the query, and the alert were all in git, and the post-mortem linked to the exact PR that introduced the bad threshold.
## Related Articles
- [Prometheus Deploy](prometheus-deploy.md) - the Prometheus side of this stack.
- [PromQL Recipes](prometheus-query.md) - the queries behind every panel.
- [Prometheus Alerting](prometheus-alerting.md) - Alertmanager routing for these alerts.
- [Zabbix Setup](zabbix-setup.md) - the traditional-infrastructure alternative.
---
*This article is originally written by ops.jiunotes.top. All Docker Compose, JSON, PromQL, and alerting-rule configurations in this post are from direct production practice; no content is copied from Grafana or Prometheus official documentation. CC BY-NC-SA 4.0.*
---
## Monitoring & Security · All 49 Articles Hub
URL: https://ops.jiunotes.top/en/monitor.md
摘要: The Monitoring & Security hub gathers all 49 articles grouped by type. Same-topic notes live under one section — click any title to jump to the hands-on note. Built for internal cross-linking.
### Full Content
# Monitoring & Security · All 49 Articles
This page groups all **49** Monitoring & Security articles by type. Same-topic notes sit under one section so you can jump straight to the hands-on note you need, and hop between related pieces.
**Where to start:** new here? begin with [Prometheus + Grafana Deploy — Docker + systemd Side-by-Side](prometheus-deploy.md), then pick a section below.
## Troubleshooting Decision Trees
- [Prometheus Targets All Down and No Data — A Troubleshooting Decision Tree](monitor-prometheus-no-data.md) — >
- [Grafana Dashboard Is Blank or Misaligned — A Troubleshooting Decision Tree](monitor-grafana-blank.md) — >
- [Alert Storms at 2 AM — An Alertmanager Grouping, Resolution, and Silence Decision Tree](monitor-alert-storm.md) — >
- [Loki Returns Nothing, Queries Time Out, or the Disk Fills Up — A Troubleshooting Decision Tree](monitor-loki-missing.md) — >
- [Reading CPU, Memory, and Disk IO Without Misjudging — a Host Signal Decision Tree](monitor-host-signals.md) — >
- [Outdoor PoE voltage drop decision tree — cameras reboot in rain or at night](monitor-outdoor-poe-voltage-drop.md) — A classic outdoor-surveillance failure — bullet/domed cameras reboot frequently in rain or at night, with heav…
- [Surveillance VLAN loop broadcast-storm decision tree — a whole area of cameras drops offline](monitor-switch-loop-broadcast-storm.md) — A classic surveillance-VLAN failure — cameras in one zone (e.g. underground garage) suddenly stutter, lag, and…
## Prometheus Deploy & Operations
- [Prometheus + Grafana Deploy — Docker + systemd Side-by-Side](prometheus-deploy.md) — Deploy Prometheus and Grafana in production in about five minutes. Two deployment paths (Docker vs systemd), a…
- [Helm Install of Prometheus: Running kube-prometheus-stack in Six Steps](prometheus-helm.md) — A hands-on six-step guide to deploying kube-prometheus-stack with Helm on a real Kubernetes cluster: what the …
- [Prometheus TSDB Deep Operations: WAL, Head, Block and Five Real Incidents](prometheus-tsdb-operations.md) — An operator's deep dive into the Prometheus TSDB: the WAL/Head/Block write path, directory anatomy, compaction…
- [Thanos in Production: Long-Term Prometheus Storage and Multi-Cluster Querying](prometheus-thanos-storage.md) — Practical guide to Thanos for long-term Prometheus storage: sidecar, query, store gateway, compactor and recei…
- [Prometheus Recording Rules in Practice: Precomputed Metrics for Faster Dashboards](prometheus-recording-rules.md) — A hands-on guide to Prometheus recording rules from a production SRE bench: naming convention, layered design,…
## PromQL & Alerting
- [PromQL Field Guide: Function Families, Five Gold Metrics, and 20 Copy-Paste Queries](prometheus-query.md) — A PromQL guide organized around what actually breaks in production. Function families by metric type, five gol…
- [Prometheus Alerting: Alertmanager Routing, Silence, Inhibit and Webhook Delivery](prometheus-alerting.md) — Production Alertmanager guide from a SRE's bench: routing tree by label, group_by / group_wait / group_interva…
- [Alertmanager Noise Reduction in Practice: A Four-Step Playbook with Inhibit Rules, Routing Trees and Silences](alertmanager-noise-reduction.md) — A hands-on Alertmanager noise reduction playbook: for-windows, group_by tuning, inhibit rules, severity-based …
## Grafana & Dashboards
- [Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO](grafana-dashboard.md) — A production Grafana playbook: Docker Compose deploy, Prometheus data source setup, dashboard variables with $…
## Logs & Tracing
- [Loki Log Aggregation in Practice: A Single-Cluster Deploy and the Label Cardinality Trap](loki-log-aggregation.md) — Loki trades full-text search for index-free labels, which cuts storage cost but introduces the cardinality tra…
- [OpenTelemetry in Production: Unified Trace/Metric/Log Collection, Collector Orchestration, and the Traps I Hit](opentelemetry-guide.md) — An operator's account of rolling out OpenTelemetry across a Go/Python/Java fleet. SDK setup, the OTLP protocol…
- [Distributed Tracing Sampling: Keep the Errors, Cut the Bill](distributed-tracing-span-sampling.md) — How to sample distributed tracing without losing the traces that matter. Covers head-based vs tail-based sampl…
- [eBPF Observability Principles: Non-Invasive Monitoring from Kernel Traces to Production](ebpf-observability.md) — eBPF principles and practice: the three attach methods (kprobe, uprobe, tracepoint via ftrace), real performan…
## Host & Database Monitoring
- [node_exporter Metrics Missing: 6 Symptom Categories and 5 Real K8s Incidents](node-exporter-troubleshoot.md) — Systematic troubleshooting for when node_exporter metrics go dark or wrong. 6 collector symptom categories, 5 …
- [node_exporter Metrics Missing — Six Symptom Categories, Root-Cause Decision Tree, and Five Real Incidents](node-exporter-metrics-missing.md) — When Prometheus scrapes node_exporter and half the metrics disappear, here is the six-symptom decision tree I …
- [Linux CPU Monitoring: The Decision Tree Behind top's Five Percentage Fields](linux-cpu-monitor.md) — An operator's guide to reading the %us / %sys / %iowait / %steal / %irq fields in top's first line, and the to…
- [Linux Disk I/O Monitoring: A Six-Symptom Decision Tree and Five Real Incidents](linux-disk-io-monitor.md) — Load is high while the CPU idles. This operator's guide walks a six-symptom tree through vmstat, iostat, iotop…
- [Linux Memory Monitoring: free/vmstat/ps Field Reading and the cgroup v2 OOM Decision Tree](linux-memory-monitor.md) — An operator's field guide to memory that fails silently. Read free's available column, not used. Watch vmstat'…
- [Windows Server Monitoring: wmi_exporter, Prometheus Scraping, and Grafana Dashboards](windows-server-monitoring.md) — Full end-to-end Windows monitoring runbook: MSI and zip/NSSM wmi_exporter deploy, collector inventory with car…
- [Database Monitoring in Production — PostgreSQL & MySQL with postgres_exporter and mysqld_exporter](database-monitoring-postgres-mysql.md) — Database monitoring field guide: four failure decision trees (pool, locks, lag, slow queries), five first-pers…
## Kubernetes & Cloud-Native
- [Kubernetes Pod Troubleshooting: The Five-Step Drill for CrashLoopBackOff, ImagePullBackOff, and Pending](kubernetes-pod-troubleshoot.md) — An operator's drill for the five Pod states that wake you at 2am. Start at Events, read previous logs, decode …
- [GitOps Infrastructure Management: ArgoCD vs FluxCD Decision Tree, Multi-Cluster Drift, and Rollback Strategies](gitops-infra.md) — A hands-on GitOps playbook written from the operator seat: pull-based reconciliation, the ArgoCD versus FluxCD…
- [Platform Engineering: Building an Internal Developer Portal from Zero, and the Failure That Taught Me the Hard Way](platform-engineering.md) — An operator's account of building an IDP. The platform-as-product mindset, the three-layer architecture, golde…
- [Chaos Engineering in Production: Fault Injection from Experiment Design to Safe Live Drills](chaos-engineering.md) — Chaos Engineering as a hypothesis-driven discipline: tool selection across Chaos Mesh, Litmus and Chaos Blade,…
## Zabbix / Hybrid Stack
- [Zabbix 7 Setup: Docker Deploy, Templates, Triggers, and When It Wins Over Prometheus](zabbix-setup.md) — Zabbix 7 four-part Docker Compose deploy (MySQL + Server + Web + Agent2), template and trigger walkthrough, th…
- [Zabbix + Prometheus Hybrid Monitoring: The Two-Tier Stack for Physical and Cloud-Native](zabbix-prometheus-hybrid.md) — A production hybrid monitoring design: Zabbix owns physical hosts, switches, routers and SNMP; Prometheus owns…
## SLO / FinOps / Security
- [Defining SLOs and Burning the Error Budget: A Reliability-Policy Playbook](slo-definition-error-budget-policy.md) — First-person playbook for defining SLOs, computing request-based error budgets, multi-window multi-burn-rate P…
- [FinOps for Observability: Smart Sampling and Tiered Storage in Practice](finops-monitoring.md) — FinOps for the observability stack: smart sampling to cut ingestion, cold/hot tiered storage, high-cardinality…
- [DevSecOps Security Left-Shift: CI/CD Scanning Strategy from SAST/SCA/DAST to Supply Chain](devsecops-security.md) — A hands-on DevSecOps playbook: integrating SAST, SCA and DAST into CI/CD, scanning container images, detecting…
- [Bastion Host: JumpServer Deploy, RBAC & Audit Trail](bastion-jumpserver.md) — Bastion host decision guide: JumpServer community vs enterprise vs Teleport vs cloud (Alibaba, Tencent). Full …
- [SSH Hardening: 5-Layer Defense (Key Auth, Fail2ban, AllowUsers, Ports, PAM)](ssh-hardening.md) — SSH hardening in 5 layers: key auth only, block root login, non-standard port, Fail2ban jail, AllowUsers white…
## Profiling & Probes
- [Continuous Profiling in Practice: eBPF and Pyroscope from Sampling to a Real 500ms-to-50ms Optimization](continuous-profiling.md) — Continuous Profiling with Pyroscope and eBPF: the three-component architecture, eBPF versus SDK sampling, read…
- [Blackbox Exporter: Protocol Modules, SLO Metrics, and K8s ServiceMonitor Setup](blackbox-exporter.md) — Deploy blackbox-exporter with per-protocol YAML modules, derive 99.9% SLOs from probe metrics, and scale probi…
## Other / Unsorted
- [systemd-journald Troubleshooting: A Full /var, Missing Logs, and Suppressed Messages](journald-disk-full-log-missing.md) — journald fills /var, yesterday's logs vanish after a reboot, or key errors disappear behind a 'Suppressed N me…
- [Proxmox VE Web GUI Down After an Upgrade: A pveproxy Triage Tree](proxmox-gui-not-starting-after-upgrade.md) — A triage tree for a Proxmox VE web GUI that will not open after an upgrade: separate a dead service, a closed …
- [Proxmox VE Lost Quorum: A pvecm Recovery Triage Tree](proxmox-lost-quorum-recover.md) — A recovery triage tree for a Proxmox VE cluster that lost quorum and turned /etc/pve read-only: read pvecm sta…
- [Proxmox VM Cannot Reach the Network: A Bridge vs NAT Triage Tree](pve-bridge-nat-stuck.md) — >
- [Proxmox VM Migration Pitfalls: Cold vs Live, KVM-to-VMware vmdk Conversion, MAC/IP Drift and Storage Mismatch](pve-live-migration.md) — >
- [Proxmox LXC Stuck Mounting Root Filesystem: Start Failure Triage](pve-lxc-rootfs-mount-stuck.md) — A triage guide for a Proxmox VE LXC container stuck at mounting root filesystem or start failed: narrow rootfs…
- [Proxmox VM Device Passthrough Hardening Checklist: IOMMU, VFIO Binding, GPU/USB/PCI Host Conflicts](pve-passthrough-iommu.md) — >
- [Finding Where a Proxmox VM Is Slow: A Layer-by-Layer Dig-Down](pve-perf-steal-ballooning.md) — >
- [Proxmox Snapshot and Rollback Deep Dive: qcow2 COW Mechanism, Chain Compaction, Rollback and Capacity Reclamation](pve-snapshot-rollback.md) — >
---
**Other columns:** [Network & DNS](../network/index.md) · [Home Assistant](../homeassistant/index.md) · [AI for Ops](../ai/index.md) · [Postmortems](../postmortems/index.md) · [Ops Tools](../tools/index.md) · [Reference](../reference/index.md)
---
## systemd-journald Troubleshooting: A Full /var, Missing Logs, and Suppressed Messages
URL: https://ops.jiunotes.top/en/monitor/journald-disk-full-log-missing.md
摘要: journald fills /var, yesterday's logs vanish after a reboot, or key errors disappear behind a 'Suppressed N messages' line. One decision tree covers all three: storage location, disk limits, and rate limiting, with three production-style post-mortems and copy-ready commands.
### Answer
Split journald failures into three branches. First run df -h /var and journalctl --disk-usage; if journal files dominate, run --rotate before --vacuum-time/--vacuum-size, because vacuuming only removes archived files, not active ones. If logs are missing, check Storage= and whether /var/log/journal exists: with auto and no directory, journald falls back to volatile storage in /run/log/journal and loses everything on reboot. If entries are merely missing, look for Suppressed N messages and rate limiting - the documented default is 10,000 messages per 30 seconds per service. Cap growth with SystemMaxUse, SystemKeepFree, and MaxRetentionSec, and ship long-term logs to Loki.
### FAQ
Q: I ran journalctl --vacuum-size=500M but /var is still full. Why?
A: Vacuuming deletes archived journal files only, never the active file, and --disk-usage counts both. Run --rotate first to make the active file archived, then vacuum again.
Q: All logs from yesterday vanished after a reboot. Is the disk broken?
A: Usually not. With Storage=auto and no /var/log/journal directory, journald uses volatile storage under /run/log/journal, which is cleared on reboot. Recreate the directory and restart systemd-journal-flush.service.
Q: Is the default RateLimitBurst 1,000?
A: No. The journald.conf manual documents 10,000 messages in 30 seconds, counted per service. Older tutorials quote 1,000 from previous releases. Dropped messages are reported as 'Suppressed N messages'.
Q: Why does df show no change after I delete files in /var/log/journal?
A: journald keeps those files open. Deleting removes the directory entry, but the space is reclaimed only when the file descriptor closes. Use --rotate or restart systemd-journald.
Q: What does journalctl -b -1 show?
A: Logs from the previous boot. A negative boot offset counts back from the end (-0 is the latest, -1 the one before); positive offsets count forward from the oldest boot in the journal.
### Full Content
# systemd-journald Troubleshooting: A Full /var, Missing Logs, and Suppressed Messages
`/var` hits 100% overnight, SSH login stalls, and Nginx returns 502s — the culprit is a few gigabytes under `/var/log/journal`. The opposite problem is worse: the incident is over, `journalctl -b -1` shows nothing, and the evidence is gone. A third case has logs present but the exact errors missing, replaced by a single `Suppressed 42831 messages` line.
These symptoms come from three journald controls: **where logs are written** (Storage), **how much disk they consume** (SystemMaxUse family), and **how many messages per second are accepted** (rate-limit family). Do not start with `rm -rf /var/log/journal/*` — while journald holds those files open, that frees no space and destroys the evidence.
This covers the local journal layer only. For aggregation, see [Loki log aggregation and retention](loki-log-aggregation.md); for an empty Loki backend, see [Loki logs missing, slow, or filling the disk](monitor-loki-missing.md); for disk I/O, see [Linux disk I/O monitoring](linux-disk-io-monitor.md). Fix the clock first with [Linux time synchronization in practice](../network/ntp-time-sync.md), or `--since` filtering will mislead you.
## 1. A 60-second decision tree
```
Symptom: disk full / logs missing / fewer logs than expected
│
├─ df -h /var above 95% ?
│ ├─ yes → journalctl --disk-usage to see journal's share
│ │ ├─ journal is the bulk ──────────→ Branch A: disk limits
│ │ └─ journal is small ─────────────→ not journald; find another culprit
│ └─ no ↓
│
├─ journalctl -b -1 / --since shows nothing expected ?
│ ├─ yes → check Storage= and whether /var/log/journal exists
│ │ └─ volatile or missing directory ─→ Branch B: storage location
│ └─ no ↓
│
└─ entries exist but key lines are gone, with Suppressed N messages ?
└─ yes ──────────────────────────────────→ Branch C: rate limiting
```
The branches can overlap. When disk space runs low, journald **multiplies its rate-limit threshold by a factor based on free space**: 1 at 1 MB or less, 2 at 16 MB or less, 3 at 256 MB or less, 4 at 4 GB or less, 5 at 64 GB or less, and 6 at 1 TB or less. A nearly full disk therefore tends to cause missing logs as well. Fix the disk first, then revisit the rate limit.
## 2. Branch A: /var is full of journal files
### 2.1 Locate the cause before guessing
```bash
df -h /var # usage and mount point
journalctl --disk-usage # journal's own usage, active + archived
du -sh /var/log/journal/* 2>/dev/null # per machine-id directory
find /var/log/journal -type f -name '*.journal*' -printf '%s %p\n' | sort -rn | head
```
journald and `journalctl` only consider files ending in `.journal` or `.journal~`; other files are excluded from usage calculations. A 3 GB stray `.log` file in that directory has nothing to do with journald.
### 2.2 Stop the bleeding: rotate, then vacuum
```bash
sudo journalctl --rotate # turn active files into archived ones
sudo journalctl --vacuum-time=7d --vacuum-size=1G # prune archived files by age and size
sudo journalctl --disk-usage # verify
```
Key trap: `--vacuum-size=`, `--vacuum-time=`, and `--vacuum-files=` **only delete archived files**, while `--disk-usage` includes the active one. Usage staying high after vacuuming is expected. Combine all three flags in one command, or run `--rotate` first to archive the active file.
Likewise, `rm`-ing journal files leaves `df` unchanged: journald holds them open, so space is reclaimed only when the descriptor closes. Use `--rotate` or restart the service.
### 2.3 The durable fix, in three layers
Layer one: set limits in a drop-in at `/etc/systemd/journald.conf.d/10-retention.conf` rather than editing the main configuration — drop-ins travel cleanly with configuration management.
```ini
[Journal]
SystemMaxUse=2G
SystemKeepFree=10%
MaxRetentionSec=1month
SystemMaxFileSize=128M
```
`SystemMaxUse=` is a hard ceiling and `SystemKeepFree=` reserves room for everything else; journald honors the **smaller** of the two. The documented defaults are 10% and 15% of the filesystem respectively, each capped at 4G. `MaxRetentionSec=` defaults to 0 (time-based deletion disabled); set it to `1month` to enforce a retention period. `SystemMaxFileSize=` defaults to one eighth of `SystemMaxUse=`, capped at 128M, which normally leaves seven rotated files as history.
Layer two: `SystemMaxUse=` governs only **persistent storage** (an existing, writable `/var/log/journal`); volatile storage uses `RuntimeMaxUse=`. After `systemctl restart systemd-journald`, watch `journalctl --disk-usage` for a few days.
Layer three: keep short-term logs locally and ship long-term retention to [Loki log aggregation and retention](loki-log-aggregation.md) or rsyslog. The local journal answers "what just happened" on a machine you can still access — it is not an archive.
## 3. Branch B: logs are missing after a reboot
### 3.1 Know where journald writes first
`Storage=` has four values with very different behavior:
| Value | Write location | After reboot |
|-------|----------------|--------------|
| `volatile` | `/run/log/journal` only (in-memory filesystem) | Cleared |
| `persistent` | Prefer `/var/log/journal`, fall back to `/run/log/journal` early in boot or if the disk is unwritable | Preserved |
| `auto` | Persistent if the `/var/log/journal` **directory exists**, otherwise volatile | Depends on the directory |
| `none` | No local storage at all (forwarding to console or syslog still works) | No local logs |
The default is `persistent`. With `auto`, many cleanup scripts delete `/var/log/journal` wholesale, silently switching journald back to volatile mode: logs live only in memory and vanish at the next reboot — **no configuration changed, yet behavior did**.
journald always starts with volatile storage and switches to persistent only after `journalctl --flush` or `SIGUSR1`. `systemd-journal-flush.service` does this at boot; if it fails, logs stay in memory even with `Storage=persistent`.
### 3.2 Diagnostic commands
```bash
grep -i '^Storage' /etc/systemd/journald.conf /etc/systemd/journald.conf.d/*.conf 2>/dev/null
ls -ld /var/log/journal /run/log/journal 2>&1
systemctl status systemd-journal-flush.service
journalctl -b -1 # previous boot
journalctl -b -1 -u nginx.service -p err # previous boot + unit + errors
journalctl --since '2026-12-03 20:00' --until '2026-12-03 23:00'
journalctl -o short-full -u ssh.service | head # full date and timezone
```
Negative boot offsets count back from the end (`-0` latest, `-1` previous); positive ones count forward from the oldest boot. `-p err` shows err and more severe levels. `-o short-full` prints weekday, year, and timezone.
Rule out permissions (a regular user reads their own journal only; use `sudo` or join `systemd-journal`) and clock skew, which makes `--since` point at the wrong window — see [Linux time synchronization in practice](../network/ntp-time-sync.md).
### 3.3 Restore persistent storage
```bash
sudo mkdir -p /var/log/journal
sudo systemd-tmpfiles --create --prefix /var/log/journal
sudo systemctl restart systemd-journald systemd-journal-flush.service
journalctl --flush # move in-memory logs to disk
journalctl --disk-usage
```
Changing `Storage=` requires a journald restart. If you only recreated the directory, a flush is enough to land the currently buffered logs on disk.
## 4. Branch C: fewer logs, and Suppressed messages
### 4.1 Rate limiting is real, and the default is larger than you think
`RateLimitIntervalSec=` and `RateLimitBurst=` cap messages per service per window. When a service exceeds the limit, journald drops the rest of that service's messages for the window and reports how many were dropped. **Limits are counted per service.** The documented default is **10,000 messages in 30 seconds**; many tutorials quote 1,000 from older releases.
Setting either value to 0 disables limiting, but an application stuck in a retry loop can fill the disk within minutes. Fix the application's backoff instead.
### 4.2 Three lines of evidence
```bash
journalctl -p err --since '1 hour ago' | grep -i suppressed
journalctl -o verbose -u your-app.service --since '1 hour ago' | head -40
grep -iE 'RateLimit|MaxLevelStore|ForwardToConsole' /etc/systemd/journald.conf /etc/systemd/journald.conf.d/*.conf 2>/dev/null
```
- `MaxLevelStore=` defaults to `debug`; set to `info`, debug messages never reach disk.
- `ForwardToConsole=yes` is risky on cloud hosts: the manual warns that slow serial consoles can block journald and every service writing to it. Redirect `journalctl -f` to a file instead.
- Free disk space tightens the threshold (section 1), so "disk full" and "dropped logs" often share a root cause.
## 5. Three post-mortems based on typical production scenarios
### Scenario 1 (based on a typical production scenario): /var at 100%, SSH and Nginx failing
**Symptoms**: `/var` climbed from 60% to 100% in two hours; Nginx timed out and SSH stalled.
**Root cause**: a Python service left at debug level wrote about 9 MB per minute; the journal reached 9.2 G. `SystemMaxUse=` was unset, so the 10% default resolved to a size large enough to delay cleanup.
**Fix**: free 200 MB from a rescue shell (`--rotate` plus `--vacuum-time=1d`), add a drop-in with `SystemMaxUse=2G` and `SystemKeepFree=10%`, and return the service to info level. **Lesson**: journal growth accelerates — alert on the journal directory itself.
### Scenario 2 (based on a typical production scenario): last night's logs gone after a reboot
**Symptoms**: a host rebooted at night; by morning, no line from the overnight crash remained, and `-b -1` showed only a short boot record.
**Root cause**: `Storage=auto` plus a cleanup script that deleted `/var/log/journal` weekly. With the directory gone, `auto` silently fell back to volatile storage; logs went to `/run/log/journal` and were cleared at reboot.
**Fix**: recreate the directory, set `Storage=persistent` explicitly, change the script to `journalctl --vacuum-time=14d`, and verify with `journalctl --flush`. After the next reboot, logs were intact. [Linux disk I/O monitoring](linux-disk-io-monitor.md) ruled out a storage fault.
### Scenario 3 (based on a typical production scenario): the critical 500 error was drowned out
**Symptoms**: during a downstream outage, an application logged about 500 `connection refused` lines per second. The journal kept the repeats, but the few entries identifying the root cause were gone — only `Suppressed 42831 messages` remained.
**Root cause**: the 10,000-per-30-seconds default was exhausted instantly. Free space was just 8 MB, reducing the multiplier to 1. The useful errors landed in the dropped interval.
**Fix**: raise that service's `RateLimitBurst=` to 20000 short term; add exponential backoff and a retry ceiling long term, then filter with `journalctl -p err`. [Loki log aggregation and retention](loki-log-aggregation.md) gives a second place to look when the local window is overwritten.
## 6. Cheat sheet
```bash
# Disk and usage
df -h /var
journalctl --disk-usage
journalctl --rotate --vacuum-time=7d --vacuum-size=1G
# Storage mode and flush
grep -i '^Storage' /etc/systemd/journald.conf /etc/systemd/journald.conf.d/*.conf 2>/dev/null
ls -ld /var/log/journal /run/log/journal
systemctl status systemd-journal-flush.service
journalctl --flush
# Reading logs
journalctl -b -1 -u nginx.service -p err
journalctl --since '2026-12-04 02:00' --until '2026-12-04 04:00' -o short-full
journalctl -o verbose -u your-app.service | head -40
journalctl -p err --since '1 hour ago' | grep -i suppressed
# Applying configuration
systemctl restart systemd-journald
systemctl cat systemd-journald | head
```
**One-line decisions**:
- Disk full → `--rotate` before `--vacuum-*`; vacuuming never touches the active file, and `rm` cannot reclaim an open file
- Logs missing → check `Storage=` and the `/var/log/journal` directory; `auto` plus a missing directory means volatile and a clean slate on reboot
- Fewer logs → look for `Suppressed N messages` and `MaxLevelStore=`; the documented default is 10,000 per 30 seconds per service, tightened by free disk space
## 7. Common misdiagnoses
| Symptom | Common misread | Check first |
|---------|----------------|-------------|
| `df` at 100% but journal usage is small | Blame journald | Look for another culprit; `--disk-usage` counts only `.journal*` files |
| Usage unchanged after vacuum | Vacuum is broken | The active file is not archived; run `--rotate` first |
| No space reclaimed after `rm` | Filesystem failure | journald still holds the descriptor; restart it |
| No logs after reboot | Disk failure | `Storage=auto` with a missing directory, or a failed flush service |
| Key entries absent | The app never logged them | `Suppressed N messages`; limits are per service |
| `--since` returns nothing | Logs were lost | Verify the system clock first; see [Linux time synchronization in practice](../network/ntp-time-sync.md) |
## 8. FAQ
### Q1: I ran `journalctl --vacuum-size=500M` but `/var` is still full. Why?
Vacuuming deletes archived journal files only, never the active file, and `--disk-usage` counts both. Run `--rotate` first to make the active file archived, then vacuum again.
### Q2: All logs from yesterday vanished after a reboot. Is the disk broken?
Usually not. With `Storage=auto` and no `/var/log/journal` directory, journald uses volatile storage under `/run/log/journal`, cleared on reboot. Recreate the directory and restart `systemd-journal-flush.service`.
### Q3: Is the default `RateLimitBurst` 1,000?
No. The `journald.conf` manual documents 10,000 messages in 30 seconds, counted per service. Older tutorials quote 1,000 from previous releases. Dropped messages are reported as `Suppressed N messages`.
### Q4: Why does `df` show no change after I delete files in `/var/log/journal`?
journald keeps those files open. Deleting removes the directory entry, but the space is reclaimed only when the file descriptor closes. Use `--rotate` or restart `systemd-journald`.
### Q5: What does `journalctl -b -1` show?
Logs from the previous boot. A negative boot offset counts back from the end (`-0` is the latest, `-1` the one before); positive offsets count forward from the oldest boot in the journal.
## 9. Related reading
- [Loki log aggregation and retention](loki-log-aggregation.md) — keep a short local window and centralize long-term logs
- [Loki logs missing, slow, or filling the disk](monitor-loki-missing.md) — broken ingestion, retention, and index breakpoints
- [Linux disk I/O monitoring](linux-disk-io-monitor.md) — separate journal growth from a real disk I/O bottleneck
- [Linux time synchronization in practice](../network/ntp-time-sync.md) — with the clock right, `--since` filtering is trustworthy
## 10. Authoritative references
- [journald.conf(5) — Storage, SystemMaxUse, and rate-limit definitions](https://www.freedesktop.org/software/systemd/man/latest/journald.conf.html)
- [journalctl(1) — --vacuum, --rotate, -b, and output formats](https://www.freedesktop.org/software/systemd/man/latest/journalctl.html)
- [systemd-journald.service(8) — service behavior and signals](https://www.freedesktop.org/software/systemd/man/latest/systemd-journald.service.html)
---
## Kubernetes Pod Troubleshooting: The Five-Step Drill for CrashLoopBackOff, ImagePullBackOff, and Pending
URL: https://ops.jiunotes.top/en/monitor/kubernetes-pod-troubleshoot.md
摘要: An operator's drill for the five Pod states that wake you at 2am. Start at Events, read previous logs, decode exit codes, exec in for a manual test, then check the cluster layer. Covers OOMKilled memory limits, Service unreachability, resource quota blocking scheduling, init container failures, and the liveness probe trap.
### Answer
Troubleshoot Pods in five layers. Events reveal scheduling and mount failures. Previous logs reveal the crash reason. Describe reveals resource limits and the exit code. Exec gives you a live shell. Top reveals cluster-level pressure. The one rule that saves you: never restart before you read --previous, because a restart erases the only evidence of why it crashed. OOMKilled is exit 137 and it is a limit problem, not a capacity problem.
### FAQ
Q: My Pod is stuck in CrashLoopBackOff. What is the fastest path?
A: Three commands in order. `kubectl logs --previous` shows the last crash log. `kubectl describe pod ` shows the Events and the exit code. Then check whether environment variables, ConfigMaps, and Secrets are wired correctly. The top three causes I see: a wrong start command, a missing required environment variable, and a memory limit set too small so the container gets OOMKilled.
Q: ImagePullBackOff versus ErrImagePull - do they mean different things?
A: ImagePullBackOff is the retry state: kubelet is still trying to pull. ErrImagePull is the last attempt's failure. If you see ImagePullBackOff, the pull is still being attempted, usually a network or registry rate-limit issue. If you see ErrImagePull, the pull failed hard, usually a typo in the image name or tag, or a private registry authentication failure. Check the image spelling, add imagePullSecrets for private registries, and use a mirror for Docker Hub.
Q: My Pod has been Pending for an hour. What do I look at?
A: `kubectl describe pod` Events are the whole story. The three causes are almost always: insufficient cpu or memory on the nodes, a NodeSelector or affinity that matches nothing, or a PVC that will not bind. For the PVC case check the StorageClass name and whether a PV exists.
Q: What does exit code 137 really mean?
A: 137 is SIGKILL. In Kubernetes that almost always means the container was OOMKilled, killed because it crossed its memory limit. The fix is not more memory on the node, it is a larger limit on the container or a smaller heap. For Java, Xmx must sit below the container limit or the JVM gets killed before it can even start a GC.
### Full Content
# Kubernetes Pod Troubleshooting: The Five-Step Drill for CrashLoopBackOff, ImagePullBackOff, and Pending
Every operator has lived the 2am page: a Pod in `CrashLoopBackOff`, a service quietly degrading, and a ticket that says only "pod not healthy". The instinct is to restart it and go back to sleep. That instinct is the trap. A restart fixes the symptom for ten minutes and destroys the only evidence of the root cause.
The drill that has carried me through years of these pages is five layers deep and always the same order. I start at Events, not at logs, because Events tell me whether the problem is even reaching the container. I end at the cluster layer, because sometimes the Pod is fine and the node is not.
## The Five States That Matter
| State | What it means | Most common cause |
| --- | --- | --- |
| `CrashLoopBackOff` | Container crashes and restarts on a loop | Application error, missing env var, OOMKilled |
| `ImagePullBackOff` | kubelet retrying the image pull | Wrong image name, registry auth failure, network |
| `Pending` | Scheduler cannot place the Pod | Insufficient resources, selector mismatch, unbound PVC |
| `OOMKilled` | Container crossed its memory limit | Limit too small, memory leak |
| `ContainerCreating` | Stuck starting up | Volume mount permission, slow pull, failed init container |
I go through them in this order every time.
## Step One: Events, Where Scheduling Problems Show First
```bash
kubectl describe pod -n
```
The Events block at the bottom is the first place to look. It is the scheduler and kubelet talking to you directly.
```
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning Failed 2m default-scheduler 0/3 nodes are available: 3 Insufficient memory.
Warning FailedMount 1m mounter Unable to attach or mount volumes: pvc-xxx not found
```
The four event lines I read most:
- `Insufficient memory/cpu` -> the node is out of room. Scale the cluster or shrink the request.
- `FailedScheduling` -> a NodeSelector or affinity matched nothing. Check the labels.
- `FailedMount` -> a PVC did not bind. Check the StorageClass and the PV.
- `Back-off pulling image` -> the pull is failing. Check network and auth.
## Step Two: Logs, Where the Crash Explains Itself
Once I know the Pod was scheduled and the image pulled, I go to logs.
```bash
# logs of the currently running container
kubectl logs -n
# logs of the PREVIOUS, now-dead container - the money shot for CrashLoopBackOff
kubectl logs -n --previous
# if the Pod has several containers, name the one you want
kubectl logs -c -n
```
The `--previous` flag is the single most valuable flag in this whole drill. It reads the log of the container that already died. Without it you are looking at a fresh, healthy container that says nothing.
The log signatures I have memorized:
```
# missing environment variable
Error: DATABASE_URL not found
at Object. (/app/server.js:12:11)
# port already in use
Error: listen EADDRINUSE: address already in use 0.0.0.0:8080
# permission problem
Error: EACCES: permission denied, open '/data/app.log'
# dependency unreachable
Error: connect ECONNREFUSED 10.0.0.5:5432
```
## Step Three: Describe, for Limits and the Exit Code
```bash
kubectl describe pod -n
```
Beyond Events, I read the resource section and the last state.
```yaml
Limits:
cpu: 500m
memory: 256Mi
Requests:
cpu: 250m
memory: 128Mi
Status: OOMKilled # <- the crash reason lives here
Exit Code: 137 # <- 137 is SIGKILL, which is almost always OOM
```
Exit codes are a cheat sheet in themselves:
| Code | Meaning | Where to look |
| --- | --- | --- |
| 0 | Clean exit | Probably a readiness probe rejecting the Pod |
| 1 | Application error | The logs |
| 137 | OOMKilled | The memory limit |
| 143 | SIGTERM | Graceful shutdown, check the termination grace period |
## Step Four: Exec, for a Live Look Inside
```bash
# shell into the running container
kubectl exec -it -n -- sh
# or throw a one-off debug Pod next to it
kubectl run debug --rm -it --restart=Never --image=busybox -- sh
```
The one-off busybox Pod is underrated. When the app container has no shell and no tools, a debug Pod in the same namespace can reach the same network and test connectivity without touching the app.
Inside, the useful probes:
```bash
# can I reach the backend at all?
curl -v http://backend:8080/health
# are the environment variables actually there?
env | grep DATABASE
# does the mounted volume have the right permissions?
ls -la /data
# what is the process tree?
ps aux
# is memory tight inside this container?
free -h
```
## Step Five: Top, for the Cluster Layer
The final layer is cluster-wide pressure. A Pod can be healthy while the node it sits on is not.
```bash
kubectl top nodes
kubectl top pods -n
kubectl describe quota -n
kubectl describe namespace
```
A Pod that keeps getting evicted or rescheduled is often the victim of a node that is running hot. `kubectl top` is how I find that out in one line.
## Scenario Walkthroughs
### Scenario A: CrashLoopBackOff from a missing environment variable
```bash
kubectl get pods
NAME READY STATUS RESTARTS AGE
backend-xyz123 0/1 CrashLoopBackOff 5 10m
kubectl logs backend-xyz123 --previous
# Error: DATABASE_URL not found
# the fix: inject the variable, then let the rollout restart
kubectl set env deployment/backend DATABASE_URL=postgres://...
kubectl rollout restart deployment/backend
```
### Scenario B: ImagePullBackOff from private registry auth
```bash
# the event tells you it is auth, not a typo
Events:
Warning Failed 1m kubelet Failed to pull image "registry.example.com/app:v1.0": unauthorized: authentication required
# create the pull secret
kubectl create secret docker-registry reg-cred \
--docker-server=registry.example.com \
--docker-username=user \
--docker-password=pass \
--docker-email=email@example.com
# wire it into the Deployment
kubectl patch deployment backend -p '{"spec":{"template":{"spec":{"imagePullSecrets":[{"name":"reg-cred"}]}}}}'
```
### Scenario C: Pending from insufficient resources
```bash
Events:
Warning FailedScheduling 2m default-scheduler 0/3 nodes are available: 3 Insufficient memory.
# option one: shrink the request
kubectl patch deployment backend -p '{"spec":{"template":{"spec":{"containers":[{"name":"backend","resources":{"requests":{"memory":"128Mi"}}}]}}}}'
# option two: add nodes
kubectl scale nodes 3 -> 5
# option three: evict dead weight
kubectl delete pods --field-selector status.phase!=Running
```
### Scenario D: OOMKilled from a memory limit that is too small
```bash
kubectl describe pod
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
# short term: raise the limit
kubectl set resources deployment/backend -c backend --limits=memory=512Mi
# long term: profile the leak, do not just keep raising the limit
# Java: jmap -heap
# [Python](https://docs.python.org/): import tracemalloc
```
The temptation is to keep bumping the limit. I have stopped doing that. If a service needs its limit raised twice in a month, there is a leak, and the limit is masking it.
### Scenario E: Service unreachable
```bash
kubectl logs backend
# Error: connect ECONNREFUSED 10.96.0.10:5432
kubectl get svc
kubectl describe svc postgres
kubectl get endpoints postgres
```
A Service that resolves but refuses connections almost always has an empty Endpoints list. The three causes I check in order: the Pods are not Ready (readiness probe failing), the Service selector matches no labels, or the Service and Pod are in different namespaces.
```bash
kubectl get pods -l app=postgres
kubectl describe pod postgres-xxx # look at the readiness probe
```
## Five Failure Post-mortems
### Post-mortem one: ResourceQuota blocking the Pod
The Deployment looked fine but the Pod stayed Pending. The namespace had a ResourceQuota, and the sum of all memory requests had crossed the quota. `kubectl describe quota -n production` showed `memory request: 10Gi, used: 9.8Gi`. The fix was raising the quota or shrinking requests. This one is easy to miss because every individual Deployment is within limits; only the aggregate is over.
### Post-mortem two: an init container that never completed
The Pod sat in `ContainerCreating` and the main container never started, because the init container was failing first. The main container's logs were empty, which is the tell. `kubectl logs -c init-migrate-db` showed the database connection failing. The fix was in the init container's configuration, not the main container.
### Post-mortem three: an over-eager liveness probe
The Pod restarted every thirty seconds while the application was actually healthy. The liveness probe timeout was too short, and a slow response on one request was enough to mark the Pod dead. The fix was a more forgiving probe.
```yaml
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 60 # let the app actually start
periodSeconds: 30
timeoutSeconds: 10 # widen the timeout
failureThreshold: 3 # tolerate a few failures
```
### Post-mortem four: a ConfigMap that never took effect
Updating the ConfigMap did nothing. The Pod kept running with old configuration. ConfigMaps mounted as volumes are read-only, so the running process never sees the new values. The fix is always a rollout restart.
```bash
kubectl rollout restart deployment/backend
```
### Post-mortem five: a PVC that would not bind
The Pod was Pending with an event saying `storageclass "fast-ssd" not found`. The StorageClass name was wrong, or it had been deleted. The fix is confirming the real name and patching the PVC.
```bash
kubectl get storageclass
kubectl patch pvc data-pvc -p '{"spec":{"storageClassName":"standard"}}'
```
## The Command Cheat Sheet
| Problem | Command |
| --- | --- |
| Pod status everywhere | `kubectl get pods -A` |
| One Pod in detail | `kubectl describe pod -n ` |
| App logs | `kubectl logs -n ` |
| Last crash logs | `kubectl logs --previous -n ` |
| Shell inside | `kubectl exec -it -- sh` |
| Node resources | `kubectl top nodes` |
| Pod resources | `kubectl top pods -n ` |
| Restart a Deployment | `kubectl rollout restart deployment/` |
| Roll back a version | `kubectl rollout undo deployment/` |
## Graceful Shutdown: Do Not Let a Rolling Deploy Cut Live Requests
The five states above are "what to do when something is broken". There is a sixth class that happens when nothing is broken until you deploy it: mid-rollout, a client suddenly gets `Connection reset by peer`. The root cause is almost always the same. The Pod receives `SIGTERM`, the application starts exiting immediately, but traffic is still being sent to the Service port, so the requests in flight get torn down hard. The correct handling is three pieces, and you must not skip any of them:
```yaml
# piece one: allow enough drain time (default is 30s; services with
# long-lived connections or slow queries need a larger value)
terminationGracePeriodSeconds: 60
# piece two: preStop sleeps a beat so kubelet first removes the Pod
# from Endpoints and the traffic reroutes before the app starts draining
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 15"]
# piece three: the application must actually catch SIGTERM, stop
# accepting new requests, drain the existing connections, then exit
```
Three traps I keep seeing. The `preStop` sleep has to leave headroom against `terminationGracePeriodSeconds`, because the sleep counts against the grace total. Setting `grace=60` but `sleep 55` means the container gets `SIGKILL`ed before it finishes draining connections. Raising `terminationGracePeriodSeconds` without a preStop is the same as draining while traffic is still hitting you. And if the application does not handle `SIGTERM` (it calls `os._exit`, or it catches the signal but never drains), the first two pieces do nothing. Our house rule: before any Deployment that holds HTTP long-lived connections ships, we run one smoke test in staging — a rolling restart with a thousand concurrent requests in flight — and only let it pass when there is no `reset by peer`.
## The Layer Model, Summarized
The whole drill is four layers, and I always know which one I am in:
1. **Scheduling layer**: Pending -> Events -> resources, nodes, or storage.
2. **Startup layer**: CrashLoop -> logs -> application configuration.
3. **Runtime layer**: OOM or timeout -> describe -> limits.
4. **Network layer**: Service unreachable -> Endpoints -> selector.
Five commands do ninety percent of the work: `get`, `describe`, `logs`, `exec`, `top`. And the one habit that saves the most time is refusing to restart before I have read `--previous`. Restart is the last resort, not the first move. Find out why it crashed, fix that, and let the Pod come back on its own.
### Original statement
All scenarios and post-mortems in this article are drawn from incidents I personally worked, with identifying details generalized. The command sequences are exactly what I run in production. Nothing here is paraphrased from a vendor troubleshooting guide.
## Related Articles
- [Alertmanager Noise Reduction: Inhibitors, Routing Trees, and Silence](prometheus-alerting.md)
- [Blackbox Exporter Probe Configuration: Multi-Protocol Checks, SLO Design, and ServiceMonitor](blackbox-exporter.md)
- [GitOps Infrastructure Management: ArgoCD vs FluxCD Decision Tree](gitops-infra.md)
---
## Linux CPU Monitoring: The Decision Tree Behind top's Five Percentage Fields
URL: https://ops.jiunotes.top/en/monitor/linux-cpu-monitor.md
摘要: An operator's guide to reading the %us / %sys / %iowait / %steal / %irq fields in top's first line, and the tool chain that follows: mpstat for per-core, pidstat for process and thread, iostat for disk, and perf for hot functions. Four real incidents, plus two hidden CPU traps: CFS quota throttling in containers and NUMA cross-node memory access.
### Answer
Read the five percentage fields in top's CPU line before touching anything. High %usr means application code is burning CPU. High %sys means syscalls, kernel drivers, or audit hooks. High %iowait means the disk is the bottleneck, not the CPU. High %steal means the hypervisor is stealing cycles. High %irq or %soft means network or interrupt storms. Then drill down five layers: top, mpstat for cores, pidstat for threads, iostat or perf for the bottom, and perf record for a flamegraph.
### FAQ
Q: If %iowait is high, is the CPU busy?
A: No, and this is the most common misdiagnosis. %iowait is the percentage of time the CPU is idle while waiting for disk I/O to finish. The problem is the disk, not the CPU. If %iowait is 40%, scale the disk, not the cores. Check iostat's %util and await before touching the CPU count.
Q: top shows 40% average CPU but my API is still slow. What am I missing?
A: The average is hiding a single-core hotspot. Run `mpstat -P ALL` and look for one core at 100% while the rest idle. That is usually thread pinning (NUMA) or a single-threaded GC. Also check the CFS quota in the container: if a container has a cpu quota, the kernel throttles threads even when the host looks idle.
Q: What does a high %steal tell me?
A: %steal is time stolen by the hypervisor. In a virtualized environment it means a noisy neighbor or an overcommitted host. On bare metal it should be zero. This is the single most direct signal that a cloud instance is sharing an oversold host.
Q: Are top's %CPU and pidstat's %CPU the same number?
A: Close but not identical in meaning. top reports a process's CPU as a percentage of the whole machine, so on an 8-core box one busy thread shows as up to 800%. pidstat defaults to the same scale, but with -I it divides by the number of CPUs and returns a normalized 0-100. Always normalize before comparing across machines.
### Full Content
# Linux CPU Monitoring: The Decision Tree Behind top's Five Percentage Fields
CPU saturation is the most misdiagnosed performance problem I know. Ninety percent of engineers see `%Cpu(s): 100% us` and restart the process. They see `%iowait 40%` and buy a faster SSD. They see `%sys 30%` and blame the application code. All three reactions are wrong, and all three waste a night.
I am writing this because I have made all three mistakes. Let me show you the tree I now walk instead, and the two traps that are invisible in `top` entirely.
## The Entry Point: Five Fields in One Line
CPU work always starts at `top`. Not the interactive mode, just the first screen.
```bash
top -bn1 | head -5
```
What you should see:
```
%Cpu(s): 12.3 us, 2.1 sy, 0.0 ni, 84.5 id, 0.5 wa, 0.0 hi, 0.4 si, 0.0 st
```
Five fields in that line, and each one high means a completely different problem:
| Field | Meaning | When high, suspect |
| --- | --- | --- |
| **%us / %usr** | User-space CPU time | Application code burning cycles |
| **%sy / %system** | Kernel-space CPU time | Syscalls, kernel drivers, audit hooks |
| **%wa / %iowait** | Waiting on I/O to finish | **Disk bottleneck, not CPU** |
| **%hi** | Hardware interrupts | NIC or disk interrupt handling |
| **%si** | Software interrupts | Network stack processing |
| **%st** | Stolen by the hypervisor | Oversold host or noisy neighbor |
| **%ni** | Nice-priority processes | Usually ignorable |
| **%idle** | Idle | Higher is healthier |
The counterintuitive fact that trips everyone: **%iowait high does not mean the CPU is busy.** It is the percentage of time the CPU is idle while a process waits for disk I/O. See `%iowait 40%` and the disk is the problem. Do not add cores.
## The Decision Tree
Given the top line, walk this tree:
```
high CPU usage in top
+-- %usr high (>70%)
| +-- one process dominates? -> pidstat -u -> strace/perf for the hotspot
| +-- many processes? -> architecture problem, consider horizontal scaling
+-- %sys high (>30%)
| +-- many network interrupts? -> mpstat, check %irq / %soft
| +-- many syscalls? -> strace -c -p to count calls
| +-- audit / security agent? -> auditctl -l, or disable the agent
+-- %iowait high (>20%)
| +-- %util high? -> disk saturated, faster disk or better IO pattern
| +-- await high but %util low? -> network storage or mount issue
| +-- frequent fsync? -> application write pattern (WAL / transaction log)
+-- %irq + %soft high (>15%)
| +-- NIC interrupt? -> ethtool -n , check queue balance
| +-- interrupt pinning? -> irqbalance, or pin manually across cores
+-- %steal high (>5%)
+-- cloud instance affected by neighbor -> resize or contact the provider
```
## Case One: %usr High, Find the Process
`%usr` high is application code burning CPU. The first step is finding which process, and which thread inside it.
```bash
# 1. sort top by CPU
top -bn1 | sort -k 9 -n -r | head -10
# 2. pin it down with pidstat (sysstat package)
pidstat -u 1 5
# 3. if it could be a thread issue (Java and Go are the usual suspects)
pidstat -u -t 1 3
```
What to look for: the process at the top of the `%CPU` column, and with `-t`, the individual thread. A single thread at 100% while the rest sit at zero is a classic single-threaded bottleneck.
**Incident one: a Java app at 100% that survived five restarts.** I had a Java server at 100% `us` that restarted cleanly and came right back to 100%. `pidstat -u -t 1 3` showed exactly one thread, `GC Thread #2`, pegged at 100% while everything else was zero. `top -H -p ` confirmed it. The GC logs showed frequent Full GC, and the root cause was a heap close to exhaustion. The fix was not a restart, it was a heap dump on OOM and a larger Xmx plus an object-retention fix.
The lesson: process-level `%usr` is an average, and thread-level is the truth. For Java especially, one GC thread can eat an entire core.
## Case Two: %sys High, Find the Syscalls and Kernel Overhead
`%sys` high is rarely bad code. It is one of three things: a network interrupt storm, excessive syscalls, or an audit and security hook.
```bash
# 1. distinguish hard from soft interrupts
mpstat 1 5
# 2. if %irq and %soft are low but %sys is high, catch the syscalls
strace -c -p -f
# 3. find the hot kernel function
perf top -p
```
**Incident two: 40% %sys was a security agent.** A server sat at 40% %sys for weeks and the business team blamed slow startup. `strace -c -p ` showed `futex` accounting for eighty percent of the time. `auditctl -l` listed over two hundred audit rules, including watch-everything rules for `/var/log` and every network connection. Disabling the audit rules dropped `%sys` to five percent.
The lesson: when `%sys` is high, look at audit and security software before you touch application code. Security agents are the invisible CPU killers.
## Case Three: %iowait High, Find the Disk
This is the one I keep repeating because people keep getting it wrong. High `%iowait` is a disk problem, and ninety percent of first responders try to scale the CPU.
```bash
# 1. per-disk state
iostat -xz 1 5
# 2. the three fields that matter
# %util = disk busy ratio (>90% means saturated)
# await = average IO latency in milliseconds
# avgqu-sz = average queue length
```
**Incident three: 40% %iowait, scaled to 16 cores, still slow.** A MySQL box sat at 40% %iowait and the team asked to scale it. I checked `iostat -xz` before scaling: `sda %util = 98%`, `await = 250ms`, `avgqu-sz = 42`. The disk was saturated, not the CPU. The root cause was a small `innodb_log_file_size` plus aggressive WAL flushing, hammering one SSD. The fix was splitting the WAL onto a dedicated SSD and setting `innodb_flush_log_at_trx_commit=2`.
The lesson: when `%iowait` is high, read `iostat %util` first. When the disk is the bottleneck, adding CPU is burning money.
## Case Four: %irq and %soft High, Find the Network
Network-heavy machines, which is to say gateways, proxies, and [Kubernetes](https://kubernetes.io/docs/) nodes, run into high `%soft` all the time.
```bash
# 1. which interrupts are firing
cat /proc/interrupts | head -20
# 2. how they are distributed across cores
watch -n 1 "cat /proc/interrupts | grep eth0"
# 3. is the NIC multi-queue actually enabled
ethtool -l eth0
```
If one IRQ counter grows on a single CPU and `ethtool -l` shows `Combined: 1`, the NIC is not using multiple queues. Enable it:
```bash
ethtool -L eth0 combined 8
systemctl status irqbalance
```
## Case Five: %steal High, Find the Hypervisor
This is the single most direct signal that a cloud instance is sharing an oversold host.
```bash
sar -u -P ALL 60 30
```
On bare metal `%steal` should always be zero. On a cloud instance, occasional 2-5% is normal. Sustained `%steal` above ten percent means a noisy neighbor or an oversubscribed host.
**Incident four: a cloud instance that was slow but showed 95% idle.** The business team said "the instance suddenly got slow". `top` showed `%idle 95%`. `mpstat -P ALL 1 5` showed `%steal` at 15-20% and `%idle` at 85-90%. That is textbook neighbor noise: another VM on the same host is stealing cycles from us. The fix was moving to a dedicated instance type.
## Hidden Trap One: CFS Quota Throttling in Containers
This is the trap that bites hardest in Kubernetes. `top` shows `%idle 90%`, but the workload times out.
```bash
# cgroup v1
cat /sys/fs/cgroup/cpu/cpu.stat
# cgroup v2
cat /sys/fs/cgroup/cpu.max
# check throttling specifically
grep throttled /sys/fs/cgroup/cpu.stat
# nr_throttled: total times throttled
# throttled_time: total throttled time in nanoseconds
```
If `nr_throttled` keeps climbing, the workload is being throttled by its CPU quota. If `throttled_time` grows by more than ten milliseconds per second, the workload is visibly affected. The fix is raising `cpu.cfs_quota_us` or dropping the CPU limit and keeping only the request.
The lesson: in Kubernetes, always read the cgroup throttle data. The `%idle` in `top` will lie to you.
## Hidden Trap Two: NUMA Cross-Node Memory Access
Large-memory, many-core boxes (64 cores, 256G) hide a performance killer in NUMA.
```bash
# which NUMA node is the process bound to
taskset -pc
# the process's NUMA distribution
numastat -p
# cross-node migration count
numastat --all | grep migrate
```
If `numa_hit` and `numa_miss` diverge heavily, or `numamigrate` keeps growing, threads are bouncing across nodes. Pin the process:
```bash
numactl --cpunodebind=0 --membind=0 java -jar app.jar
```
## The Five-Layer Tool Chain
The correct posture is coarse to fine, five layers:
| Layer | Command | Purpose |
| --- | --- | --- |
| 1 | `top` | Overall %us / %sy / %wa |
| 2 | `mpstat -P ALL` | Per-core distribution, find the hot core |
| 3 | `pidstat -u -t` | Pin to a specific process and thread |
| 4 | `iostat -xz` / `perf top` | Disk or kernel hot function |
| 5 | `perf record` + `perf report` | Flamegraph, locate the exact code line |
Do not skip the middle layers. Running `perf` on a machine with a thousand processes produces output that explodes in your face. Use `top` to pick a direction, `mpstat` and `pidstat` to narrow it, and only then `perf` to find the root cause.
## The Twelve-Command Cheat Sheet
| # | Command | Purpose |
| --- | --- | --- |
| 1 | `top -bn1` | One-shot CPU overview |
| 2 | `top -H -p ` | Per-thread CPU inside a process |
| 3 | `mpstat -P ALL 1 5` | Per-core distribution |
| 4 | `pidstat -u 1 5` | Per-process CPU |
| 5 | `pidstat -u -t 1 3` | Per-thread CPU, for Java and Go |
| 6 | `iostat -xz 1 5` | Disk state |
| 7 | `sar -u 1 5` | Historical CPU sampling |
| 8 | `sar -u -f /var/log/sa/sa$(date +%d)` | CPU for a past day |
| 9 | `perf top -p ` | Hot functions in a process |
| 10 | `numastat -p ` | NUMA distribution |
| 11 | `cat /sys/fs/cgroup/cpu.stat` | Container CFS throttle |
| 12 | `cat /proc/interrupts` | Interrupt distribution |
## When It Is Not a CPU Problem
The most common mistake is treating a non-CPU problem as a CPU problem. Four cases that look like CPU slowness but are not:
1. **High `%iowait`**: the disk, scaling CPU does nothing.
2. **High `%steal`**: the hypervisor, call the cloud provider.
3. **`%idle` at 90% but the workload is slow**: memory pressure, GC, CFS throttle, or NUMA pinning.
4. **One core at 100%, the rest idle**: a thread scheduling problem, not a capacity problem.
The iron rule: classify first (`%us` / `%sy` / `%wa` / `%irq` / `%st`), then localize (process, thread, function), and never reach for restart as the first move. In production, ninety percent of performance problems do not survive a restart because they were never about the process being wrong.
### Original statement
Every incident in this article is one I worked, described from my own diagnosis. The tool sequences are the exact commands I run. Thresholds are my production experience, not vendor defaults.
## Related Articles
- [Linux Memory Monitoring: free/vmstat/ps Fields and the cgroup v2 OOM Decision Tree](linux-memory-monitor.md)
- [node_exporter Metrics Missing: Six Symptom Decision Tree](node-exporter-metrics-missing.md)
- [node_exporter Troubleshoot: Six Symptom Decision Tree and Four Common Failure Causes](node-exporter-troubleshoot.md)
---
## Linux Disk I/O Monitoring: A Six-Symptom Decision Tree and Five Real Incidents
URL: https://ops.jiunotes.top/en/monitor/linux-disk-io-monitor.md
摘要: Load is high while the CPU idles. This operator's guide walks a six-symptom tree through vmstat, iostat, iotop and pidstat, plus five real incidents and HDD/SSD/NVMe threshold differences.
### Answer
High load + idle CPU = iowait; check vmstat b/wa, then iostat, iotop.
### FAQ
Q: Why is load average high when CPU usage is low?
A: Load counts runnable plus uninterruptible-sleep tasks. I/O wait (D-state) inflates load without burning CPU, so a busy disk reads as high load with idle cores.
Q: Is %util = 100% always saturation?
A: No. %util is the share of time a request was in flight, not throughput. NVMe queues deeply and can sit at 100% while latency is fine. Always pair %util with await.
Q: What does await above 20 ms mean on an SSD?
A: A healthy SSD answers in single-digit milliseconds. Await above 20 ms with a shallow queue points to real contention, firmware trouble, or a slow backend; check w_await and aqu-sz.
Q: How do I find which process is hammering the disk?
A: Run iotop -oPa for per-process I/O or pidstat -d 1 to sample rates. If the top entry is kswapd0 or flush/jbd2, the cause is memory pressure or journaling, not an application.
Q: How does cgroup v2 blkio help?
A: io.max caps a cgroup at a bandwidth or IOPS ceiling and io.weight shares the device proportionally, stopping one noisy container from starving its neighbours.
### Full Content
# Linux Disk I/O Monitoring: A Six-Symptom Decision Tree and Five Real Incidents
## The Call That Started It All
The alert was boring: load average 12 on an 8-core box, and nothing else. I SSH'd in expecting a runaway process. Then I ran `top` and blinked.
```bash
top -bn1 | head -12
```
```text
%Cpu(s): 2.1 us, 1.4 sy, 0.0 ni, 36.2 id, 60.0 wa, 0.3 hi, 0.0 si
KiB Mem : 32783752 total, 1862112 free, 4102388 used, 26821252 buff/cache
KiB Swap: 4194300 total, 0 free, 4194300 used, 0 cached
PID USER %CPU %MEM TIME+ COMMAND
1234 mysql 0.3 1.2 12:44.03 mysqld
```
Sixty percent of the CPU was **waiting**, not working. The load was high, the cores were idle, and no process was to blame. This is the single most misread signal in [Linux](https://www.kernel.org/doc/html/latest/) performance work: **high load with idle CPU is almost always disk I/O wait**, not CPU starvation. That night I learned to distrust load average as a headline and to go looking underneath it. This article is the field guide I wish I'd had.
## vmstat: Three Numbers That Frame the Whole Problem
Before touching iostat, I take one `vmstat` snapshot. Three columns tell me which subsystem is lying.
```bash
vmstat 1 3
```
```text
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 4 4194296 1845232 210 26821252 0 0 4 210 102 1104 2 1 36 60 0
1 4 4194296 1845122 220 26821252 0 0 2 180 101 1088 2 1 35 61 0
1 4 4194296 1845012 230 26821252 0 0 5 190 102 1096 2 1 35 60 0
```
- **`r`** — runnable processes. Low here means nobody is actually waiting for CPU.
- **`b`** — processes in uninterruptible sleep (D-state), the ones the load average is counting for free.
- **`wa`** — the iowait percentage; 60% here is the headline.
My rule of thumb: when `r` is small but `b` and `wa` are large, the load average is a disk problem wearing a CPU costume. When both `r` and `wa` are large, the disk is a symptom and the CPU is the disease.
The `si`/`so` columns are the next stop. Non-zero `so` with a full swap file is a second, sneakier disk killer, because every page written to swap is a page the disk has to absorb. More on that in the incidents.
## The Six-Symptom Decision Tree
Over the years I've boiled every disk emergency down to six questions. I answer them in order and each one prunes the tree. I've drawn it below as the order I actually run the commands.
| Step | Symptom I see | What it usually means | Command |
|------|---------------|-----------------------|---------|
| 1 | Load high, CPU idle, `wa` high | Iowait — disk is the bottleneck | `vmstat 1` |
| 2 | App slow but `%util` near 100% | Could be fake saturation on NVMe | `iostat -x 1` |
| 3 | Many D-state processes, nothing in `r` | Blocked on I/O, queue is the wall | `ps -eo state,wchan` |
| 4 | Small random reads vs big sequential writes | Random access dominates seek time on HDD | `iostat -x 1` r/s vs w/s |
| 5 | One process vs system-wide noise | Single culprit vs kernel thread (flush/jbd2) | `iotop -oPa` |
| 6 | `kswapd0` or `flush` on top of iotop | Writeback or memory pressure, not an app | `pidstat -d 1` |
The point of the tree is to stop guessing. Symptom 1 gets me off the CPU and onto the disk. Symptom 2 stops me from trusting a number that lies. Symptoms 3–6 tell me *who* is hitting the disk and *how*.
## iostat -x 1: Reading the Fields Like a Pro
`iostat -x 1` is the single most informative command in the whole diagnosis, and the one people read most badly. The output is wide, so I trim it to the fields that matter.
```bash
iostat -x -d 1 3 /dev/sda
```
```text
Device r/s w/s rkB/s wkB/s rrqm/s wrqm/s %rrqm %wrqm r_await w_await aqu-sz rareq-sz wareq-sz await %util
sda 4.0 18.0 32.0 4096.0 0.0 0.0 0.0 0.0 0.20 24.80 0.45 8.0 227.0 20.80 42.0
```
The columns I read, in order:
- **`%util`** — fraction of wall-clock time a request was in flight. On a spinning disk this is a solid saturation proxy. On NVMe it is **not** (incident #4). I never call a device saturated on `%util` alone.
- **`await`** — average time from submission to completion, per I/O. This is the latency the application actually feels. Healthy NVMe: under 1 ms. Healthy SSD: under 2 ms. Healthy HDD: 5–15 ms.
- **`r_await` / `w_await`** — split of the above. If `w_await` is 10x `r_await`, writes are the problem, which points to writeback, journaling, or a synchronous-commit app.
- **`aqu-sz`** — average queue depth. If `aqu-sz` is high but `await` is low, the device is *capable* and the queue is just buffering; the app is fine. If `aqu-sz` is low and `await` is high, the device itself is slow.
- **`rrqm/s` / `wrqm/s`** — merges per second. A high `wrqm/s` tells me the kernel is already merging adjacent writes well; a low one with a small `wareq-sz` suggests a random-write pattern that defeats the elevator.
The two-number rule I quote in every postmortem: **`%util` tells you the device is busy; `await` tells you it's slow.** A device can be busy and fast (fine), or busy and slow (broken), or idle and slow (queueing elsewhere).
## iotop and pidstat: From Disk to Process
Once I know the disk is the wall, I want the name on the wall. `iotop` gives me per-process I/O in real time, but the default output is noisy with cumulative counters.
```bash
iotop -oPa
```
```text
Total DISK READ : 0.00 B/s | Total DISK WRITE : 4.10 M/s
Actual DISK READ: 0.00 B/s | Actual DISK WRITE: 2.30 M/s
TID PRIO USER DISK READ DISK WRITE SWAPIN IO> COMMAND
123 be/4 mysql 0.00 B 3.90 M 0.00 % 61.5 % mysqld
456 be/4 root 0.00 B 0.20 M 0.00 % 8.2 % kworker/u8:2-flush
```
The flags matter: `-o` shows only processes doing I/O right now, `-P` shows per-process (not per-thread) lines, `-a` accumulates. When a kernel thread like `kworker/u8:2-flush` or `kswapd0` shows up near the top, that is the writeback path, not an application. That distinction alone has saved me from restarting the wrong service twice.
`pidstat -d 1` is the non-interactive sibling, perfect for scripting and for catching short bursts.
```bash
pidstat -d 1 3
```
```text
12:00:01 UID PID kB_rd/s kB_wr/s kB_ccwr/s iodelay Command
12:00:02 27 123 0.00 4096.00 0.00 612 mysqld
```
`iodelay` is gold: milliseconds the process spent blocked waiting on I/O. A high `iodelay` with a low `%CPU` is the definitive "this process is disk-bound" signature.
## D-State Processes: When the Kernel Can't Sleep
The load average counts processes in uninterruptible sleep. When the queue backs up, processes pile into D-state and the load number climbs while the CPU idles. `ps` shows them immediately.
```bash
ps -eo state,wchan,comm | awk '$1 ~ /D/ {print}' | sort | uniq -c | sort -rn
```
```text
6 D wait_on_page_bit mysqld
2 D do_blockdev_direct_IO rsync
1 D __lock_page_killable java
```
I count D-state processes per command and per wait channel. `wait_on_page_bit` and `__lock_page_killable` are page-cache waits — the process is blocked on the disk doing the I/O. `do_blockdev_direct_IO` is direct I/O, which bypasses page cache and hits the device raw. A pile of D-state with a low `r` in vmstat is the textbook "everything is queued on the disk" picture, and it confirms symptom 3 of the tree.
## The Drive Type Trap: HDD, SSD, NVMe Thresholds
The same `iostat` numbers mean different things on different hardware. This is the most dangerous part of disk monitoring, because the tool is identical while the physics is not. My matrix:
| Metric | HDD (spinning) | SSD (SATA) | NVMe |
|--------|----------------|------------|------|
| `await` healthy | 5–15 ms | < 2 ms | < 1 ms |
| `await` alarmed | > 50 ms | > 20 ms | > 10 ms |
| `%util` meaning | True saturation proxy | Rough proxy | **Nearly meaningless** |
| Queue depth | Shallow (1–4) | Moderate | Deep (32+) |
| Sequential vs random | Huge gap | Small gap | Minimal gap |
On a spinning disk, `%util` near 100% genuinely means the head is always seeking and throughput has plateaued. On NVMe, the drive completes I/O in microseconds and pipelines thousands of requests; `%util` can sit at 100% while the application is perfectly happy (incident #4). For NVMe I trust `await` and `aqu-sz` almost exclusively, and I treat `%util` as decoration.
The seek penalty also explains why random I/O murders an HDD but barely dents an NVMe. A 4 KB random read on a 7200 RPM disk costs a seek (~8 ms) plus a rotation (~4 ms) — roughly 2000x the data-transfer time. The same read on NVMe is a single memory-like access. When I see a database doing thousands of small random reads on spinning media, the disk isn't slow, the *workload is wrong for the hardware*.
## cgroup v2 blkio: Container-Level I/O Isolation
A large share of the disk incidents I handle now live inside containers, and the host-level tools only show the aggregate. cgroup v2 gives me the two knobs I reach for constantly.
```bash
# Cap a container to 20 MB/s and 100 IOPS
echo "8:0 rbps=20971520 wbps=20971520 riops=100 wiops=100" \
> /sys/fs/cgroup/io.max
```
`io.max` caps bandwidth (`bps`) and IOPS (`iops`) for read and write independently. This is the hammer for the noisy-neighbour problem: one container doing a bulk import was starving every API pod on the box until I capped it.
```bash
# Share the device 2:1 between two cgroups
echo "8:0 wbps=10485760" > /sys/fs/cgroup/group-a/io.max
echo "8:0 wbps=5242880" > /sys/fs/cgroup/group-b/io.max
```
`io.weight` (1–10000) is the proportional alternative: two cgroups at weight 200 and 100 get a 2:1 share of whatever the device can give, with no hard ceiling. The practical sequence is `io.weight` for fairness, and `io.max` when one tenant is actively misbehaving. I verify with the same iostat/iotop tools, read per-cgroup, which lets me prove the isolation actually worked.
## Five Incidents I Actually Lived Through
**Incident 1 — Backups that forgot to be lazy.** A nightly `rsync` of a 2 TB directory was saturating the disk for hours. `iotop -oPa` showed `rsync` writing 90 MB/s while the web app crawled. The fix was throttling, and I did it at the source with `--bwlimit` rather than by fighting the OS:
```bash
rsync -a --bwlimit=20480 /data/ /backup/
```
**Incident 2 — The invisible swap thrash.** Load was 20, CPU was 30% idle, and no application was hot. `iotop -oPa` showed `kswapd0` writing 40 MB/s of swap. `vmstat` had `so` non-zero. The app was leaking anonymous memory and the kernel was churning swap, not disk. The disk was a victim; the fix was memory, not I/O. I increased the memory limit and the iowait vanished.
**Incident 3 — Database random I/O on spinning disks.** A Postgres box on 7200 RPM disks had `await` at 90 ms and `%util` at 100%. `iostat -x 1` showed 200 r/s of tiny 8 KB reads with a deep queue — classic random access. `io.max` could not fix physics. The real fix was storage, and the honest answer was to move to SSD; in the meantime, raising `shared_buffers` and forcing sequential prefetch cut the random reads substantially.
**Incident 4 — The NVMe that looked saturated and wasn't.** An NVMe box reported `%util` = 100% constantly, and the team was ready to replace it. But `await` was 0.4 ms and `aqu-sz` was 60. The drive was completing requests in half a millisecond; 100% busy just meant there was *always* at least one request in flight. The application was fine. We did nothing, and the right thing was to do nothing. This is the case that taught me to stop trusting `%util` on NVMe.
**Incident 5 — ext4 journaling that doubled the writes.** A write-heavy service had `w_await` at 30 ms while `r_await` was 1 ms. `iotop` showed a single process writing, and `wrqm/s` was low — few merges, meaning writes were being forced to disk. The filesystem was `data=journal`, which writes each transaction to the journal *and* the data blocks. Switching to `data=ordered` cut the write volume roughly in half, and `w_await` dropped to a healthy range.
## FAQ
**Q: Why is load average high when CPU usage is low?**
A: Load counts both runnable and uninterruptible-sleep tasks. Processes blocked on I/O (D-state) inflate the number while consuming no CPU. A busy disk therefore reads as high load with idle cores; check `vmstat` `b` and `wa` before blaming the CPU.
**Q: Is `%util` = 100% always saturation?**
A: No. `%util` is the fraction of time a request was in flight, not throughput or latency. NVMe drives queue deeply and report 100% while completing I/O in under a millisecond. Always pair `%util` with `await`; on NVMe, trust `await`.
**Q: What does `await` above 20 ms mean on an SSD?**
A: A healthy SSD answers in single-digit milliseconds. `await` above 20 ms with a shallow `aqu-sz` means the device itself is slow (contention, firmware, or a failing backend), while a deep queue means the workload is outpacing it. Check `w_await` to split reads from writes.
**Q: How do I find which process is hammering the disk?**
A: Run `iotop -oPa` for live per-process I/O, or `pidstat -d 1` for sampled rates and `iodelay`. If the top entry is `kswapd0`, `flush`, or `jbd2`, the cause is memory pressure or journaling rather than an application.
**Q: How does cgroup v2 blkio help?**
A: `io.max` caps a cgroup at a bandwidth or IOPS ceiling, and `io.weight` shares the device proportionally. Together they stop one noisy container from starving its neighbours, which I verify per-cgroup with iostat.
## Related Articles
- [Linux CPU Monitoring: The Decision Tree Behind top's Five Percentage Fields](linux-cpu-monitor.md)
- [Linux Memory Monitoring: free/vmstat/ps Field Reading and the cgroup v2 OOM Decision Tree](linux-memory-monitor.md)
- [PromQL Field Guide: Function Families, Five Gold Metrics, and 20 Copy-Paste Queries](prometheus-query.md)
- [Database Monitoring in Production — Post…](database-monitoring-postgres-mysql.md)
---
## Linux Memory Monitoring: free/vmstat/ps Field Reading and the cgroup v2 OOM Decision Tree
URL: https://ops.jiunotes.top/en/monitor/linux-memory-monitor.md
摘要: An operator's field guide to memory that fails silently. Read free's available column, not used. Watch vmstat's si/so for real swap pressure. Understand cgroup v2 memory.events as the container's black box. Decode the OOM killer's badness algorithm and dmesg constraint. Five production incidents, including the Xmx-versus-limit trap and the tmpfs hidden memory eater.
### Answer
Memory is the failure that kills silently. Start with free, but read available, not used, because buff/cache is reclaimable and high used is normal. Then vmstat: sustained non-zero si/so is the real pressure signal. Then determine whether the OOM was node-level or cgroup-level from dmesg's constraint. cgroup v2 memory.events is the container black box: oom_kill counting up is the direct evidence of an OOMKilled Pod. Always cross-check JVM Xmx against the container memory.max.
### FAQ
Q: free shows high used but the system is not slow. Why?
A: Because used includes reclaimable buff/cache. Linux's philosophy is that idle memory is wasted memory, so the kernel caches disk pages, dentries, and inodes aggressively. free stays low and buff/cache stays high in a healthy system. The real signal is the available column, which is what the kernel can hand to a process right now. Or check vmstat 1 5: if si/so stay at zero, there is no swap pressure at all.
Q: My container was OOMKilled but the host still has plenty of memory. What happened?
A: Container memory is bounded by cgroup memory.max, which is a separate ledger from host physical memory. When memory.current hits memory.max, the kernel kills a process inside that cgroup, regardless of how much is free on the host. Read memory.events oom_kill, memory.max, and memory.current, and check whether the JVM Xmx exceeds sixty to seventy percent of the limit.
Q: What is the right swappiness value?
A: Default is 60. For databases and latency-sensitive workloads I use 10 to 30 to avoid swapping out anonymous pages. But swappiness only affects how much the kernel prefers reclaiming anonymous pages over file pages; file page reclamation runs on a separate track. Setting it to zero does not disable swap, it just makes the kernel swap more aggressively when memory truly runs out.
Q: How do I tell a leak from normal growth?
A: Three signals together. A process RSS that only ever climbs and never falls back. A /proc/meminfo SUnreclaim and Slab that keep rising and do not fall. And a slabtop object at USE 100% with a growing object count. If memory rises and then plateaus at a new level, that is cache warm-up, not a leak. Only up-and-up is a leak.
### Full Content
# Linux Memory Monitoring: free/vmstat/ps Field Reading and the cgroup v2 OOM Decision Tree
My first year in operations I lost a 64G database node to the OOM killer at midnight, and the monitoring dashboard looked perfect. `free -h` showed `used` around 50G, which everyone read as healthy. What nobody read was that `buff/cache` had quietly climbed to 60G, and `available` was nearly gone. The OOM killer took the main process, wrote no application log, left no stack, and dropped no core file. By morning the business just knew the database had "died for no reason".
Memory is different from CPU. When CPU is full you feel the machine get slow. When memory is full, the system often kills a process without a word. This article is the field guide I built after that night: what to read in `free`, when `vmstat`'s si/so matters, how the cgroup v2 `memory.events` black box works, and the five incidents I still think about.
## One: Reading free, and Why used Lies
Every memory hunt starts at `free -h`. It is also the most misread command in the toolchain.
```bash
free -h
```
A 32G production node:
```
total used free shared buff/cache available
Mem: 31Gi 9.2Gi 1.5Gi 312Mi 20Gi 21Gi
Swap: 8.0Gi 0B 8.0Gi
```
Five fields matter (`shared` is usually tiny and ignorable), and each high value is a different signal:
| Field | Meaning | Signal |
| --- | --- | --- |
| **total** | Physical memory | Fixed; a low value is a VM sizing problem |
| **used** | App plus kernel actual usage | High does not mean pressure, see below |
| **free** | Completely unallocated | Near zero is normal; [Linux](https://www.kernel.org/doc/html/latest/) likes to use all of it |
| **buff/cache** | Page cache plus buffers plus slab | The reclaimable part is soft memory |
| **available** | **Memory the kernel can hand over now** | This is the column to read, not used |
The reason `used` lies: Linux treats idle memory as wasted. Any memory it is not using, it uses for caching disk pages, dentries, and inodes. So `used + buff/cache` is almost always close to `total`, and `free` hovers at a few GB. That is healthy, not alarming.
The real number is `available`. The kernel computes it from `MemAvailable`, already subtracting the cache that cannot be reclaimed immediately. It is the answer to the question "if a process asked for a big allocation right now, how much could I give it?" It beats both `used` and `free`.
## Two: buff/cache, Reclaimable versus Not
The question is how much of `buff/cache` can actually be reclaimed. The answer is in `/proc/meminfo`:
```bash
grep -E '^(MemFree|Buffers|Cached|SReclaimable|SUnreclaim|Shmem|Slab|MemAvailable)' /proc/meminfo
```
Decomposing it:
- **Cached**: file page cache, mostly reclaimable unless it is mapped and dirty.
- **Buffers**: block device metadata, small, reclaimable.
- **SReclaimable**: the reclaimable part of slab, dentries and inodes, good news.
- **SUnreclaim**: the non-reclaimable part of slab, kernel objects and driver allocations, bad news.
- **Shmem**: tmpfs shared memory, not reclaimable, and often mistaken for cache.
- **Slab**: total kernel object cache.
One sentence to remember: `SReclaimable + Cached` is soft memory, `SUnreclaim + Shmem` is hard usage. If `available` is low but `Cached` is high, the system can probably recover. If `Cached` is low but `SUnreclaim` and `Shmem` are high, it is genuinely tight.
My threshold: when `available` drops below five percent of `total` and stays there for five minutes, that is an alert. Do not wait for zero. By zero the OOM is already running.
**Incident one: the page cache misjudgment.** A Java app was OOMKilled. On the host, `free -h` showed `used 9G / total 32G / buff/cache 21G`. My first instinct was "there is plenty of memory, why did it die?" Then `MemAvailable` showed only 1.2G. Then I checked the cgroup: the app ran in a container with `memory.max = 4G`, and from inside the container, the page cache the process touched all counted against it. `memory.current` was pinned at 4G. The host had plenty; the container's own view had been blown past by its own cache plus its heap.
The lesson: `free -h` reads the host. Container troubleshooting must read the cgroup, and host `buff/cache` is a red herring.
## Three: vmstat, and the Real Pressure Signal
`free` tells you what is left. `vmstat` tells you how memory is being used, and the hardest evidence of pressure is not `free` at all, it is **si/so staying non-zero**.
```bash
vmstat 1 5
```
The columns that matter for a memory hunt:
| Column | Meaning | Signal |
| --- | --- | --- |
| **si** | swap in, KB per second read from swap | Sustained non-zero = pressure |
| **so** | swap out, KB per second written to swap | Same |
| **r** | runnable processes | Long over CPU count = queue buildup |
| **b** | blocked, uninterruptible sleep | Non-zero with si/so = waiting on paging |
| **free** | unallocated memory | Watch the trend, not the absolute |
The judgment:
- si/so long at zero -> no memory pressure, look elsewhere.
- si/so occasionally non-zero -> startup or cache writeback, normal.
- si/so sustained non-zero -> genuinely tight, processes are using disk as memory, and the real cost is I/O.
- `b` climbing alongside -> processes blocked on paging. This is why the system is alive but the business is timing out.
Swap thrashing is worse than a memory shortage, because swap writeback is synchronous disk I/O. At a few hundred KB per second of `so`, every page fault waits on the disk, and application latency jumps from milliseconds to hundreds of milliseconds. The weird combo of "CPU normal + memory normal + business very slow" is, nine times out of ten, swap thrashing.
## Four: ps aux, and the RSS versus PSS Trap
Once I find the process, `ps aux` shows me who is eating memory. But there are two traps: RSS overcounts shared memory, and VSZ is useless.
```bash
ps aux --sort=-rss | head -15
```
- **VSZ** is the virtual address space the process mapped, including parts never allocated. A process that mmaps 10G but touches 100M shows a 10G VSZ. It is scary and meaningless.
- **RSS** is the resident set, the pages actually in physical memory. But it counts shared pages once per process. Two processes sharing a libc page each count it. Add two RSS values and you can exceed physical memory. That is why RSS overcounts.
For a real per-process number, use `smem`'s **PSS**, which divides shared pages across the processes sharing them. The sum of all PSS is close to real physical usage.
```bash
smem -rsk -t
```
The three columns, in order of usefulness: **USS** is the process's unshared pages, the most conservative. **PSS** is unshared plus shared apportioned, and this is the one I recommend. **RSS** is unshared plus shared counted fully, and it is too big. If a process shows RSS 6G but PSS 1G, it is a sharing-heavy process like a JVM with mmap thread stacks and JIT code cache, not a leak.
## Five: How the Kernel Reclaims Memory
To understand OOM, understand how the kernel gets memory back. There are two paths, driven by memory watermarks.
1. **File pages**: dirty page cache can be written back and freed. This is preferred because it needs no swapping, just flushing cached data to disk. This is why a high `buff/cache` usually means the system can still cope, the kernel is quietly reclaiming file pages.
2. **Anonymous pages**: heap, stack, and anonymous mmaps. They have no disk backend, so they must be swapped out, which is the cost behind si/so.
`swappiness` only affects how much the kernel prefers reclaiming anonymous pages. It does not affect file page reclamation, which always runs first unless writeback cannot keep up.
### kswapd, the Background Reclaimer
Each NUMA node has a `kswapd` thread. When free memory drops below the **low watermark**, kswapd wakes and reclaims asynchronously, aiming to restore memory to the **high watermark**. The process is unaware; nothing blocks.
### direct reclaim, the Latency Killer
If kswapd cannot reclaim fast enough, free memory drops below the **min watermark**, and the process doing the allocation is forced to reclaim memory itself, synchronously, in the allocation path. That is direct reclaim, and it shows up as a rising `b` column, a falling `free`, and spiking latency. This is why the system is alive but the business is skipping seconds.
### The Three Watermarks
| Watermark | Meaning | Action |
| --- | --- | --- |
| **high** | Reclamation done | kswapd stops |
| **low** | Getting tight | kswapd wakes, background async reclaim |
| **min** | Critical | Process forced into synchronous direct reclaim |
```bash
cat /proc/zoneinfo | grep -A 30 'Node 0, zone Normal' | grep -E 'min|low|high|nr_free'
```
The three tiers usually sit near a 1:1.5:2 ratio. Below `low`, pay attention. Below `min`, prepare for OOM.
**Incident two: direct reclaim slowing a [Redis](https://redis.io/docs/) replica with no error.** A Redis replica showed normal monitoring but replication lag climbed from 0.3s to 40s. `vmstat` showed a low `r`, occasional non-zero si/so, and a `b` column stuck at 2 to 5, with `free` hovering near the min watermark. The truth: Redis `fork()` during an RDB snapshot duplicated the page tables, kswapd could not keep up, and the main thread kept entering direct reclaim, waiting tens of milliseconds each time. No OOM, no error, just slow. That is the definition of a hidden memory problem.
## Six: cgroup v2, the Container OOM Black Box
Most modern memory failures live in containers, and container memory is bounded by cgroup, not by host physical memory. These are two separate ledgers.
```bash
# find the container's cgroup
cat /proc//cgroup
# read the control files
cat /sys/fs/cgroup/system.slice/docker-xxxx.scope/memory.max
cat /sys/fs/cgroup/system.slice/docker-xxxx.scope/memory.current
cat /sys/fs/cgroup/system.slice/docker-xxxx.scope/memory.events
```
The `memory.events` file is the black box:
```
low 0
high 0
max 3421 # times current hit max
oom 12 # times OOM killer was triggered
oom_kill 12 # times a process was actually killed
```
- `low` / `high` rising is the early warning that memory is getting tight.
- `max` climbing is the container repeatedly hitting its ceiling.
- `oom_kill` moving from zero is the direct evidence of an OOMKilled Pod.
The scope of an OOM kill is the cgroup that triggered it and its descendants. When a container's `memory.current` hits `memory.max`, the kernel picks the highest `oom_score` process inside that cgroup and kills it. It does not touch other containers on the host. So a container being OOMKilled while the host has half its memory free is normal, and the direction to investigate is `memory.max` being too small, not "add a machine".
`memory.current` also includes every page cache the container touched. A Java process with 800M RSS can show 1.2G `memory.current` because of cached files. Never troubleshoot container memory by process RSS alone; `memory.current` is the container's real total.
```bash
cat /sys/fs/cgroup/system.slice/docker-xxxx.scope/memory.stat | grep -E '^(anon|file|slab_reclaimable|slab_unreclaimable|shmem|pgmajfault)'
```
If `file` dominates and `anon` is small, the container memory is inflated by page cache, and you can raise the limit or wait for reclaim. If `anon` is near `memory.max`, the application itself is growing and you have a leak or a real capacity problem.
## Seven: The OOM Killer, and How It Picks a Victim
When direct reclaim cannot keep up, the kernel runs the OOM killer. It is not a judgment, it is an execution: pick, kill, done.
### The badness Algorithm
The kernel scores every process, and the highest score is the victim. Roughly:
```
badness ~ (RSS + swap + page tables) adjusted by oom_score_adj
```
The bigger the memory footprint, the more likely it is to be killed. The lower the `oom_score_adj`, the less likely. `-1000` means never kill, `+1000` means kill first.
```bash
# higher score means more likely to be chosen
for pid in $(pgrep -u app); do echo -n "$pid "; cat /proc/$pid/oom_score; done | sort -k2 -n -r | head
```
### oom_score_adj, the Insurance Policy
```bash
# protect critical processes
echo -500 > /proc//oom_score_adj
# sacrifice batch jobs first
echo 500 > /proc//oom_score_adj
# -1000 means the OOM killer skips this process entirely, use with care
echo -1000 > /proc//oom_score_adj
```
My production defaults on a database node: MySQL or [PostgreSQL](https://www.postgresql.org/docs/) at -500 to -300, Redis at -300, monitoring agent at -200, log collector at +100, batch jobs at +300. In [Kubernetes](https://kubernetes.io/docs/) the equivalent is the Pod's `oomScoreAdj` or the runtime configuration.
### Reading dmesg, the Incident Report
```bash
dmesg -T | grep -i -E 'out of memory|killed process|oom' | tail -30
```
Line by line, this is the full report:
| Log fragment | Meaning | Where it points |
| --- | --- | --- |
| `invoke_oom_killer ... order=0` | OOM on a single-page allocation | Small `order` means slow drip pressure, not a huge allocation |
| `constraint=CONSTRAINT_NONE` | **Node-level OOM** | The whole host is out, look at the host |
| `constraint=CONSTRAINT_MEMCG` | **cgroup-level OOM** | A container hit its ceiling, look at the cgroup |
| `Killed process 1234 (java)` | Who died and how much | Note the PID and name |
| `total-vm / anon-rss / file-rss` | The victim's memory profile | `anon-rss` is real usage, `file-rss` is cache |
| `Tasks state ... anon:65536` | Snapshot of all processes | Compare anon values, find the real suspect |
The single most important judgment: `CONSTRAINT_MEMCG` means the container is the problem, `CONSTRAINT_NONE` means the node is the problem. Getting that backwards wastes the whole investigation. A host OOM that you chase into a container ceiling, or a container OOM that you chase into host memory, both lead nowhere.
**Incident three: a Java service OOMKilled daily in Kubernetes.** The customer's service was OOMKilled several times a day, and the host showed 200G free. `kubectl exec` showed `oom_kill 18` in `memory.events`, `memory.max = 2147483648` (2G), `memory.current = 2130706432` (1.98G). Then the killer: `jcmd VM.flags` showed `MaxHeapSize = 3221225472` (3G). The container limit was 2G but the JVM heap was configured to 3G. The JVM thought it had 3G, the container only allowed 2G, and the moment heap plus metaspace plus thread stacks plus page cache hit 2G, the OOM killer took the JVM.
The fix was `-Xmx1280m` against the 2G limit, plus `-XX:MaxRAMPercentage=60` so the JVM auto-detects the container limit. The lesson: the first thing to check in a container OOM is the ratio of Xmx to memory.limit. A heap larger than the container limit is the number one cause of OOMKilled Java services in Kubernetes.
## Eight: swap Configuration, swappiness, zram, and overcommit
Swap used well is a buffer. Swap used badly is a disaster.
### swappiness
`/proc/sys/vm/swappiness` controls how much the kernel prefers reclaiming anonymous pages versus file pages. Default is 60.
| Value | Use case | Effect |
| --- | --- | --- |
| 0 | Extremely conservative | Rather kill a process than swap |
| 10 | **Database / latency-sensitive** | Barely swap, prefer file pages |
| 30 | General services | Balanced |
| 60 | System default | Moderate |
| 100 | Aggressive | Constant swapping, latency collapses |
My default: database nodes at 10, general web services at 20 to 30, desktops at 60. Do not set swappiness to zero as a way to "disable swap". It only stops voluntary swapping; when memory truly runs out the kernel swaps anyway, and more violently. Give it a 10 and let it swap gently.
**Incident four: swap thrashing spiking database latency.** A PostgreSQL primary showed queries occasionally freezing for two to three seconds. `free` showed `available` at 6G, so "there is memory". But `vmstat 1 3` showed si/so sustained at 200 to 800 KB/s and a `b` column of 2 to 3, and `%iowait` around fifteen percent. `cat /proc/sys/vm/swappiness` showed 80, someone had raised it. With swappiness at 80, the kernel was eagerly swapping out anonymous pages, including PostgreSQL's shared_buffers. Every query that hit a swapped-out page waited on disk. Setting swappiness to 10 and persisting it brought si/so to zero within the hour and restored latency.
The lesson: high swappiness plus active swap is a latency bomb. On databases, push it below ten and verify si/so actually goes to zero.
### zram and zswap
Since swapping to disk is slow, compress the swap and keep it in memory.
- **zram**: a compressed block device used as swap. Good for small-memory boxes that want to avoid disk swap. Compression ratio is typically 2 to 4x.
- **zswap**: a compressed cache layered on top of existing disk swap. Good when you have disk swap and want to cut I/O.
```bash
modprobe zram
echo 2048M > /sys/block/zram0/disksize
mkswap /dev/zram0
swapon -p 100 /dev/zram0
```
My honest take: memory-resident applications like Redis do not need swap at all, and zram fits the "a bit tight but do not want to buy a machine" case. If memory is genuinely short, adding a DIMM beats any swap scheme.
### overcommit_memory
The kernel can oversell memory, a successful malloc does not guarantee physical pages.
| overcommit_memory | Meaning |
| --- | --- |
| 0 | Heuristic, default |
| 1 | Always overcommit, no check, dangerous |
| 2 | Strict, no overcommit, governed by overcommit_ratio |
For databases I set `overcommit_memory=1`, because MySQL and PostgreSQL mmap large blocks that the heuristic sometimes rejects. But it needs enough swap as a backstop. If you set `2`, be careful: an application failing to start with `Cannot allocate memory` may actually be overcommit refusing the allocation, not real memory exhaustion.
## Nine: Leak Detection, /proc/meminfo, slabtop, and the RSS Curve
Memory problems split into one-off pressure (traffic spike) and chronic leaks (only up, never down). The leak is more dangerous because it can take days to trip an alert.
```bash
grep -E '^(Slab|SReclaimable|SUnreclaim|Dentry|Inode)' /proc/meminfo
```
- `SUnreclaim` rising and never falling -> kernel slab leak, suspect drivers, filesystems, kernel modules.
- `SReclaimable` rising -> usually dentry or inode cache, reclaimable, not a leak.
- `Dentry` abnormally high -> directory entry cache leak, common with apps that create and delete files constantly.
```bash
slabtop -o
```
An object at USE 100% with a growing count is a leak. `dentry` at 100% growing is a dentry leak. `kmalloc-*` at 100% growing is a kernel module or driver leak. `filp` growing is a file descriptor leak.
User-space leaks show as RSS that only climbs. A normal process has peaks and valleys; it falls back after GC or after a request completes. A staircase that never falls back is a leak.
```bash
while true; do
echo "$(date +%H:%M:%S) $(ps -o rss= -p )" >> /tmp/rss_$(date +%F).log
sleep 60
done
```
**Incident five: a kernel slab leak growing 2G a day.** A node gained 2G of memory per day, while `used` and `available` looked fine, but `Slab` climbed daily and `SUnreclaim` went from 500M to 8G. `slabtop` showed `dentry` at 100% USE with a growing object count. The box ran an NFS client plus a cron job that created and deleted temp files at high frequency. The NFS dentry cache was not being released when files were deleted. The fix was upgrading the NFS client module, reducing temp file churn, and a manual reclaim with `echo 2 > /proc/sys/vm/drop_caches`.
The lesson: when memory only climbs and every process RSS is normal, check slab. Kernel-space leaks are invisible to `ps`; only `slabtop` and `SUnreclaim` reveal them.
## Ten: The Decision Tree
```
memory suspected (slow / process killed / alert)
|
+-- 1. free -h + /proc/meminfo
| +-- available healthy (>10%) -> not memory, move to CPU/IO
| +-- available low but buff/cache high -> page cache at the top, try reclaim, continue
| +-- SUnreclaim + Shmem high -> kernel/tmpfs usage, jump to step 6 (leak)
|
+-- 2. vmstat 1 5
| +-- si/so sustained non-zero -> real pressure, swap active, jump to step 7 (swap tuning)
| +-- si/so zero but b high -> disk IO or direct reclaim, check iostat
| +-- free falling and r rising -> memory being eaten slowly, jump to step 6 (leak)
|
+-- 3. OOM happened? dmesg -T | grep -E 'Out of memory|killed'
| +-- constraint=CONSTRAINT_MEMCG -> container-level, jump to step 5 (cgroup)
| +-- constraint=CONSTRAINT_NONE -> node-level, note the Killed process, continue
| +-- no OOM log but process died -> not memory, check app log / coredump
|
+-- 4. node-level OOM: ps aux --sort=-rss, find high-RSS process
| +-- found it -> check oom_score / oom_score_adj, protect critical, scale or shrink
| +-- not found (RSS sum << memory) -> check Shmem (tmpfs) / SUnreclaim (slab), jump to 6
|
+-- 5. container-level OOM: memory.events + memory.max + memory.current
| +-- oom_kill > 0 and current ~ max -> container at ceiling, check Xmx vs limit
| +-- oom_kill > 0 but current << max -> transient spike, check memory.peak
|
+-- 6. leak: slabtop + RSS curve
| +-- SUnreclaim / slab climbing -> kernel slab leak, check driver/NFS/filesystem
| +-- a process RSS climbing, never falling -> user-space leak, jmap/valgrind
| +-- Dentry high -> high-frequency file ops, fix the app
|
+-- 7. swap tuning: swappiness + zram/zswap + overcommit
+-- database node: swappiness=10, maybe disable swap or use zram
+-- latency-sensitive: verify si/so returns to zero
+-- critical process: set oom_score_adj=-500
```
The fastest entry is three steps: `free -h` for `available`, `vmstat` for si/so, then decide whether the OOM is node-level or cgroup-level. Three steps in, eighty percent of problems are located.
## The Cheat Sheet
| # | Command | Purpose | Key output |
| --- | --- | --- | --- |
| 1 | `free -h` | Overview | `available` is the real number |
| 2 | `grep -E '^(MemAvailable\|SUnreclaim\|Shmem)' /proc/meminfo` | Real available plus hard usage | Split soft/hard memory |
| 3 | `vmstat 1 5` | Swap and run queue | si/so sustained non-zero = pressure |
| 4 | `ps aux --sort=-rss \| head` | Big-RSS process | RSS overcounts |
| 5 | `smem -rsk -t` | Real memory by PSS | PSS is the honest number |
| 6 | `cat /sys/fs/cgroup/.../memory.events` | Container OOM black box | `oom_kill` count |
| 7 | `cat /sys/fs/cgroup/.../memory.max` | Container ceiling | Check ratio against Xmx |
| 8 | `cat /sys/fs/cgroup/.../memory.current` | Container current usage | Includes page cache |
| 9 | `dmesg -T \| grep -E 'Out of memory\|killed'` | OOM log | `constraint` decides scope |
| 10 | `cat /proc//oom_score_adj` | OOM protection score | -1000 = never kill |
| 11 | `echo -500 > /proc//oom_score_adj` | Protect critical process | Negative value |
| 12 | `cat /proc/sys/vm/swappiness` | Swap preference | Default 60 |
| 13 | `slabtop -o` | Kernel object cache sort | USE 100% and climbing = leak |
| 14 | `cat /proc/zoneinfo \| grep -E 'min\|low\|high'` | Memory watermarks | Free below min = danger |
| 15 | `cat /proc/meminfo \| grep -E '^(Slab\|Dentry\|Inode)'` | Kernel memory | Slab climbing = leak |
## FAQ
### Why does free show high used but the system is fine?
Because `used` includes a lot of reclaimable `buff/cache`. Linux caches disk pages, dentries, and inodes whenever memory is idle, so `used` being high is normal and healthy. Read `available`, which is what the kernel can actually give a process right now. Or check `vmstat 1 5`: if si/so stays zero, there is no swap pressure and memory is not tight.
### Why was my container OOMKilled when the host has plenty of memory?
Container memory is bounded by cgroup `memory.max`, a separate ledger from host memory. When `memory.current` hits `memory.max`, the kernel kills a process inside that cgroup. Read `memory.events` `oom_kill`, plus `memory.max` and `memory.current`, and check whether the JVM Xmx exceeds sixty to seventy percent of the limit.
### What is the right swappiness?
Default is 60. For databases and latency-sensitive workloads use 10 to 30 to avoid swapping out anonymous pages. But remember: swappiness only affects the preference between anonymous and file page reclamation, setting it to zero does not disable swap, and database workloads should verify si/so actually goes to zero.
### How do I tell a leak from normal growth?
RSS that only climbs and never falls, plus `SUnreclaim` and `Slab` that climb and never fall, plus a `slabtop` object at 100% USE with a growing count. If memory rises and plateaus, that is cache warm-up. Only up-and-up is a leak.
### Why did OOM kill my critical process instead of the big memory hog?
The OOM killer scores by `oom_score`, which is mostly memory footprint but is adjusted by `oom_score_adj`. If your critical process has a positive or zero `oom_score_adj` and the memory hog has a negative one, the killer may pick yours. Set critical processes to `oom_score_adj=-500` and batch jobs positive, so the choice is yours, not the default.
### How can available still have several GB but I still got OOM?
`available` is what could be given immediately, but allocation is instantaneous. A JVM expanding its heap by 2G, or a huge query mmapping memory, can allocate faster than direct reclaim can react. `available` is a trend indicator, not a guarantee against a spike. Look at cgroup `memory.peak` or a sudden jump in `vmstat`'s `r` column.
### Original statement
All five incidents are ones I worked directly, with identifying details generalized. Every command sequence is the one I run in production. Thresholds and tuning values are my field experience, not vendor defaults.
## Related Articles
- [Linux CPU Monitoring: top's Five Percentage Fields and the Decision Tree](linux-cpu-monitor.md)
- [node_exporter Metrics Missing: Six Symptom Decision Tree](node-exporter-metrics-missing.md)
- [Kubernetes Pod Troubleshooting: The Five-Step Drill](kubernetes-pod-troubleshoot.md)
- [HA MQTT Auto-Discovery Failure Postmortem: Topic Drift / Duplicate Names Made Devices Vanish](../postmortems/ha-mqtt-discovery-failure.md)
---
## Loki Log Aggregation in Practice: A Single-Cluster Deploy and the Label Cardinality Trap
URL: https://ops.jiunotes.top/en/monitor/loki-log-aggregation.md
摘要: Loki trades full-text search for index-free labels, which cuts storage cost but introduces the cardinality trap. This guide walks a docker-compose single-cluster deploy, the Alloy vs Promtail vs Vector decision, LogQL patterns, and five incidents that taught me the rules.
### Answer
Loki's label design is the real skill. Keep label combos under 100k, use low-cardinality fields, and check rate vs count_over_time before querying.
### FAQ
Q: Why would I move from ELK to Loki?
A: Loki is index-free: it labels streams instead of full-text indexing every line. For high-volume logs where you mostly filter by labels and search occasionally, it cuts storage cost dramatically and ingests faster.
Q: What is the label cardinality trap?
A: If you attach high-cardinality labels like pod_name or container_id, every unique value creates a new stream and a new index entry. Past roughly 100k unique label combinations, queries start timing out and ingestion slows.
Q: Alloy, Promtail, or Vector — which should I pick?
A: For a pure Loki pipeline Alloy is the current default. Vector is stronger if you also fan out to other backends. Promtail is legacy but still works. Match the collector to your whole pipeline, not just Loki.
Q: What is the difference between rate() and count_over_time()?
A: rate() converts a log counter to an events-per-second gauge for dashboarding. count_over_time() returns the raw number of lines in the window — it is a step counter, not a rate, so the range matters.
### Full Content
# Loki Log Aggregation in Practice
I have run log pipelines for a small platform team for years, and for most of that time I ran ELK. [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html) was comfortable: I could grep anything, anywhere, instantly. Then the bill arrived. My ingest went from ~20 GB/day to ~120 GB/day as the microservice count doubled, and the Elasticsearch cluster needed three more data nodes just to keep index latency under a second. The storage cost and the ops load were both growing faster than my headcount. I migrated to Loki.
## 1. Why ELK and I parted ways
The core difference is the index. Elasticsearch full-text indexes every log line. That is why search is instant — but it is also why storage explodes. A 1 KB JSON log line can consume 3–5 KB on disk once you count the inverted index, the doc store, and replica overhead. Loki does the opposite: it does not index content at all. It indexes **labels** and stores the log bytes as compressed chunks. Search across the body is a scan, not an index lookup.
The cost math is what convinced me. In my ELK cluster, a hot data node with 1 TB of NVMe held roughly 8 days of logs at 120 GB/day before the 15% shard watermark forced rebalancing. On Loki with the same volume, the same retention fit on a single 1 TB disk with room to spare. Ingest also got simpler: no shard tuning, no mapping conflicts, no force-merge windows. For a team that mostly filters by service and searches by error string, Loki was the better trade.
## 2. Picking a deploy mode
Loki ships three ways. The **single binary** runs everything in one process and is fine for a dev box, but it has no HA. The **microservices mode** splits compactor, distributor, ingester, and querier into separate deployments — that is what [Grafana](https://grafana.com/docs/) Cloud runs and what a large platform needs, but it is overkill for a team of four. The **docker-compose cluster** runs the Loki components as separate containers sharing object storage. That is the mode I chose: simple enough to debug, resilient enough for production, and I can lift it into [Kubernetes](https://kubernetes.io/docs/) later without rewriting configs.
## 3. The single-cluster docker-compose walkthrough
My stack is three containers: `loki`, `alloy`, and `grafana`, wired into a `monitoring` network. The Loki config keeps a single filesystem backend and a ring backed by Consul or, simpler for one node, a boltdb file.
```yaml
# loki-config.yaml
auth_enabled: false
server:
http_listen_port: 3100
common:
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
retention_period: 720h
ingestion_rate_mb: 8
```
The 30-day retention lives in `limits_config.retention_period`, and I set `ingestion_rate_mb` per-stream to keep a noisy app from flooding the ingester. The compose file maps those into a named volume.
```yaml
services:
loki:
image: grafana/loki:3.1.0
command: -config.file=/etc/loki/config.yaml
volumes:
- ./loki-config.yaml:/etc/loki/config.yaml:ro
- loki-data:/loki
ports: ["3100:3100"]
alloy:
image: grafana/alloy:v1.4.0
volumes:
- ./alloy-config.alloy:/etc/alloy/config.alloy:ro
- /var/log:/var/log:ro
- /var/run/docker.sock:/var/run/docker.sock:ro
grafana:
image: grafana/grafana:11.2.0
environment:
GF_AUTH_ANONYMOUS_ENABLED: "true"
ports: ["3000:3000"]
volumes:
loki-data:
```
I verify the cluster in three steps: check readiness, push a probe line, then confirm it lands.
```bash
curl -s localhost:3100/ready
echo '{"streams":[{"stream":{"job":"probe"},"values":[["'"$(date +%s%N)"'","hello from loki"]]}]}' \
| curl -s -X POST localhost:3100/loki/api/v1/push -H 'Content-Type: application/json' --data-binary @-
# expect: {"status":"success"}
```
In Grafana I add a Loki data source at `http://loki:3100`, then run `{job="probe"}` in Explore. I learned the hard way that the push endpoint wants nanosecond timestamps; sending milliseconds silently drops the entry.
## 4. The collector decision: Alloy, Promtail, or Vector
I ran all three before committing. **Promtail** is the legacy Loki collector. It works, but Grafana moved development to Alloy and Promtail is in maintenance mode. **Vector** is a general-purpose agent from Datadog. It is the strongest choice when I fan out the same logs to Loki *and* a metrics backend *and* an S3 archive, because it handles many sinks natively. **Alloy** is the current Grafana default, and for a Loki-centric pipeline it is what I settled on. It replaces both Promtail and the old Grafana Agent, uses a declarative River syntax, and gives me service discovery and relabeling in one config.
For my single-cluster setup the choice was clear: Alloy, because my pipeline ends at Loki and Alloy has the tightest integration with it.
```alloy
# alloy-config.alloy
loki.source.docker "default" {
host = "unix:///var/run/docker.sock"
targets = discovery.docker.containers
forward_to = [loki.process.default.receiver]
}
discovery.docker "containers" {
host = "unix:///var/run/docker.sock"
}
loki.process "default" {
stage.regex { expression = "^(?P\\w+)\\s.*" }
stage.labels { values = { level = "" } }
forward_to = [loki.write.default.receiver]
}
loki.write "default" {
endpoint { url = "http://loki:3100/loki/api/v1/push" }
}
```
The `stage.regex` and `stage.labels` blocks parse the log level out of the first field and attach it as a label, which is exactly the kind of label I can filter on later.
## 5. Label design: the golden rules
Loki is a label-first database. Every unique set of label values creates a **stream**, and every stream is an index entry. That is powerful but it is also the trap. My rules, hard-won:
- **Budget cardinality.** I keep the total number of unique label combinations under ~100,000 across all streams. Past that, query planning and ingestion both slow down.
- **Labels are low-cardinality only.** `job`, `level`, `app`, `cluster`, `env` are safe. `pod_name`, `container_id`, `trace_id`, and `request_id` are never labels. Those belong in the log line body, not the label set.
- **Labels are filters, not metadata.** If I never query on it, I do not label it. Metadata belongs in the structured log body where `| json` can extract it lazily.
The anti-patterns I actually hit are worth naming. I once relabeled the full `container_id` from [Docker](https://docs.docker.com/). Every container restart created a new stream, and within a week I had 400,000 streams and queries that timed out. I also labeled `path` from [nginx](https://nginx.org/en/docs/) access logs — that was hundreds of streams per app, all from a field I rarely filtered on. I fixed both by moving the high-cardinality value into the log body and keeping only `job` + `level` + `app` as labels. My stream count dropped from ~400k to ~2k and queries went from timing out to sub-second.
## 6. LogQL cheat sheet
LogQL is the query language, and the two functions that trip everyone up are `rate` and `count_over_time`.
```logql
# events per second — use for dashboards and alerts
rate({app="api"}[5m])
# raw line count in the window — a step counter, NOT a rate
count_over_time({app="api"}[5m])
```
`rate()` normalizes by the range, so it is comparable across windows and it is what I plot. `count_over_time()` returns the raw count, so a 5m window shows five times the value of a 1m window. If I alert on it I must set the threshold with the range in mind.
Structured logs are where I parse JSON with `| json`. The trap: a malformed JSON line in the stream aborts the query for that stream. I always test against a mixed sample.
```logql
{app="api"} | json | level = "error" | line_format "{{.ts}} {{.msg}}"
# unwrap extracts a numeric value for metric-style aggregation
sum by (route) (rate({app="api"} | json | unwrap bytes [5m]))
```
`unwrap` is what turns a numeric field inside the log body into a series I can `rate` or `sum`. It only works on numbers; passing a string returns an error, which is another parsing trap I hit in production.
## 7. Five real incidents
**Incident 1: log volume spike filled the disk.** A cron job flipped into a tight error loop and wrote 400 GB of stack traces in six hours. The chunk disk hit 100%. The fix was a global `ingestion_rate_mb` in the limits config, plus a per-tenant cap, and a Grafana alert on `rate({app=~".+"}[5m])` crossing a threshold so I know before the disk does.
**Incident 2: label cardinality explosion.** The `container_id` relabeling I described above. Queries started timing out at the querier. I fixed it by dropping the high-cardinality label, and I added a Grafana dashboard to watch stream growth.
**Incident 3: retention not applying, disk filled again.** I set `retention_period` and waited, and nothing happened. Loki's retention is applied by the **compactor**, not the ingester, and my single-binary config had compaction scheduled far apart. I set `compactor.compaction_interval` and `retention_period` together, ran a manual compaction, and the disk came back down.
**Incident 4: cross-cluster federation sync lag.** I had a second cluster forwarding to the primary. The federated querier returned stale results for minutes because the store refresh interval was too long. I lowered the store `refresh_interval` so queries balanced across stores.
**Incident 5: multi-tenant misconfig leaked logs between tenants.** I enabled `auth_enabled` but left the push endpoint open with a default tenant. A tenant A service pushed into the default tenant, and tenant B could read it. I enforced a tenant header on every push and locked down the distributor to reject pushes without a valid `X-Scope-OrgID`.
## 8. The production checklist
Before I take a Loki stack live, I run eight checks:
1. **Retention** is set in `limits_config` and the compactor interval is aligned with it.
2. **Cardinality** is below the 100k budget; I verify stream count with `sum(count_over_time({job=~".+"}[1m]))`.
3. **High-cardinality labels** (pod, container, trace) are excluded from the label set.
4. **Ingestion rate limits** are configured globally and per-stream.
5. **Auth and tenants** are enforced; no anonymous push, valid `X-Scope-OrgID` required.
6. **Alerts** exist for log rate, stream count, and disk usage.
7. **Storage** has headroom for at least two full retention cycles.
8. **Backup** of the config and the object store is tested, not assumed.
## 9. Loki HTTP API quick reference
```bash
curl localhost:3100/ready # health check
curl localhost:3100/metrics # internal metrics
curl -X POST localhost:3100/loki/api/v1/push # push logs
curl 'localhost:3100/loki/api/v1/query_range?query={app="api"}&start=...&end=...&limit=100' # range query
curl -G 'localhost:3100/loki/api/v1/query_range' --data-urlencode 'query=rate({app="api"}[5m])' # metric query
```
The push endpoint is a POST with a JSON body; the query endpoints take a URL-encoded LogQL expression. I keep the push body small and batched, because many small pushes are slower than a few large ones.
## 10. FAQ
**Q: How do I know when to alert on a log rate spike?**
A: Plot `rate({app="api"}[5m])` and alert when it crosses a multiple of the baseline — I use 3x for 10 minutes. Alert on the rate, not on `count_over_time`, so the threshold is window-independent.
**Q: Should I keep structured logs as JSON or plain text?**
A: JSON. `| json` lets me filter and `unwrap` numeric fields without regex. Plain text is fine for a single app, but the moment I need a field for a query it has to be structured.
**Q: My query is slow — what do I check first?**
A: Cardinality. Run `sum(count_over_time({job=~".+"}[5m]))` and look at `bytes_processed` in the query stats. If stream count is high, drop the high-cardinality label. Then check that I used a label matcher, not just a body filter.
**Q: Is Loki a drop-in replacement for Elasticsearch?**
A: No. Loki is not a full-text search engine. It is a label-first log store. If I need substring grep across arbitrary bodies at scale, ELK still wins. Loki wins when the primary access path is label filtering plus occasional scanning.
## Related Articles
- [Blackbox Exporter: Protocol Modules, SLO Metrics, and K8s ServiceMonitor Setup](blackbox-exporter.md)
- [node_exporter Metrics Missing — Six Symptom Categories, Root-Cause Decision Tree, and Five Real Incidents](node-exporter-metrics-missing.md)
- [node_exporter Metrics Missing: 6 Symptom Categories and 5 Real K8s Incidents](node-exporter-troubleshoot.md)
- [Chaos Engineering in Production: Fault Injection from Experiment Design to Safe Live Drills](chaos-engineering.md)
---
## Alert Storms at 2 AM — An Alertmanager Grouping, Resolution, and Silence Decision Tree
URL: https://ops.jiunotes.top/en/monitor/monitor-alert-storm.md
摘要: The on-call channel is flooded with the same alerts over and over, Alertmanager grouping did not work, silences did not hold. This page lays out a decision tree that first separates "the alerts are genuinely duplicated" from "grouping is broken", then drives the fix onto group_by, resolve_timeout, and silence matchers, and finally adds a noise-reduction strategy that collapses off-hours non-core alerts into one.
### Answer
First separate "genuinely duplicated" from "grouping failed". A group_by that misses a key label keeps every alert separate. Three levers reduce noise: add group_by, shrink resolve_timeout, and silence the non-core pages. Inhibit rules let a critical alert suppress its warnings.
### FAQ
Q: The same alerts keep firing all night. Which three parameters are usually out of alignment?
A: Three: a group_by that misses a key label so alerts that should merge never do; a resolve_timeout that is too long so recovered alerts are slow to clear; and duplicate receiver routes so one alert hits several channels.
Q: I added a silence but I still receive alerts. Why?
A: Either the silence matchers do not cover the alert's real labels, or the silence window is too short and has already expired. Open the silences page in Alertmanager and check that the matchers actually match the labels on the alert.
Q: How do I tell whether an alert is genuinely duplicated or grouping failed?
A: Genuinely duplicated means the alert labels differ, for example a different instance, so they should stay separate. Grouping failed means the labels are identical yet the alert keeps re-paging, which means group_by is not merging them into one group. Read the labels to tell the two apart.
Q: There are too many off-hours non-core alerts. How do I collapse them into one?
A: Give the non-core alerts a fallback receiver in the route with group_by set to alertname, shrink resolve_timeout, and let many non-core alerts merge into one "N non-core alerts" summary instead of paging you individually.
Q: Which labels should go into group_by?
A: At minimum alertname and instance, or job, so same-type same-instance alerts merge. Adding severity lets you also page P0 and P2 to different people.
### Full Content
# Alert Storms at 2 AM — An Alertmanager Grouping, Resolution, and Silence Decision Tree
What I dread is not alerts at all. I dread the same batch of alerts re-paging me through the night. Once a core node went down and a single Prometheus down-alert fired. Alertmanager had no grouping, so every one of twenty node exporters that flickered produced twenty nearly identical alerts that all hit the on-call channel in under three minutes, then repeated on a five-minute cycle. I was woken at two and found the same event had been scrolled through forty times.
I have since built a small decision tree for this kind of alert storm. The core move is to first ask "is this genuinely duplicated or is grouping broken", then drive the fix onto three parameters.
## Step 1: Decide whether the alert is genuinely duplicated or grouping is broken
Open the Alerts view in Alertmanager and read the batch that is flooding you.
| Symptom | Verdict | Where to fix |
|---|---|---|
| Labels identical yet it keeps paging | Grouping broken | Check group_by |
| Labels differ (instance / job differ) | Genuinely duplicated (many instances each fired) | Check whether the data really has many instances in trouble, or dedup is missing |
| One alert hit several channels | Duplicate receivers | Check the receiver routes |
This split is the fork. Get it wrong and every later step is wasted.
## Step 2: Grouping broken — group_by is not merging what should merge
The classic case: one Prometheus alert rule fires for every instance under a job and should become a single "N instances down" notification, but instead it pings one by one.
The cause is almost always a group_by that missed a key label.
```yaml
# before: group_by only has severity, so twenty instances collapse into one group yet each pages on its own
route:
group_by: [severity]
# after: add alertname and instance and job, so same-type same-instance merges
route:
group_by: [alertname, instance, job]
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
```
Read the three parameters together:
- **group_by** decides which alerts count as one group. Miss a label and they never merge.
- **group_wait** is how long a group waits before a new alert in it is sent. Too short and it is the same as not merging at all.
- **repeat_interval** is how often a still-firing group re-reminds. Too short and it becomes a spam loop.
I once changed group_wait from the default thirty seconds to five seconds, so the twenty alerts still pinged one by one and looked like grouping was broken when really the wait window was too short. Changing it back to thirty seconds merged them into one immediately.
## Step 3: A silence did not hold — check two places
A silence that still lets alerts through usually has two causes.
1. The matchers do not cover the alert's real labels. The alert label is alertname="NodeDown" but the silence wrote alertname="node_down", a spelling or case mismatch, and it never matches.
```yaml
silences:
- matchers:
- alertname="NodeDown"
- severity="warning"
startsAt: 2026-11-14T02:00:00Z
endsAt: 2026-11-14T06:00:00Z
comments: "core node maintenance window, silence the non-core alerts"
```
2. The window is too short and expired early. A thirty-minute maintenance dragged to forty, so the last ten minutes of alerts leaked through.
Open the Silences page in the Alertmanager Web UI and compare the alert labels against the silence matchers one by one. Fix whichever one does not line up.
## Step 4: The three noise levers — collapse off-hours non-core alerts into one
The most practical way to stop "2 AM non-core alert bombing" is three levers, all at the route layer.
**Lever one: split receivers by severity.**
```yaml
route:
group_by: [alertname, instance, job]
group_wait: 30s
routes:
- match:
severity: critical
receiver: page-oncall
- match:
severity: warning
receiver: slack-noncore
```
**Lever two: add a time-window silence for non-core alerts.**
```yaml
# off-hours non-core alerts are not paged, batched until morning
route:
- match:
severity: warning
receiver: slack-noncore-morning
```
**Lever three: use inhibit rules to let the high-severity alert suppress the low ones.**
When a machine goes down, the hundreds of warnings on it (CPU, memory, disk IO all jitter) all stem from that single down. An inhibit rule suppresses the low ones:
```yaml
inhibit_rules:
- source_match:
severity: critical
target_match:
severity: warning
equal: [instance, job]
```
Meaning: if a critical is already firing for the same instance and job, the warning is not paged on its own. This one rule removes about eighty percent of the noise in a storm.
## Step 5: One quick verification command
After changing the config, hot-reload it and fire a test alert to confirm the noise is actually down:
```bash
kill -HUP $(pgrep -f alertmanager)
kubectl -n monitoring rollout restart deploy/alertmanager
curl -X POST -H "Content-Type: application/json" \
-d '{"labels":{"alertname":"TestStorm","severity":"warning"},"annotations":{"summary":"test"}}' \
http://localhost:9093/api/v1/alerts
curl -s http://localhost:9093/api/v1/alerts | jq '. | length'
```
## A single card
| Symptom | Root cause | One fix |
|---|---|---|
| Twenty near-identical alerts ping one by one | group_by missed a label / group_wait too short | add instance and job to group_by, set group_wait to 30s |
| Recovered alerts slow to clear | resolve_timeout too long | shrink resolve_timeout |
| A silence did not hold | matchers do not match the real labels | compare the silence matchers against the alert labels one by one |
| One alert hit several channels | duplicate receiver routes | remove the duplicate receiver |
| 2 AM non-core alert bombing | no split by severity | critical pages, warning posts to chat, add a 0-7 silence |
| Most of the storm is same-source noise | low-severity alerts not suppressed | add inhibit_rules so critical suppresses warning |
## One question I ask before touching the route
Before I change the route I ask myself: "Are there really many machines in trouble at the same time, or is one event being scrolled N times?" The first is a real incident and should widen the on-call response. The second is a configuration problem and should be de-noised. Get it wrong in one direction and you either suppress a real incident or keep paging people for a storm. Judge first, then decide whether to add a silence or widen the response.
## After the storm: what I leave behind
Two post-mortem moves, so the next storm does not blow up in my face.
First I classify this storm's alerts into "the real culprit" and "the noise that got suppressed", and write that split into the team's alert-naming convention. For example: any P0 such as "a machine is down" must carry severity=critical in its alert rule labels, and every CPU, memory, or disk wobble it generates must carry severity=warning. That way the next inhibit rule has a documented basis instead of someone guessing at three in the morning.
Second I keep group_by down to the smallest actionable set: alertname plus instance plus job, and I keep severity out of group_by. Severity routes the alert to the right receiver; it does not belong in the grouping key. If I put severity into group_by, the critical and the warning on the same machine split into two groups and I get an extra notification, which is the opposite of noise reduction. The point of grouping is "who should be woken", not "group as finely as possible".
Two cheap habits help on top of that. One is a nighttime paging window: between midnight and morning only critical pages, everything else queues in chat until I wake up, and that single cut removes about eighty percent of the disturbance. The other is a weekly look at the alert panel: any alert that fires every single night for the past seven days and gets silenced every time is not something I need to see, it is a threshold I wrote wrong. Either tune the threshold or delete the alert; do not keep pressing silence on it every night.
## Turning Alert Quality into a Standing Metric
A storm is a one-off; "will it blow up again" is a measurement question. I keep three alert-quality numbers and review their trend every Monday: ① the **noise ratio** — silenced or inhibited alerts divided by alerts actually delivered; a rising ratio means thresholds or grouping are degrading; ② the **escape rate** — incidents caught more than an hour after on-call should have caught them, which exposes critical-routing gaps; and ③ the **manual-silence coverage** — the share of noise I keep holding down by hand each night. The third one is the honest tell: the higher it gets, the more my rules are not fixing anything and I am just pressing silence. All three sit on a Grafana panel on the on-call dashboard, and any one of them trending worse for two straight weeks forces a scheduled de-noising sprint, instead of waiting for the next 3 a.m. wake-up to remember it was needed.
## Related
- [Prometheus alert design](prometheus-alerting.md) — alert rule and severity conventions
- [Alert noise reduction strategy](alertmanager-noise-reduction.md) — the full de-noising methodology
---
## Grafana Dashboard Is Blank or Misaligned — A Troubleshooting Decision Tree
URL: https://ops.jiunotes.top/en/monitor/monitor-grafana-blank.md
摘要: A Grafana dashboard renders as a grey empty rectangle, or the numbers do not match what you expect, or the curves sit at the top of the chart. This page walks a six-pit decision tree — data source, time range, variables, units, query semantics, panel mapping — and pairs each pit with one curl call or one query you can run to cross-check whether the problem is a misconfiguration or missing data.
### Answer
When a dashboard is blank, first confirm the data source can return a raw metric, then check the time range, variables, and units. If the curve is misaligned, look at the unit and the aggregation function. If the numbers disagree, check whether the query is missing a rate or a by clause.
### FAQ
Q: The whole dashboard is blank. What do I check first?
A: Start at the data source. Open the data source in Grafana and run a query for up. If that returns nothing, no amount of panel configuration will help; the data source layer is broken. If the source returns values, move down to the individual panels.
Q: One panel is blank but the others have data. Where is the problem?
A: That panel is bound to a data source or a variable that did not resolve. Open the panel editor and check the Data section: the query, the data source dropdown, and whether a variable such as $host resolved to an empty string. Walk through each one.
Q: The curve is stuck at the top of the chart. Why?
A: Almost always a wrong unit. If a CPU metric is shown as bytes instead of percent, the value is off by a factor of a thousand and the line pins to the top. Set the Unit in the panel standard options to the correct type.
Q: The number in Grafana does not match what I query in Prometheus. Why?
A: Most often the panel uses one aggregation such as avg while the direct Prometheus query uses rate or sum. The two queries have different semantics, so the curves cannot line up. Paste the panel query verbatim into Prometheus and compare the two result sets.
Q: The $instance variable does not populate when I refresh. What is wrong?
A: The variable refresh is not set to on dashboard load. Open the variable and change refresh to on dashboard load, then reload the dashboard.
### Full Content
# Grafana Dashboard Is Blank or Misaligned — A Troubleshooting Decision Tree
I once inherited a Grafana dashboard that the team reported as "all grey". I opened a panel and confirmed the data source was connected and that up returned values, yet not a single panel on the board had a curve. It took me twenty minutes to find the cause: the dashboard had been cloned from a different environment, and none of the variables those panels referenced were defined in this environment. So $instance in every query resolved to an empty string, turning each PromQL statement into rate(node_cpu_seconds_total{job=""}[5m]) — a query that matches nothing.
Since then I keep a small decision tree with six branches: data source, time range, variables, units, query semantics, and panel mapping. Each branch has a cross-check I can run before I touch anything.
## Pit one: the data source has no data at all
The deepest reason a dashboard is blank is that the data source to Prometheus link is broken in itself.
```bash
# open the data source page in Grafana, go to Query, and run
# up, or hit the proxy API with a Grafana token
curl -s -H "Authorization: Bearer $GTO" \
-G "http://localhost:3000/api/datasources/proxy/uid/0/prometheus/api/v1/query" \
--data-urlencode 'query=up'
```
If that returns result=[], the data source layer is dead. Go back to Prometheus targets and the network before spending time here.
Another variation I have hit: the data source is connected but Prometheus retention is only four hours, so a dashboard pulling yesterday's curves is blank. This one is easy to miss because the source "can return values", it just returns only the last four hours. Check retention:
```bash
curl -s http://localhost:9090/api/v1/status/runtimeinfo | jq '.data.tsdb.retention.time'
```
## Pit two: the time range does not line up
The second most common reason a dashboard renders empty is the time range. Two typical misalignments:
- The range is set to last 30 days but Prometheus keeps only 48 hours. Result: the curve exists on the left and is blank on the right.
- The range is last 5 minutes but a panel is bound to a low-frequency recording rule that emits a point every five minutes, so a 5-minute window lands on nothing.
Two quick checks:
```bash
# see how far back the source actually returns data
curl -s -G "http://localhost:3000/api/datasources/proxy/uid/0/prometheus/api/v1/query_range" \
--data-urlencode 'query=up' \
--data-urlencode 'start=2026-09-01T00:00:00Z' \
--data-urlencode 'step=3600' | jq '.data.result | length'
```
Thousands of points means retention is fine. Zero means data was pruned.
## Pit three: the variables did not resolve
This is the pit I fall into most. Panels on a Grafana dashboard reference variables such as $instance, $host, $job, and when a variable fails to refresh or is undefined, the PromQL has the variable replaced with an empty string and the whole query stops matching anything.
How to pin it down:
1. Open any panel in edit mode and look at the query for $-prefixed variables.
2. Check that the variable actually resolved to a value. In the Variables section, open the variable and read its values list.
3. If the list is empty, look at the variable query type:
- **query** — the variable itself runs a PromQL to pull labels, e.g. label_values(up, instance). If that query returns nothing, every label it feeds is empty and every panel that uses it is empty.
- **custom** — manually entered values; confirm the right entry is selected.
- **constant** — a fixed string; usually fine.
Fix: set refresh to on dashboard load, or reorder the dashboard so variables resolve before the panels. I once had an ops teammate set a constant variable job to the wrong spelling, and every one of the twenty panels on the board went blank until he fixed the constant.
## Pit four: a unit misalignment pins the curve to the top or bottom
A curve that looks misaligned but actually has data is, almost without exception, a unit problem. The Units setting decides how the y-axis interprets the number. Typical wrong pairings:
| Unit you assumed | Real value magnitude | Result |
|---|---|---|
| percent (1-100) | bytes (gigabytes) | curve pinned to the top, y-axis at 1e9 |
| bytes | percent (1-100) | curve pinned to the bottom, invisible |
| seconds | milliseconds | timeline stretched a thousand times |
To pin it down: open the panel, go to Standard options and Unit, and compare it against the real magnitude of the metric (run the metric in Prometheus /query and read the value).
I once set the unit of rate(node_disk_bytes_written[5m]) to percent, and the y-axis ran to 1e12 while the curve sat glued to the zero line. Change the unit to bytes and the curve came back instantly.
## Pit five: a query-semantics misalignment makes numbers disagree
When a Grafana panel number does not match a direct Prometheus query, the usual causes fall into three groups.
### 5.1 A missing rate or sum
The panel writes node_cpu_seconds_total, which is a cumulative counter, while the direct Prometheus query uses rate(node_cpu_seconds_total[5m]), the per-second delta. The two have completely different meanings, so the numbers cannot agree.
### 5.2 Different aggregation functions
One side uses avg and the other uses sum, so the magnitudes differ by ten to a hundred times.
### 5.3 A missing by label
sum(rate(node_cpu_seconds_total[5m])) and the same expression with by (instance) return different row counts, so Grafana draws a single line while the direct query returns a bundle.
Cross-check:
```bash
# copy the panel query verbatim and run it in Prometheus
curl -s "http://localhost:9090/api/v1/query" --data-urlencode 'query='
# compare the two result sets and find the semantic gap
```
I hit one where a Grafana panel used avg but the alerting script used max, and the two disagreed by three times. Aligning the functions made them match.
## Pit six: a panel-mapping overlap stacks the curves
A single panel that should show many instances defaults to splitting by series. If the labels are not split correctly, the curves stack on one another and the chart looks like a single line.
To pin it down: look at the panel Transformations and see whether a Group by is applied, and whether the Legend is set to {{instance}}. If the legend is wrong, the chart draws only one line.
```yaml
# legend template example
{{instance}} - {{job}}
```
Set the legend correctly and the curves separate.
## A single card
| Symptom | Pit | One cross-check |
|---|---|---|
| Whole board blank | data source | run up in the data source page |
| One panel blank | variable | see what a $ variable resolves to in the panel query |
| Curve only covers the last N hours | time range/retention | /api/v1/query_range start point |
| Curve pinned top or bottom | unit | is the panel Unit the real magnitude of the metric |
| Numbers disagree | query semantics | paste the panel query into Prometheus |
| Curves overlap | panel mapping | is the Legend set to {{instance}} |
## One question I ask before touching a panel
Before I change anything I ask myself: "Is this curve 'no data' or 'wrong configuration'?" The first points at the data source and retention. The second is the panel itself. The two paths do not overlap, so getting the direction right up front saves real time.
I also ask one more question: "Where did this dashboard come from?" If it was cloned from another environment, the variables, the data source UID, and the time offsets may all be stale — and I check "are all the variables defined and is the data source UID correct" before anything else. Most dashboards that suddenly go blank are a migration that was not finished, not a data problem.
## Related
- [Grafana dashboard design](grafana-dashboard.md) — the unit and Legend conventions when building a board from scratch
- [Prometheus query cheat sheet](prometheus-query.md) — the semantic differences between rate, sum, and avg
- [Prometheus deployment](prometheus-deploy.md) — aligning retention with the query window
---
## Reading CPU, Memory, and Disk IO Without Misjudging — a Host Signal Decision Tree
URL: https://ops.jiunotes.top/en/monitor/monitor-host-signals.md
摘要: A load of 30 does not mean you need more CPU, a 95% memory figure does not mean you need more RAM, and a high iowait does not mean the disk is dying. This page separates the three classic host misjudgments and gives a symptom-to-command decision tree for CPU, memory, and disk IO, with eight high-frequency traps and their corrections.
### Answer
For each host signal, ask whether the number is high because the resource is busy or because something is waiting. CPU: split real work from steal and iowait. Memory: check available and OOM records, not used. Disk: pair %util with await and aqu-sz, and use PSI for the true stall time.
### FAQ
Q: Load is very high but CPU usage is low. Do I actually need more CPU?
A: Not necessarily. A high load with high idle usually means threads stuck in D state, an uninterruptible IO wait, so the bottleneck is disk, not CPU. Read the run and blocked columns in vmstat: a run queue above the core count is real CPU queuing, a blocked count above zero is IO waiting.
Q: Memory is at 95 percent. Should I add RAM?
A: Check available, not used. Linux puts free memory into cache, so a high used figure is normal. Look at MemAvailable and the Buffers and Free lines, and search dmesg for OOM kill records. If available still has headroom and there is no OOM, no extra RAM is needed.
Q: iowait is high. Does that mean the disk is failing?
A: Not necessarily. iowait is a result, the CPU waiting on IO, not the root cause. Use iostat -x and read %util, await, and aqu-sz together. Utilization near one hundred with a rising await is a truly busy disk. Low utilization with high await means large requests or a deep queue, often an application tuning problem.
Q: The container is CPU-bound but the host looks idle. What is going on?
A: This is the most common misjudgment. A cgroup CPU quota throttles the container processes while the host aggregate stays low. Read the nr_throttled counter in the cgroup cpu.stat and use the PSI cpu pressure to see how much time is spent stalled.
Q: Disk utilization is one hundred percent but throughput has not grown. What does that mean?
A: Percent utilization at one hundred only means saturated on a single-queue device. On an NVMe or multi-queue solid state drive the figure is naturally high and is not saturation. Judge saturation from the average queue depth, or from the PSI some and full stall ratios.
### Full Content
# Reading CPU, Memory, and Disk IO Without Misjudging — a Host Signal Decision Tree
I have seen far too many "the metric is scary but nothing is actually wrong" incidents, and just as many "no alert fired but the system is already wedged" ones. The most common host-monitoring failure is not not knowing how to read a metric. It is reading the metric wrong: a load of 30 and someone shouts for more CPU, memory at 95 percent and someone rushes to add RAM, iowait spikes and someone blames a slow disk. Each of these misjudgments burns a half day, and each one can trigger a wrong capacity decision.
So I broke the three host signals down into one decision tree, symptom to command to fork, built on three sentences:
- **CPU**: a high load does not equal not enough CPU. Separate the real work from steal and iowait.
- **Memory**: a high used figure does not equal not enough memory. Look at available and the OOM records.
- **Disk IO**: high utilization does not equal a saturated disk. Tell real busy from waiting on a lock or a queue.
## Signal one: CPU — a high load does not mean you should scale out
### Symptom A: high load and %user is not low either
```bash
vmstat 1 10
mpstat -P ALL 1 5
cat /proc/stat
```
The fork: in vmstat, the run column above the core count means the CPU is genuinely the limit and you should scale out or throttle. A normal run queue with the blocked column above zero means threads are stalled on IO, the root cause is not the CPU, so go to the disk segment.
### Symptom B: high load but high idle as well
```bash
ps -eo state,pid,cmd | awk '$1=="D"' | head
vmstat 1 5 | awk 'NR>2 {print $cs}'
```
This is the classic case where load lies: D-state processes count toward the load average but they never take the CPU. Most of the time the disk or NFS is slow, not the CPU.
### Symptom C: high %steal in a virtualized environment
```bash
mpstat -P ALL 1 3 | grep -E "CPU|%st"
```
%steal is the host taking your virtual CPU time to serve somebody else. I once saw a container pegged at 90 percent where neither %sys nor %user was high and the whole thing was steal; it turned out the host was oversold and moving the workload was the fix. **High %steal means go to the host, not add an instance.**
## Signal two: memory — 95 percent does not force you to add RAM
### Separate used, available, and cache
```bash
free -h
grep -E "MemAvailable|MemFree|Buffers|Cached" /proc/meminfo
```
Linux puts idle memory to work caching files, so used stays high and that is normal. **Watch available**, the kernel's estimate of what is actually usable. If it still has a gigabyte or more and the system is not lagging, do not rush to add memory.
### Three hard proofs of real memory pressure
```bash
dmesg | grep -i "out of memory" | tail -5
vmstat 1 5
cat /proc/pressure/memory
```
The third line is the most direct signal: some avg10 above ten means processes are stalling on memory frequently and it is a real bottleneck; near zero means the number is just ugly and performance is fine.
### The container trap: host free does not see the cgroup limit
```bash
cat /sys/fs/cgroup/memory/memory.limit_in_bytes
cat /sys/fs/cgroup/memory/memory.usage_in_bytes
dmesg | grep -i "killed process"
```
The host free shows fifty gigs, but the container limit is two gigs and it OOMs anyway. **Judge memory in the cgroup that owns the workload.**
## Signal three: disk IO — 100 percent utilization is not a saturated disk
### Split it with iostat -x
```bash
iostat -x 1 5
```
| Reading | Verdict | Next move |
|---|---|---|
| Util near 100 with high await | truly busy on a single-queue device | scale up, swap to SSD, or split the disk |
| Low util but high await | large requests or a deep queue | inspect request size, tune the app concurrency |
| Util near 100 but throughput flat | waiting on a lock or queue | check queue depth and the application layer |
| Util naturally high on NVMe | multi-queue device, not saturation | read queue depth and PSI instead |
I was burned once: the monitor reported a hundred percent utilization and I was told to swap the drives. I ran iostat -x and saw await of 0.8 milliseconds and a queue depth of 0.3, the device was not queuing at all; the high utilization was just how a multi-queue drive displays. The real problem was the application writing one huge request. **A bare utilization figure misleads; always pair it with await and queue depth.**
### Let PSI hand you the "how long we stalled on IO" answer
```bash
cat /proc/pressure/io
```
Some avg10 above ten confirms real IO stalling; full avg10 above one means every task stalled at once, which is worse. On the Prometheus side the same numbers come from the node pressure IO waiting series.
### High iowait but the disk is not busy — the cause is elsewhere
```bash
cat /proc/*/stat 2>/dev/null | awk '$3=="D"' | head
bpftrace -e 'tracepoint:block:block_rq_issue { @[comm] = count(); }'
dmesg | grep -i "nfs" | tail
```
High iowait with a low disk utilization means the bottleneck is network storage or lock contention, not the local disk. This single check saves a wrong "replace the drive" decision.
## A single card
| Misjudgment | The truth | One command |
|---|---|---|
| High load equals not enough CPU | many D-state means waiting on IO | list D-state processes |
| High load equals not enough CPU (VM) | high %steal means host oversell | mpstat for %st |
| Memory at 95 equals not enough | check available and OOM records | grep MemAvailable, then dmesg for OOM |
| Not enough memory in a container | host free ignores the cgroup limit | read the cgroup memory limit |
| 100 percent util equals saturated | multi-queue drives need queue depth | iostat -x |
| High iowait equals slow disk | possibly NFS or lock contention | cat /proc/pressure/io |
| Container CPU exhausted | cgroup quota throttling | read nr_throttled in cpu.stat |
| "It is slow" blames one component | find the stall source first | read the cpu, memory, and io PSI |
## One question I ask before calling for a capacity change
Before I ask for a bigger machine I ask: "Is this number high because it is busy, or because it is waiting?" CPU can be high while waiting on a lock, memory can be high and just be cache, and utilization can be high and just be how a multi-queue drive displays. Almost every host misjudgment is reading a "waiting" as a "busy". One command to find the wait source, the D-state count, PSI, queue depth, or %steal, is a hundred times cheaper than adding a machine, and it will not bury the real root cause in application code, lock contention, NFS, or host oversell.
## A hard-earned lesson I keep in my pocket
I built this habit after being burned. For a stretch the dashboards were red every day, three metrics taking turns spiking, and every on-call assumed the box was about to die, yet the business side never reported a single slowdown. When I finally compared one busy morning hour by hour, all three "fires" were waiting, not work: the CPU spike was quota throttling driving a retry storm, the 95 percent memory had sixty gigs of cache with forty still available and not one OOM in dmesg, and the iowait was a scheduled batch job writing logs, with await at 1.2 milliseconds. Three red flags, all "waiting".
Since then I have a rule: when any host metric trips, I do not reach for the machine first. I run the matching verification command, the PSI line, dmesg, iostat -x, or the steal figure, and I write down "busy or waiting" before I act. Thirty minutes of verification saves an unnecessary capacity approval and, more importantly, keeps me from burying the real root cause behind a wrong one. The value of a monitor is not turning every number green. It is telling you precisely where it is stuck.
## Wiring the Three Signals into Prometheus: from local command to alert rule
This decision logic works well when you run it by hand on the box, but on-call can not log in and type `iostat` and `cat /proc/pressure` every time. The real payoff is wiring the same "symptom to metric" mapping into Prometheus so the alert does the "first ask whether it is busy or waiting" for you. Here is the fixed way I hook it up.
CPU: do not alert on load; alert on queueing and on being stolen. Load itself is a poor alert source (D-state pollutes it). Keep `node_load1/5/15` for the dashboard, but split the alert into two rules: one fires when `node_load5` divided by the core count stays above one (real queueing), and one fires when `avg by(instance)(rate(node_cpu_seconds_total{mode="steal"}[5m])) * 100` is above ten percent (you are being stolen from in a virtualized host, so go find the host, not scale out). That way the alert arrives with a built-in direction to look, instead of being yet another "CPU high."
Memory: alert on available, not on used, and pair it with an OOM backstop. The main rule is `node_memory_MemAvailable_bytes` below five percent of the node's total RAM (fire only under five percent, which is far more accurate than watching used cross 95 percent). Add a hard backstop for OOM events (the delta of `node_vmstat_oom_kill`, or an event stream), because "available looks fine but a process already got OOM-killed" is the most damaging case and must fire on its own. In containers, move the judgment into the matching cgroup's `memory.limit_in_bytes` and `memory.usage_in_bytes` ratio; do not answer with the host's `MemAvailable`.
Disk I/O: alert on await and on PSI, not on the bare %util value. A lone %util is unreliable on NVMe. Alert on the rate of `node_disk_io_time_weighted_seconds_total` (weighted queueing, a close proxy for aqu-sz pressure) together with the rate of `node_pressure_io_waiting_seconds_total`. Keep %util on the dashboard for reference only, out of the alert path. This is the rule change that finally killed the "buy an SSD" misjudgment — once the alert source changed, a naturally-high %util could no longer drag a purchase decision.
Based on a typical production scenario: after wiring the above into a 40-node cluster, over one month the false positives from the "CPU high / memory high / IO high" alert class fell from about six a week to one, and that one was a real fault (a node at eighty percent steal, genuinely an oversold host, resolved by a migration). The two rules that paid off most: the steal rule wrote "go find the host" directly into the alert text for the first time, so on-call no longer had to guess; and the IO rule caught a real write-pressure batch during an await rise, before the business stalled, and let us retune the write cadence in time. The lesson: the value of an alert rule is not "it fires a lot"; it is that every rule carries its own direction, and the "busy or waiting" fork is decided at the rule layer.
## Related
- [Linux CPU monitoring](linux-cpu-monitor.md) — a deeper read of each column in the top line
- [Linux memory monitoring](linux-memory-monitor.md) — the full breakdown of cache, buffers, and available
- [Linux disk IO monitoring](linux-disk-io-monitor.md) — every iostat field and how to call saturation
- [node-exporter troubleshooting](node-exporter-troubleshoot.md) — when these metrics are not being collected, check the collector first
---
## Loki Returns Nothing, Queries Time Out, or the Disk Fills Up — A Troubleshooting Decision Tree
URL: https://ops.jiunotes.top/en/monitor/monitor-loki-missing.md
摘要: Loki is up but logcli returns empty, or the query crawls until it times out, or the disk alarm fires every day. This page separates the four symptoms — nothing ingested, no match, slow query, disk full — and drives each onto its own segment: collector, labels, retention, or chunks, with one runnable command per breakpoint.
### Answer
When queries return nothing, check /ready and the label endpoint first. Empty labels mean no logs arrived, so inspect the collector. Labels with values but empty queries mean the LogQL matcher is wrong. Slow queries point at label cardinality or time range, and disk alarms mean retention and compactor are not configured.
### FAQ
Q: logcli returns nothing at all. What is the first thing to check?
A: Confirm Loki itself is alive with /ready, then hit /loki/api/v1/labels and /label//values. Empty labels mean not a single line reached Loki, so inspect the collector side. Labels with values but an empty query means your LogQL matcher does not match the stream labels exactly.
Q: The log file exists on disk but Loki does not have it. Why?
A: The collector is the usual culprit. Confirm the tail process is following the file, then confirm the file appears in the collector positions file. The three most common breakpoints are a path glob that misses subdirectories, a SELinux permission denial, and a Kubernetes pod whose positions directory lives inside a container that gets recreated.
Q: Labels have values but the query still returns empty. What is wrong?
A: The label matcher. LogQL matches stream labels exactly with {job="x"}, and the value must match the output of /api/v1/labels character for character. One wrong letter and the query silently returns an empty result instead of an error, which is the most time-wasting kind of failure.
Q: Queries are extremely slow or time out. How do I pin it down?
A: Three directions: the label cardinality is in the hundreds of thousands of streams, the time range is too wide, or the chunks live on object storage and every query fetches them back. Narrow the time range first, then read the stream and chunk metrics.
Q: The disk alarm fires every day. What is the real fix?
A: Configure retention properly: set retention_period, enable retention in the limits config, and turn on the compactor. Delete files by hand without a compactor and you corrupt the index; config one field without the other and nothing is deleted.
### Full Content
# Loki Returns Nothing, Queries Time Out, or the Disk Fills Up — A Troubleshooting Decision Tree
Loki bills itself as Prometheus for logs, but the ways it breaks are quite different. I have seen four symptoms dominate, and each one belongs to a different segment of the pipeline. Split them first and every command after gets shorter.
Four symptoms, four segments:
| Symptom | Segment | First command |
|---|---|---|
| Nothing (logcli returns empty) | collector down / label mismatch | /loki/api/v1/labels |
| Partial (some hours or apps missing) | glob miss / incomplete chunks | collector positions |
| Slow or timeout | label cardinality / time range / chunk fetch | narrow the range and retry |
| Disk alarm every day | retention / compactor missing | /loki/api/v1/status/buildinfo |
## Segment one: nothing found — distinguish "zero lines" from "wrong matcher"
```bash
curl -s http://localhost:3100/ready
curl -s http://localhost:3100/loki/api/v1/labels
curl -s http://localhost:3100/loki/api/v1/label/job/values
logcli query '{job="app"}' --limit=10 --since=1h
```
Labels entirely empty goes to segment two, the collector. Labels present but query empty means the matcher is wrong, and three traps cover almost every case.
**Trap one: the matcher must be exact.** LogQL's {job="app"} is an exact stream-label match, not a fuzzy one. {job="application"} and {job="App"} match no stream at all and, worse, return empty silently with no error. Copy label names and values from the output of /labels and /label/job/values rather than typing them.
**Trap two: do not put high-cardinality fields into stream labels.** Teams routinely promote trace_id, user_id, or a raw path into a stream label, and one application splinters into hundreds of thousands of streams. The query then matches a different set of streams than you expect and the result looks incomplete. Stream labels belong to low-cardinality enums such as level, env, and service; high-cardinality fields go through a line filter like |= "trace_id" or structured metadata.
**Trap three: the time range.** logcli's default window is not the one you picked in Grafana. --since=24h is how you pull yesterday's logs.
## Segment two: the file exists on disk but Loki never sees it
This is the collector segment, and the chain is application writes to file, the collector tails it, pushes, and Loki ingests. Verify each link in order:
```bash
tail -f /var/log/app/app.log
curl -s -o /dev/null -w "%{http_code}" http://localhost:9080/ready
cat /var/lib/promtail/positions.yaml | grep app.log
journalctl -u promtail --since "10min" | grep -Ei "error|permission|denied"
```
The three most common breakpoints:
1. The positions file has no entry for your file, which means the __path__ glob does not cover it. Globs do not recurse by default, so /var/log/*.log never picks up /var/log/subdir/. Use /var/log/**/*.log.
2. SELinux blocks the tail. A permission denied shows up in the collector log, and ausearch -m avc -ts recent | grep promtail shows the denial record.
3. In Kubernetes the positions directory lives inside the container, so every pod recreation restarts from zero and gets truncated by retention. Confirm the DaemonSet mounts positions on a hostPath.
I once had an application and the collector in the same pod where __path__ pointed at a host path that does not exist inside the container. The collector logged "no files matched" on every start with exit code zero, nobody noticed, and logging was dark for three days. So the order in this segment is always: file exists, tail process is following it, positions file lists it. Do not skip ahead.
## Segment three: slow or timing out
Three root causes, cheapest to dearest:
```bash
logcli query '{job="app"}' --since=30m
curl -s http://localhost:3100/loki/api/v1/labels | head
curl -s http://localhost:3100/loki/api/v1/status/metrics | grep -E "streams|chunks"
logcli query '{job="app"}' --limit=100 --since=6h --verbose
```
- **Range too wide.** Loki has no full-text index, so a wider window means more chunks scanned. Shrink to thirty minutes first, then widen.
- **Cardinality exploded.** A streams metric in the hundreds of thousands means too many labels; go back to trap two in segment two. The real fix is deleting the high-cardinality label so one application collapses into a handful of streams.
- **Chunks fetched from object storage.** Verbose output full of GET requests to an object store means cold data is on S3 and every query pays the round trip. Either accept it or shorten local retention and tune the compactor.
The same logic applies inside Grafana: when one panel hangs, cut the time range to fifteen minutes and add a line filter such as |= "keyword", and you can almost always tell a range problem from a cardinality problem in one try.
## Segment four: the disk alarm every day — retention is the real fix
Loki does not delete old data unless you explicitly configure retention, so the disk only ever grows. Three settings must go together:
```yaml
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
retention_period: 168h
retention_delete_worker_count: 150
compactor:
working_directory: /loki/wal
compaction_interval: 10m
retention_enabled: true
retention_delete_delay: 2h
```
Three points:
1. retention_enabled and retention_period must both be set; the period without the compactor does nothing.
2. Keep retention_delete_delay at two hours so the logs you are about to query are not deleted mid-query.
3. Put the compactor working directory and index on local disk or object storage so the compactor cannot fill the disk it is cleaning.
Verify:
```bash
curl -s http://localhost:3100/loki/api/v1/status/buildinfo | grep -i retention
du -sh /loki/chunks && df -h /loki
watch -n 60 'du -sh /loki/chunks'
```
One hidden item: the write-ahead log. The WAL is not part of normal queries, but if a query window lands on the WAL boundary or the WAL is sized to eat the disk, the alarm fires faster than chunks grow. Read max_query_lookback and the WAL size together.
## A single card
| Symptom | Segment | One check |
|---|---|---|
| logcli entirely empty | labels empty | curl /loki/api/v1/labels |
| Labels exist, query empty | matcher wrong | copy a value from /label/job/values |
| File exists, Loki does not have it | collector | grep the file name in positions.yaml |
| Glob misses subdirectories | collector | change __path__ to **/*.log |
| Query times out | range too wide | retry with --since=30m |
| Query is slow | cardinality | a streams metric in the hundreds of thousands means too many labels |
| Slow and hits S3 | chunk fetch | watch for object-store GETs in --verbose |
| Disk alarm | retention missing | retention_enabled plus retention_period |
| Compactor never reclaims | partial config | are both fields present |
## One question I ask before touching anything
Before I start I ask: "Is there zero, or is a piece missing?" Zero lines means the collector or the matcher is wrong about nine times out of ten, and query performance is not even in the picture. A piece missing means I narrow by time or application, and the cause is almost always a glob that missed a directory, a pod that was never reattached, or an incomplete chunk. Get the direction right and every command afterwards tests one hypothesis instead of flailing.
## Beyond troubleshooting: one habit I keep reminding myself of
Loki's traps differ from Prometheus's. Prometheus usually fails at scraping; Loki usually fails at label design. So I run a label health check on every investigation: list every label name, pull out the high-cardinality ones such as trace_id, user_id, path, and pod_uid, and demote every one of them out of stream labels into a line filter or structured metadata. Even when the current incident is not caused by labels, that pass removes the single biggest latent risk.
There is one more lesson: a slow query and a full disk are often the same root cause. Too many labels fragment the stream set, every small chunk stores duplicate metadata, and that both slows queries and eats the disk. When both symptoms show up together, do not treat them separately; fix the label design once and both usually clear.
## Changing label design is a migration, not a config edit
I keep saying label design is the root cause, but the moment you actually change it is where people ship the worst outages, because **changing a stream label is a data migration, not a config edit**. Loki organizes chunks by stream (the label set), so the instant you touch any stream label, every chunk stored under the old labels stops matching your new queries — old logs go missing, dashboards go dark, and it looks like "Loki is broken" when you actually cut your own streams.
So I change labels in three steps and never in one shot:
1. **Add first, never delete.** To demote `trace_id` out of stream labels, first add the new path — a `|=` line filter or structured metadata — so new logs flow through both routes while the old label is still in place. Both old and new queries keep matching; nothing breaks.
2. **Leave an observation window before removing the old one.** Once the new path has run stably for a full retention cycle (I use seven days) and I have confirmed no old query still relies on `trace_id` as a stream label, only then do I drop the label from promtail. Before I drop it I re-check it against `/loki/api/v1/labels`.
3. **Change one label at a time and watch the streams metric after each.** Batch changes interfere with each other and make it impossible to say which label caused a regression. After each change I watch the streams count in `/status/metrics` collapse as expected (it should fall clearly once a high-cardinality label is gone) and confirm harmless before the next one.
One blood-and-tears lesson: after you change a label in promtail, **the positions file does not reset just because the label changed** — it only tracks file offsets. So old files do not get re-read because the label moved. If you expect "change the label and history logs auto-move to the new stream," you are wrong: the old chunks stay under the old labels forever, and only new logs take the new ones. To truly normalize, you rebuild the index or let the data age out of retention on its own.
## Related
- [Loki log aggregation](loki-log-aggregation.md) — deployment and label design end to end
- [Prometheus TSDB operations](prometheus-tsdb-operations.md) — the metric-side retention story; the same ideas transfer to Loki
---
## Outdoor PoE voltage drop decision tree — cameras reboot in rain or at night
URL: https://ops.jiunotes.top/en/monitor/monitor-outdoor-poe-voltage-drop.md
摘要: A classic outdoor-surveillance failure — bullet/domed cameras reboot frequently in rain or at night, with heavy snow-noise on the image. This page gives a troubleshooting decision tree: confirm it is "insufficient PoE voltage causing repeated reboots" rather than water ingress or network, then measure end voltage with a multimeter, watch packet loss with ping -t, check the PoE switch port power, and finish with cable replacement, industrial switch and rainy-season inspection.
### Answer
When outdoor cameras reboot frequently in rain or at night with snow-noise images, it is usually not water ingress and not the network — it is PoE line aging or exceeding distance, causing excessive voltage drop and insufficient end voltage that reboots the camera repeatedly. Confirm the "reboots are regular and accompanied by voltage sag" signature, then measure the camera-end voltage with a multimeter (PoE standard ~48V; much lower means big drop), corroborate with ping -t intermittent loss and the PoE switch port output power. The cure is replacing over-long/aged outdoor cable, moving to an industrial PoE switch with a weatherproof box, and a rainy-season inspection plan.
### FAQ
Q: Why does it only reboot in rain and at night, but work fine on dry sunny days?
A: Rain/night stack two factors: high humidity and damp connectors lower the aged cable's insulation so voltage drop worsens; and lower night temperatures make some adapters/connectors contract and lose contact, dropping voltage further. On a dry sunny day the drop is just barely acceptable; once it gets damp and cold it falls below the camera's under-voltage threshold, so the camera reboots repeatedly. That is classic insufficient power margin, not coincidence.
Q: How do I confirm it is a voltage-drop problem with a multimeter?
A: Measure the actual voltage at the camera end (at the PoE splitter or cable termination) against the standard: 802.3af ~48V, 802.3at ~50-57V. If you read only around 30 V or lower, the line from switch to camera is dropping too much. Then measure the same port at the switch end; if the switch end is normal but the camera end is low, the drop is confirmed. Measure during the fault, not after it has recovered.
Q: Does ping -t packet loss relate to insufficient power?
A: Yes. An under-voltage PoE camera drops power and reboots first; the network goes down during reboot, showing as intermittent ping -t timeouts. If the loss lines up with the reboot times and the reboots track damp/cold periods, it is power, not the link itself. A pure link problem rarely changes "on schedule" with the weather.
Q: Must I replace cable over 100 meters?
A: PoE is more sensitive to drop than data. Fast Ethernet may still pass beyond 100m, but PoE over a long aged line drops end voltage below threshold directly. The spec caps a single Ethernet segment at 100m, and PoE needs more margin in practice. For over-long or aged outdoor cable, prefer a better-shielded, thicker-conductor (Cat5e/Cat6) outdoor cable, or add a PoE extender/injector mid-span.
Q: Are industrial PoE switches and weatherproof boxes worth it?
A: Very much so outdoors. Ordinary switches and connectors age fast under constant sun and rain; industrial gear has wider temperature range and surge protection, and a weatherproof box markedly extends life and cuts weather-driven failures. It turns "reactive repair" into "proactively fewer incidents", and works best with a rainy-season inspection plan.
### Full Content
# Outdoor PoE voltage drop decision tree — cameras reboot in rain or at night
There is a headache outdoor-surveillance failure: a few bullet/domed cameras behave fine on dry sunny days, but reboot frequently in rain or at night, with heavy snow-noise on the image. The first reflex drifts toward "the camera got water in it" or "the network is unstable", so people swap cameras and tweak APs — money spent, problem remains.
The signature of this fault is **"reboots/snow track the weather and time of day, and the root is power margin"**. A PoE-powered camera on an aged or over-distance line drops voltage until it falls below threshold and the camera power-cycles. The decision tree below handles the "outdoor PoE insufficient power" class.
## 60-second check — is it insufficient power?
Self-test with one sentence:
> Camera reboots/snow concentrate in rainy / low-temperature periods; fine on sunny days; and the reboot times are suspiciously "on schedule" → **strongly suspect PoE end voltage insufficient (excessive drop)**.
If reboots are random all day and unrelated to weather, look at the device or network itself — outside this page.
## Troubleshooting decision tree
```
User reports: outdoor camera reboots in rain/night, snow-noise image
│
├─ Look at the pattern
│ ├─ Reboots concentrate in damp/cold periods? → power-margin suspect (check power)
│ └─ Random all day, unrelated to weather? → check device or network itself
│
├─ Measure camera-end voltage (key)
│ ├─ Measured far below 48V (af) / 50-57V (at)? → excessive drop ★most common
│ └─ End voltage normal? → not power, move to network/device
│
├─ Switch-end same-port output vs camera-end
│ ├─ Switch end normal, camera end low? → line drop confirmed
│ └─ Both low? → switch port power / PSU itself
│
├─ ping -t the camera IP
│ ├─ Loss lines up with reboot times? → reboot causes outage, corroborates power
│ └─ Loss unrelated to reboot? → real link problem
│
└─ Root-cause locating
├─ Cable over 100m / aged damp? → replace, add PoE extender/injector
├─ Adapter aged damp? → industrial PSU / weatherproof box
└─ Switch port power insufficient? → industrial PoE switch
```
The hinge of the whole tree is one line: **first confirm "does the reboot track power margin", then decide whether to check voltage or network**. That step "measure camera-end voltage during the fault" is the pivot — the drop will not wait for you to be ready; you must catch it while it happens.
## Three-step locating procedure
### Step 1 — catch "during the fault" end-voltage
```bat
:: Not a terminal command — field measurement notes (use a multimeter / PoE tester)
:: 1. Measure actual voltage at the camera end (PoE splitter or cable termination)
:: 2. Standard: 802.3af ~48V, 802.3at ~50-57V
:: 3. Reading drops by 10 V or more → excessive drop
:: 4. Measure DURING reboot/snow, not after recovery (voltage returns to normal then)
```
Note: drop is set by load + line together; fault-state and recovered-state voltage can differ a lot. Catch a voltage frame at the moment the symptom appears.
### Step 2 — switch-end vs camera-end comparison
```
1. On the PoE switch port see "output power/voltage" (commands differ by vendor)
2. Switch end normal, camera end clearly lower → line drop confirmed
3. Both low → problem is switch port power or chassis PSU, not the cable
```
This step separates "cable problem" from "switch problem" and decides whether to replace cable or switch.
### Step 3 — ping -t to see if loss syncs with reboot
```bat
ping -t :: watch whether timeouts cluster around reboot periods
```
If the timeout times line up with "device reboot" and reboots track the weather, power is locked in. A pure link problem rarely "follows the weather" this precisely.
## Emergency stopgap — restore power temporarily
This is a **field-handling checklist** (not a terminal script; PoE power must be fixed on the cable/device):
```
1. Power this camera from a nearby independent PoE injector (shorten the path, reduce drop)
2. Or move the camera to a closer, higher-output switch port
3. Temporarily bridge the over-long cable with a better-quality segment to cut resistance
4. After recovery, watch one or two damp/cold cycles to confirm no more reboots
```
**Honest note**: fixing PoE power means "replace cable / replace switch / change power topology" — there is no copy-run script. The above is a checklist for field troubleshooting and temporary recovery, not code; cable spec and gear depend on your site.
## Root cause — make weather-driven failures rarer
Recovering one camera is only a stopgap. Outdoor low-voltage sits in the fastest-aging environment; close it off in three layers:
| Layer | Action | Prevents |
|---|---|---|
| Cable | Replace over-long/aged outdoor cable with better-shielded, thicker-conductor outdoor cable; add PoE extender/injector beyond 100m | long-line + aging drop breaking threshold |
| Device | Industrial PoE switch outdoors, surge-protected; connectors in a weatherproof box | sun/rain accelerated aging, surge burnout |
| Ops | "Outdoor weak-current box rainy-season inspection plan": pre-rain end-voltage check, damp-connector check, standing-water clearing | turn reactive repair into proactive fewer incidents |
One often-missed point: **PoE is more sensitive to drop than data**. The same 100m-plus line may still pass Fast Ethernet, but PoE end voltage has already dropped below threshold. So "ping works" does not mean "power is enough" — the voltage step cannot be skipped.
## Quick decision table (use it directly)
| Symptom | First reflex (misjudged) | Real root cause | Where to look |
|---|---|---|---|
| Reboots only in rain/night | camera water damage | PoE end voltage insufficient (drop) | measure camera-end voltage during fault |
| Snow-noise image | network unstable | under-voltage disturbs image module | end voltage + switch port power |
| Fine sunny, dead in rain | signal interference | damp worsens aged-line drop | damp connectors + line resistance |
| Intermittent ping timeouts | link broken | reboot causes outage | does loss sync with reboot times |
| Swapping camera did nothing | camera quality issue | root is line / power | switch-end vs end voltage compare |
This table is the practical version of "what this class of ticket is most easily misdiagnosed as" — eight out of ten of them open as "camera broken" or "bad network", and checking against the table skips most wasted effort.
## FAQ
**Q: Why does it only reboot in rain and at night, but work fine on dry sunny days?**
A: Rain/night stack two factors: high humidity and damp connectors lower the aged cable's insulation so voltage drop worsens; and lower night temperatures make some adapters/connectors contract and lose contact, dropping voltage further. On a dry sunny day the drop is just barely acceptable; once it gets damp and cold it falls below the camera's under-voltage threshold, so the camera reboots repeatedly. That is classic insufficient power margin, not coincidence.
**Q: How do I confirm it is a voltage-drop problem with a multimeter?**
A: Measure the actual voltage at the camera end against the standard: 802.3af ~48V, 802.3at ~50-57V. If you read only around 30 V or lower, the line from switch to camera is dropping too much. Then measure the same port at the switch end; if the switch end is normal but the camera end is low, the drop is confirmed. Measure during the fault, not after it has recovered.
**Q: Does ping -t packet loss relate to insufficient power?**
A: Yes. An under-voltage PoE camera drops power and reboots first; the network goes down during reboot, showing as intermittent ping -t timeouts. If the loss lines up with the reboot times and the reboots track damp/cold periods, it is power, not the link itself. A pure link problem rarely changes "on schedule" with the weather.
**Q: Must I replace cable over 100 meters?**
A: PoE is more sensitive to drop than data. Fast Ethernet may still pass beyond 100m, but PoE over a long aged line drops end voltage below threshold directly. The spec caps a single Ethernet segment at 100m, and PoE needs more margin in practice. For over-long or aged outdoor cable, prefer a better-shielded, thicker-conductor outdoor cable, or add a PoE extender/injector mid-span.
**Q: Are industrial PoE switches and weatherproof boxes worth it?**
A: Very much so outdoors. Ordinary switches and connectors age fast under constant sun and rain; industrial gear has wider temperature range and surge protection, and a weatherproof box markedly extends life and cuts weather-driven failures. It turns "reactive repair" into "proactively fewer incidents", and works best with a rainy-season inspection plan.
## Further reading and references
- [IEEE 802.3af/at PoE standard overview](https://en.wikipedia.org/wiki/Power_over_Ethernet) — nominal voltage and power per type; the baseline for "is end voltage in spec"
- [CommScope — PoE cabling distance and gauge guidance](https://www.commscope.com/) — long-distance PoE requirements on conductor gauge (follow vendor white papers)
- [Hikvision install guide — lightning and moisture chapters](https://www.hikvision.com/) — vendor advice on outdoor cabinet/connector moisture and surge protection (follow latest docs)
> This page is a troubleshooting decision asset. External links are authority references only; cable spec and gear depend on your site.
## Related guides and tools
- [Network connectivity troubleshooting (tcp-troubleshoot)](../network/tcp-troubleshoot.md) — underlying ping/loss/path checks; separate "reboot-caused loss" from a real link problem
- [Blackbox Exporter probing in practice](blackbox-exporter.md) — use active probing to keep watching outdoor camera liveness and latency; catch reboots earlier than manual patrol
- [Monitor switch loop broadcast-storm decision tree](monitor-switch-loop-broadcast-storm.md) — same-column sibling: another on-site failure class for the surveillance VLAN (loop)
> The fault case in this page comes from a real low-voltage site, used as a credibility anchor for the judgment. Actual voltage and cable spec depend on your field measurement.
---
## Prometheus Targets All Down and No Data — A Troubleshooting Decision Tree
URL: https://ops.jiunotes.top/en/monitor/monitor-prometheus-no-data.md
摘要: You just finished installing Prometheus and Grafana's dashboard is a blank grey rectangle. /targets shows half the targets in red. This page lays out a decision tree that separates "the scrape pipeline broke" from "the query layer is wrong", then drives each branch with one curl, one promtool check, and one kubectl command until the root cause is pinned to a specific segment: network, auth, TLS, relabel, or ServiceMonitor.
### Answer
Start by asking whether the target is down or up. If down, check scrape connectivity and auth first. If up but empty, the metric name or a relabel rule likely renamed the label away; verify the metric exists via the API and check promtool for config errors.
### FAQ
Q: All targets in /targets are down. What segment is most likely broken?
A: Most often it is the scrape side failing to reach the target: the network is unreachable, the exporter is not running, the port is wrong, or auth is failing. The Last Scrape error tells you which layer to dig into first.
Q: A target shows up but Grafana is still blank. Where is the problem?
A: up only means Prometheus reached the target and got something. It does not mean you got the metric you queried. Usually a relabel rule renamed or dropped the label, or the job name changed and your PromQL label matcher no longer matches. Open /query and confirm the metric name exists.
Q: How do I confirm a specific metric actually exists in Prometheus?
A: Hit the API directly: curl -s http://localhost:9090/api/v1/label/__name__/values lists every metric name, and a query against up proves the scrape path works. If the query returns a value, the problem is downstream in the query layer, not the scrape pipeline.
Q: In a Kubernetes cluster every target just went down. What do I check first?
A: Check whether the Prometheus and node-exporter pods are Running, whether the ServiceMonitor or PodMonitor was deleted or its labelSelector drifted, and finally read the Prometheus scrape errors from the pod logs.
Q: Targets went down right after I added auth. How do I pin it down?
A: The error is almost always a mismatch between basic_auth or tls_config in scrape_configs and what the target actually expects. Look at the Last Scrape message: 401/403 means credential mismatch, a TLS handshake failure means the certificate or endpoint scheme is wrong.
### Full Content
# Prometheus Targets All Down and No Data — A Troubleshooting Decision Tree
I have hit this more than once: I finish a Prometheus deployment, open Grafana, and the whole dashboard is a blank grey rectangle. I go to /targets and half the rows are red. The state is called "installed but no data", and it is the most time-wasting kind of failure because the possible causes are scattered across network, config, relabel, and the service layer. After the first few of these, I built a small decision tree for myself that separates the failure into segments and then executes the matching fix. Usually I can pin the root cause in under an hour.
## Step 1: Decide whether the fault is in the scrape segment or the query segment
Open the Prometheus Web UI under Status and go to Targets. The single most useful thing to read is the state column.
| State | Meaning | Where to go next |
|---|---|---|
| down | Nothing was scraped | Scrape segment: network / port / auth / exporter |
| up but the query returns empty | Scraped something, not the metric you want | Query segment: metric name / relabel / PromQL |
| up and the metric has values | Everything is fine | You queried the wrong panel; check the dashboard |
This one split shortens every later step.
## Step 2: If the target is down, branch on the error message
Open a down target and read the Last Scrape message. Three buckets cover almost everything I have seen.
### 2.1 connection refused or i/o timeout
This is the network layer. Walk the path from the Prometheus host to the target exporter in order:
```bash
# from the machine that runs Prometheus, test the target port directly
curl -v http://:/metrics
# if that is closed, check three things
ps -ef | grep -E "node_exporter|cadvisor" # is the exporter actually up?
sudo iptables -L -n | grep # is the firewall blocking it?
kubectl get svc -n monitoring # K8s: is the service still published?
```
I once had a target on 10.0.1.15 with Prometheus on a different node, and the firewall was blocking the whole 9100-9105 range. Opening that range brought the target back to up within ten minutes.
### 2.2 401 / 403
This is the auth layer. The scrape_configs job has basic_auth or a bearer token that does not match what the target actually expects, or the target started requiring auth and the config was never updated.
```bash
curl -s http://localhost:9090/api/v1/targets | jq '.data.activeTargets[] | select(.scrapeUrl|contains("9100"))'
```
Align the username, password, and tls_config three-piece set with what the target is really configured for.
### 2.3 TLS handshake failed
The target is HTTPS but the scrape config has no tls_config, or the CA is missing.
```yaml
scrape_configs:
- job_name: node-exporter-tls
tls_config:
ca_file: /etc/prometheus/ca.crt
insecure_skip_verify: false
basic_auth:
username: prom
password_file: /etc/prometheus/prom-pass
```
## Step 3: If the target is up but the query is empty
A target showing up still leaves three ways to end up with a blank dashboard.
### 3.1 The metric name does not exist
```bash
curl -s http://localhost:9090/api/v1/label/__name__/values | jq -r '.data[]' | head -100
curl -s "http://localhost:9090/api/v1/query" --data-urlencode 'query=up{instance="10.0.1.15:9100"}'
```
If the metric you are querying is missing from that list, the exporter is not exposing it. Hit the exporter directly and read what it actually publishes:
```bash
curl -s http://10.0.1.15:9100/metrics | grep -E "^node_" | head -20
```
### 3.2 A relabel rule renamed or dropped the label
This is the one that bit me hardest. I added a metric_relabel rule to filter some metrics and wrote the regex wrong, so it dropped every node metric. The target stayed up but the query returned nothing.
```bash
curl -s "http://localhost:9090/api/v1/query?query=up" | jq '.data.result'
curl -s "http://localhost:9090/api/v1/series?match[]=up" | jq '.data[0].metric'
```
When you add metric_relabel, always pair it with an allow-list regex such as `^(node_.*|up|process_.*|prometheus_.*).*$` so you do not wipe out the metrics you actually want.
### 3.3 Kubernetes: the ServiceMonitor was deleted or its labelSelector drifted
When every target in a cluster goes down, the first three checks I run are:
```bash
kubectl -n monitoring get pod -l app.kubernetes.io/name=prometheus
kubectl -n monitoring get servicemonitor -o wide
kubectl -n monitoring get servicemonitor -o yaml | grep -A5 selector
kubectl -n monitoring logs deploy/prometheus-server --tail=200 | grep -E "error|scrape"
```
Once I found a teammate who had edited the ServiceMonitor namespace by hand, so the selector no longer matched any pods and Prometheus stopped scraping entirely. Every target turned down with "no targets" in Last Scrape. Reverting the selector brought it back to life in thirty seconds.
## Step 4: Do not just stare at the targets — scrape interval and retention make data "invisible"
Everything above assumes the data is genuinely missing. There is a common false alarm where the data is being written the whole time, you just do not see it when you look. Three parameters cause this.
First, the scrape interval is too long. If scrape_interval is set to 60 seconds and you zoom the Grafana time range out to a year, the points are a minute apart and the small window looks empty. Confirm the real interval from the status flags:
```bash
curl -s http://localhost:9090/api/v1/status/flags | jq '.data.scrape-interval'
```
Second, retention is too short and the old data was pruned. I saw a node whose retention was misconfigured to 2 hours; the team thought monitoring was dead when in fact the three-day-old curves had been cleaned out. Read the active retention window:
```bash
curl -s http://localhost:9090/api/v1/status/runtimeinfo | jq '{tsdb_retention: .data.tsdb.retention.time, tsdb_max: .data.tsdb.versions}'
```
Third, a recording rule did not run or was written wrong. Many teams speed things up by precomputing frequently used queries as recording rules, and if that rule has a bad regex or was never activated, the metric the dashboard references is empty while the raw metric is still there.
```bash
curl -s "http://localhost:9090/api/v1/query" --data-urlencode 'query=job:http_request_total'
curl -s http://localhost:9090/api/v1/status/rules | jq '.data.groups[] | {name, rules: .rules[] | {name, state, health}}'
```
I once had an ops teammate set a recording rule interval to 15 seconds but the group evaluation_interval to five minutes, so the precomputed metric only refreshed every five minutes and the dashboard looked like it had gaps when it just had a slow refresh cadence.
## Step 5: Use promtool to pin down the config-layer error
Everything above is the runtime view. Close the loop with an offline check of the config itself:
```bash
promtool check config /etc/prometheus/prometheus.yml
promtool check rules /etc/prometheus/rules/*.yml
kubectl -n monitoring get cm prometheus-configuration -o yaml | sed -n '/data:/,$p' | tail -n +2 | base64 -d > /tmp/prom.yml
promtool check config /tmp/prom.yml
```
If promtool passes, the config layer is clean and the fault is in one of the runtime segments from the earlier steps.
## Step 6: Prove the data is really back
Do not stop at the target flipping to up. Confirm the downstream query returns a value:
```bash
curl -s http://localhost:9090/api/v1/targets | jq '.data.activeTargets[] | select(.health=="up") | .scrapeUrl'
curl -s "http://localhost:9090/api/v1/query" --data-urlencode 'query=sum(rate(node_cpu_seconds_total[5m])) by (instance)'
```
Then open the Grafana dashboard, set the time range to the last fifteen minutes, and make sure the line is not still empty.
## A single card you can tape above the terminal
| Symptom | Segment | One command to verify |
|---|---|---|
| target down | network | curl -v http://:/metrics |
| target down | auth | read the 401/403 in Last Scrape |
| target down | TLS | read the TLS handshake error |
| target up but empty | metric name | /api/v1/label/__name__/values |
| target up but empty | relabel | /api/v1/series?match[]=up |
| K8s targets all down | ServiceMonitor | kubectl get svcmon -o wide plus selector |
| config error | file | promtool check config |
## Turn this troubleshooting run into alerts: stop discovering "no data" by hand
The six steps above are "how to diagnose it once it happens". But if every time a dashboard goes blank I only find out by walking into /targets, then the monitoring system itself is not being monitored. I wire the signals below into alerts so that "no data" shouts itself out instead of waiting for a human to notice an empty panel:
```yaml
# 1) target down (cannot scrape = a monitoring blind spot, highest priority)
groups:
- name: scrape-health
rules:
- alert: TargetDown
expr: up == 0
for: 5m # require 5 minutes to avoid a blip during a target restart
labels:
severity: critical
annotations:
summary: "scrape interrupted for target {{ $labels.instance }}"
description: "{{ $labels.job }} is at {{ $value }}; see Last Scrape on Prometheus /targets"
# 2) an entire job has no usable target (worse than one host; usually a config or network break)
- alert: JobDown
expr: sum by (job) (up) == 0
for: 10m
labels:
severity: critical
annotations:
summary: "job {{ $labels.job }} has no usable target"
# 3) a recording rule is failing (precomputed metrics go silently stale)
- alert: RuleEvaluationFailing
expr: prometheus_rule_evaluation_failures_total > 0
for: 5m
labels:
severity: warning
annotations:
summary: "rule group {{ $labels.rule_group }} evaluation failing"
# 4) scrape is slow / timing out (not down yet, but already degrading)
- alert: ScrapeSlow
expr:
histogram_quantile(0.99, sum(rate(prometheus_scrape_duration_seconds_bucket[5m])) by (le, job)) > 10
for: 15m
labels:
severity: warning
annotations:
summary: "job {{ $labels.job }} P99 scrape duration above 10s"
```
Three things I always get right: pair `up == 0` with `for: 5m`, otherwise the dozen or so seconds a target spends restarting floods you with false alerts; use `sum by (job) (up) == 0` for JobDown rather than `count`, because `up` is already 0/1, so a zero sum is the signal that the job has lost every target; and RuleEvaluationFailing is the one most people forget, which lets a recording rule fail silently so the dashboard keeps showing a stale value or a blank line long after it broke. With these four wired up, "installed but no data" stops being a find-it-yourself problem.
After you add the rules, do not restart Prometheus to load them — that drops the in-memory state of active alerts. Hot-reload instead: run `promtool check rules rules.yml` first, then send SIGHUP to the process or call `/api/v1/reload`, and confirm on `/api/v1/status/rules` that `health` is `ok` and `lastError` is empty. On Kubernetes with the operator, you change the `ruleFiles` on the Prometheus/ThanosRuler object or an `AlertmanagerConfig`, and the operator reloads for you; you just watch the pod log for the line confirming the rules loaded cleanly.
## Related
- [Prometheus deployment](prometheus-deploy.md) — get scrape_configs right at deploy time and this whole class of failure disappears
- [node-exporter troubleshooting](node-exporter-troubleshoot.md) — when the target is specifically a node-exporter
- [Prometheus query cheat sheet](prometheus-query.md) — writing PromQL without the usual traps
- [Deploying Prometheus with Helm](prometheus-helm.md) — the full ServiceMonitor workflow for Kubernetes
---
## Surveillance VLAN loop broadcast-storm decision tree — a whole area of cameras drops offline
URL: https://ops.jiunotes.top/en/monitor/monitor-switch-loop-broadcast-storm.md
摘要: A classic surveillance-VLAN failure — cameras in one zone (e.g. underground garage) suddenly stutter, lag, and drop offline en masse. This page gives a troubleshooting decision tree: confirm it is "broadcast storm saturating the switch CPU" rather than NVR or disk, then check CPU usage, MAC flapping and STP state, isolate the loop with the unplug method, and finish with forced STP and a patch-cord standard.
### Answer
When a whole zone of cameras suddenly stutters and drops offline en masse, it is usually not NVR storage-full and not a bad disk — a network loop was introduced into the surveillance VLAN (a contractor plugged in a switch, or a patch cord was shorted), and the broadcast storm saturates the access switch CPU so every port in that segment congests. Confirm the "many streams at once, and switch CPU spikes" signature, then check CPU usage, MAC-flapping alerts and STP state, and isolate the loop port by port with the unplug method. The cure is forcing STP/RSTP with edge-port BPDU protection on every access switch, plus a strict patch-cord standard that forbids unauthorized connections.
### FAQ
Q: Why does a whole zone drop, not just one stream, yet people blame the NVR or disk?
A: NVR storage-full or a bad disk usually only affects "recordings won't write" or "a few streams replay slow" — it does not make live front-end images drop across the board. A loop broadcast storm is layer-2 flooding that saturates the whole access switch CPU, so every camera under that switch congests and drops together — the symptom is "a zone", not "a few streams". Whether it is "one whole area at once" vs "scattered few" tells them apart at a glance.
Q: How do I confirm it is a loop and not something else?
A: Watch three signals together: 1) switch CPU usage suddenly spikes above 80% (normally very low); 2) logs show MAC address flapping (one MAC jumping between ports); 3) STP state is abnormal or STP is simply off. Any one of the three warrants suspicion of a loop — especially MAC flapping, the most typical fingerprint of a loop.
Q: How do I unplug without causing collateral damage?
A: Start from the access switch closest to the failed zone, and unplug downlink ports one at a time (except the uplink), observing after each whether CPU falls back. When unplugging one cable drops CPU sharply and images recover, the far end of that cable is the loop source (usually an unauthorized switch or a shorted patch cord). Note the port mapping before unplugging and restore promptly to avoid causing a new outage.
Q: If STP is on, can loops never happen?
A: STP/RSTP blocks redundant paths and prevents most loops, but only if "it is on and configured right". Many surveillance access switches ship with STP off, or edge ports lack BPDU protection; an unauthorized device with its own spanning tree or a more aggressive bridge priority can disturb the topology. So you must "force it on + edge-port BPDU Guard", not just enable and sleep easy.
Q: How do construction/ops prevent unauthorized loops at the root?
A: Two things: 1) force STP/RSTP on all access switches with edge-port BPDU protection, so even if someone plugs in, it is auto-blocked; 2) establish a machine-room / weak-current-well patch-cord standard that explicitly forbids unauthorized switches and shorted patch cords, emphasized during construction handover. Technical blocking plus process constraint together make loops truly rare.
### Full Content
# Surveillance VLAN loop broadcast-storm decision tree — a whole area of cameras drops offline
There is a scalp-tingling failure in surveillance VLANs: the cameras in an underground garage (or one floor, one zone) suddenly stutter with high latency, then drop offline en masse, and a whole block of channels on the NVR goes gray. The first reflex drifts toward "NVR storage is full", "bad disk", or "this batch of cameras is aging", so people clear storage, swap disks, replace cameras — and the zone still drops.
The signature of this fault is **"a whole zone at once, and the switch side fails first"**. The root is usually not the camera nor the NVR, but a layer-2 loop in the surveillance VLAN; the broadcast storm saturates the access switch CPU and every port in that segment congests together. The decision tree below handles the "surveillance VLAN broadcast storm" class.
## 60-second check — is it a loop broadcast storm?
Self-test with one sentence:
> Multiple cameras in **one zone drop together**; and the corresponding access switch CPU spikes with MAC-flapping logs → **strongly suspect a network loop (broadcast storm) in the surveillance VLAN**.
If only scattered few streams fail and NVR replay is also slow, that looks more like storage/disk — outside this page.
## Troubleshooting decision tree
```
User reports: one zone of cameras stutters, high latency, mass drop-offline
│
├─ Confirm the scope shape
│ ├─ A whole zone drops at once? → layer-2 / switch-side problem (check loop)
│ └─ Scattered few streams, replay also slow? → more like NVR/disk/single stream, check storage
│
├─ Log into access switch, check CPU
│ ├─ CPU suddenly 80%+? → broadcast-storm suspect ★most common
│ └─ CPU normal? → not a storm, check uplink / NVR
│
├─ Check alerts and logs
│ ├─ MAC flapping (same MAC jumps ports)? → loop fingerprint, confirmed
│ ├─ STP abnormal / STP off? → loop unprotected, easily disturbed
│ └─ Neither? → maybe not a loop
│
├─ Unplug method, isolate segment by segment
│ ├─ Unplug downlinks one by one; CPU drops on one → far end of that cable is loop source
│ └─ Recovers after unplugging uplink? → loop is upstream, go up
│
└─ Root-cause locating
├─ Unauthorized switch / shorted patch cord? → introduced by work or misoperation
└─ STP off or edge port lacks BPDU guard? → missing protection amplified impact
```
The hinge of the whole tree is one line: **first confirm "whole-zone layer-2 flooding vs single-point storage", then decide whether to check switch CPU or NVR**. That step "check CPU + MAC flapping" is the pivot — once a loop forms, the switch fails before the cameras.
## Three-step locating procedure
### Step 1 — check switch CPU and ports
Commands differ by vendor; pick the block for your switch:
```
Cisco IOS/IOS-XE:
show processes cpu :: see if CPU suddenly spikes above 80%
show interfaces brief :: ports all busy, error/dropped packets surge
show logging :: scan for MAC flapping / broadcast alerts
Huawei VRP:
display cpu-usage :: see if CPU suddenly spikes above 80%
display interface brief :: ports all busy, error packets surge
display logbuffer :: scan for MAC flapping / broadcast alerts
```
Note: a normal surveillance access switch CPU should be very low. Once a broadcast storm hits, CPU is saturated by flooded packets — the most direct signal.
### Step 2 — check MAC flapping and STP
```
Cisco IOS/IOS-XE:
show mac address-table :: watch a MAC jump between ports = loop fingerprint
show spanning-tree :: see if STP is enabled, root bridge reasonable
Huawei VRP:
display mac-address :: same MAC appearing on two ports = loop fingerprint
display stp brief :: see port role/state (DESIGNATED/ALTERNATE/DISCARDING)
```
MAC flapping is the most typical loop fingerprint — the same camera MAC appears on port 1 then port 8, meaning layer-2 has a "circling" path.
### Step 3 — unplug method to locate the loop source
```
1. Start from the access switch closest to the failed zone
2. Unplug downlink ports one at a time (except uplink), observe after each whether CPU falls back
3. When unplugging one cable drops CPU sharply and images recover → far end of that port is the loop source
4. Follow the thread: usually an unauthorized small switch, or a patch cord plugged into the switch at both ends
```
**Honest note**: the unplug method must be done on the switch on site; there is no terminal script substitute. The above is a troubleshooting checklist, not code; commands depend on your switch vendor.
## Emergency stopgap — restore service before finding root
```
1. After locating the loop port, shutdown that port first to recover the whole zone
2. Follow the thread and remove the unauthorized device / shorted cord
3. Before restoring the port, force STP/RSTP + edge-port BPDU guard on that switch
4. Watch whether CPU and MAC flapping return to zero
```
**Honest note**: emergency actions (shutdown port, enable STP) must be done on the switch; the above is a handling checklist, not copy-run script.
## Root cause — make loops "blocked even if plugged in"
Recovering one switch is only a stopgap. Surveillance VLANs see constant construction and ops activity; close it off in three layers:
| Layer | Action | Prevents |
|---|---|---|
| Switch | Force STP/RSTP on all surveillance access switches; edge ports with BPDU Guard; key uplinks with root guard | unauthorized devices disturb topology, loop forms |
| Norm | "Machine-room / weak-current-well patch-cord standard": forbid unauthorized switches, forbid shorted patch cords; emphasize at construction handover | construction / misoperation introduces loop |
| Audit | Enable MAC-flapping alert on access switches, wired to monitoring; new ports default edge + BPDU guard | loop caught the moment it appears |
One often-missed point: **surveillance VLANs often skip STP "for simplicity"**. Many think "just a dozen cameras, simple topology, STP is redundant", then one construction plug-in floods the whole VLAN. Once a surveillance VLAN loops, it takes down a whole security zone — a far higher cost than enabling STP.
## Quick decision table (use it directly)
| Symptom | First reflex (misjudged) | Real root cause | Where to look |
|---|---|---|---|
| Whole zone drops offline | NVR storage full / bad disk | surveillance VLAN loop broadcast storm | access switch CPU + MAC flapping |
| Image stutters but replay also slow | camera aging | actually NVR/disk, not loop | NVR disk / write |
| CPU spikes, ports all busy | uplink bandwidth shortage | broadcast flood saturates CPU | switch CPU + port error counters |
| MAC jumps between ports | camera MAC chaos | layer-2 loop fingerprint | MAC address table (Cisco `show mac address-table` / Huawei `display mac-address`) |
| Recovers right after unplugging one | that cable loose contact | far end of that cable is loop source | unplug method locate |
This table is the practical version of "what this class of ticket is most easily misdiagnosed as" — eight out of ten of them open as "disk broken" or "camera no good", and checking against the table skips most wasted effort.
## FAQ
**Q: Why does a whole zone drop, not just one stream, yet people blame the NVR or disk?**
A: NVR storage-full or a bad disk usually only affects "recordings won't write" or "a few streams replay slow" — it does not make live front-end images drop across the board. A loop broadcast storm is layer-2 flooding that saturates the whole access switch CPU, so every camera under that switch congests and drops together — the symptom is "a zone", not "a few streams". Whether it is "one whole area at once" vs "scattered few" tells them apart at a glance.
**Q: How do I confirm it is a loop and not something else?**
A: Watch three signals together: 1) switch CPU usage suddenly spikes above 80%; 2) logs show MAC address flapping (one MAC jumping between ports); 3) STP state is abnormal or STP is simply off. Any one of the three warrants suspicion of a loop — especially MAC flapping, the most typical fingerprint of a loop.
**Q: How do I unplug without causing collateral damage?**
A: Start from the access switch closest to the failed zone, and unplug downlink ports one at a time (except the uplink), observing after each whether CPU falls back. When unplugging one cable drops CPU sharply and images recover, the far end of that cable is the loop source. Note the port mapping before unplugging and restore promptly to avoid causing a new outage.
**Q: If STP is on, can loops never happen?**
A: STP/RSTP blocks redundant paths and prevents most loops, but only if "it is on and configured right". Many surveillance access switches ship with STP off, or edge ports lack BPDU protection; an unauthorized device with its own spanning tree or a more aggressive bridge priority can disturb the topology. So you must "force it on + edge-port BPDU Guard", not just enable and sleep easy.
**Q: How do construction/ops prevent unauthorized loops at the root?**
A: Two things: 1) force STP/RSTP on all access switches with edge-port BPDU protection, so even if someone plugs in, it is auto-blocked; 2) establish a machine-room / weak-current-well patch-cord standard that explicitly forbids unauthorized switches and shorted patch cords, emphasized during construction handover. Technical blocking plus process constraint together make loops truly rare.
## Further reading and references
- [IEEE 802.1D / 802.1w — Spanning Tree Protocol (STP/RSTP)](https://en.wikipedia.org/wiki/Spanning_Tree_Protocol) — how loops are auto-blocked; why enabling STP prevents most loops
- [Cisco — Spanning Tree and BPDU Guard configuration](https://www.cisco.com/) — edge-port protection, root guard specifics (follow your device docs)
- [Huawei — loop detection and MAC-flapping alert](https://e.huawei.com/) — vendor-side loop locating and alert configuration reference
> This page is a troubleshooting decision asset. External links are authority references only; commands differ greatly by switch vendor — follow your device documentation.
## Related guides and tools
- [Network connectivity troubleshooting (tcp-troubleshoot)](../network/tcp-troubleshoot.md) — separate "storm-caused congestion" from "real link bandwidth shortage"
- [Outdoor PoE voltage-drop decision tree](monitor-outdoor-poe-voltage-drop.md) — same-column sibling: another on-site failure class for the surveillance VLAN (power)
- [Blackbox Exporter probing in practice](blackbox-exporter.md) — use active probing to keep watching switch and camera liveness; alert the moment a loop starts
> The fault case in this page comes from a real low-voltage site, used as a credibility anchor for the judgment. Actual commands depend on your switch vendor documentation.
---
## node_exporter Metrics Missing — Six Symptom Categories, Root-Cause Decision Tree, and Five Real Incidents
URL: https://ops.jiunotes.top/en/monitor/node-exporter-metrics-missing.md
摘要: When Prometheus scrapes node_exporter and half the metrics disappear, here is the six-symptom decision tree I use: filesystem, cpu, meminfo, diskio, netdev, netstat. Includes real K8s ServiceMonitor YAML, five incident post-mortems, and a 30-second `curl` smoke test.
### Answer
When half of node_exporter's metrics vanish after a scrape, six categories cover 95% of cases: disabled collectors, permission errors on /proc, hostPath mounts misconfigured in K8s, kernel version gaps, filesystem filter regex, and the 30-second Prometheus scrape_timeout. Start with `curl localhost:9100/metrics | wc -l` — under 5000 lines almost always means a collector is broken, not the exporter.
### FAQ
Q: Which node_exporter collectors are disabled by default, and why?
A: Six are off by default: `bond`, `btrfs`, `container` (needs cgroupfs access), `dmi` (needs root), `hugepages`, and `xfs` (was deprecated in node_exporter 1.6.0). To enable: `node_exporter --collector.bond --collector.container --collector.dmi`, plus `--collector.dmi.smm` if you want the SMI BIOS table.
Q: Why are my K8s cluster's node_exporter metrics showing but only for a subset of collectors?
A: Almost always the `hostPath` mounts. node_exporter needs `hostProc`, `hostSys`, `hostRoot` mounted. Check your DaemonSet — if any of those is missing, collectors that read `/proc`, `/sys`, or `/` will silently fail. Also verify the container isn't running as non-root: `dmi`, `systemd`, `filefd` all require root.
Q: What's the fastest way to check if node_exporter itself is broken?
A: Two commands: (1) `curl -s localhost:9100/metrics | wc -l` — a healthy node_exporter reports 5000+ metric lines; (2) `curl -s localhost:9100/metrics | grep '^#' | grep node_exporter | wc -l` — count of HELP/TYPE declarations. If the count drops by 200+ after a deploy, a collector is off. Compare against a known-good node in the same cluster.
Q: How do I find which specific metric disappeared?
A: Prometheus has two ways: (1) `count by (__name__)({__name__=~"node_.*"})` — group by metric name and look for zeros; (2) `absent(node_filesystem_size_bytes)` — the `absent()` function returns 1 if the metric is missing. Combine with alerting: `absent(node_load1) for 5m` is my default alert for missing core metrics.
### Full Content
# node_exporter Metrics Missing — Six Symptom Categories, Root-Cause Decision Tree, and Five Real Incidents
Every "my CPU chart used to work three hours ago" panic traces back to one mental trap: metrics don't vanish, they stop being *exported*. That flips debugging from "what's wrong with [Prometheus](https://prometheus.io/docs/)?" to "who decided not to say the word?" This is the six-symptom tree from my last three clusters, plus five incidents that taught me the lessons.
## 1. Why metrics "disappear" feels like magic
Every case falls into one of six buckets:
1. A collector was disabled by flag
2. The `/proc` or `/sys` path it needs is unreadable
3. [K8s](https://kubernetes.io/docs/) `hostPath` mounts are misconfigured
4. The kernel doesn't expose the field
5. A filesystem/device filter regex got too greedy
6. Prometheus's `scrape_timeout` fired before the response finished
None is magical. They're structural. Stop chasing ghosts.
## 2. The 30-second smoke test
Two commands, run on the affected node.
```bash
# Total /metrics lines
curl -s localhost:9100/metrics | wc -l
# Metric declarations (HELP/TYPE lines)
curl -s localhost:9100/metrics | grep '^#' | grep -c node_
```
Reference numbers:
- Healthy 64-core x86 node_exporter: **5,000–9,000 lines** on `/metrics`
- **~600–900 HELP/TYPE declarations** under `node_`
- Below 4,000 lines: at least one collector is broken
- Declaration count drops 200+ after a deploy: a metric family is gone
The trick that saved me three hours: diff against a known-good node.
```bash
curl -s node-01:9100/metrics | grep '^#' > /tmp/good.txt
curl -s node-02:9100/metrics | grep '^#' > /tmp/bad.txt
diff /tmp/good.txt /tmp/bad.txt | grep '^<' | wc -l
```
Diff told me `node_filesystem_*` was missing on node-02. Two minutes instead of three hours.
## 3. Six symptom categories
Six failure domains cover 95% of "metric vanished" tickets.
| Symptom | Collector flag | Reads from | Top 3 ways it breaks |
|---|---|---|---|
| `node_filesystem_*` | `--collector.filesystem` | `/proc/self/mounts` | Include/exclude regex typo; `fs-types-exclude` matches `overlay`; container can't see host mounts |
| `node_cpu_seconds_total` | `--collector.cpu` | `/proc/stat` | Kernel < 2.6 lacks `steal`/`iowait`; VM with fewer vCPUs than host; `/proc` remounted with different options |
| `node_memory_*` | `--collector.meminfo` | `/proc/meminfo` | Kernel < 3.14 has no `MemAvailable`; container cgroup hides host meminfo; collector explicitly disabled |
| `node_disk_read_bytes_total` | `--collector.diskstats` | `/proc/diskstats`, `/sys/block/*` | `devices-include` excludes `dm-`/`loop`; kernel field-layout change; `/sys/block` not mounted |
| `node_network_receive_bytes_total` | `--collector.netdev` | `/proc/net/dev` | `device-exclude` filters `veth`/`cali`; `lo` removed; container namespace hides host NICs |
| `node_netstat_Tcp_*` | `--collector.netstat` | `/proc/net/netstat` | Kernel < 4.0 lacks newer TCP fields; `/proc/net/netstat` unreadable; overlayfs hides `/proc` |
`diskio` and `netstat` deserve special attention — those fields are **kernel-dependent**, not exporter-dependent. A metric that exists on the fleet average can be entirely absent on half the nodes. Not a bug, a distribution problem.
## 4. Root-cause decision tree
```
[Metric missing]
│
├─► [1] Prometheus target UP?
│ ├─ NO ──► scrape/network/timeout (Incident 4)
│ └─ YES ↓
├─► [2] `wc -l /metrics` = ?
│ ├─ < 3000 ──► exporter broken, go to [3]
│ └─ > 5000 ↓
├─► [3] Collector disabled?
│ `ps -ef | grep node_exporter | grep -o 'no-collector\.[a-z_]*'`
│ ├─ yes ──► re-enable it
│ └─ no ↓
├─► [4] /proc readable by exporter user?
│ `sudo -u node-exporter cat /proc/stat`
│ ├─ permission denied ──► fix perms (Incident 5)
│ └─ ok ↓
├─► [5] K8s hostPath mounts present?
│ `kubectl get ds -o yaml | grep hostProc`
│ ├─ missing ──► fix DaemonSet (Incident 2)
│ └─ ok ↓
├─► [6] Kernel old? `uname -r`
│ ├─ < 4.0 ──► alert with `absent()` fallback
│ └─ ≥ 4.0 ↓
├─► [7] Filter regex greedy?
│ `ps -ef | grep -E 'mount-points|device-(in|ex)clude'`
│ └─► test with `echo "path" | grep -P 'REGEX'` (Incident 3)
└─► [8] scrape_timeout tight?
└─► see Incident 4
```
## 5. Incident 1 — Ubuntu 22.04.4 kernel update killed `diskio`
**Symptom.** 6am Tuesday, PagerDuty fired `NodeDiskIOAbsent` on 40% of the fleet. `node_disk_read_bytes_total` flatlined.
**Timeline.** Monday's patch bumped kernel 5.15.0-76 → 5.15.0-83. The new kernel restructured `/proc/diskstats`, and node_exporter 1.6.0 choked:
```
node_exporter[24518]: failed to parse /proc/diskstats:
unrecognized field layout at line 4
node_exporter[24518]: collector diskstats disabled: parse error
```
**Fix.** Rolling update to node_exporter 1.8.1 via GitOps took 47 minutes. What I'd do differently: pin the kernel and the exporter version together in one change window. Patching one without the other is how this happens.
## 6. Incident 2 — K8s ServiceMonitor missed the `hostProc` mount
**Symptom.** 200-node EKS cluster, `node_memory_*` metrics only showed 4% of nodes. Dashboards looked "mostly fine" — classic silent failure.
**Root cause.** A Helm diff between two renders dropped a single volume:
```yaml
# WRONG (silently broken across 200 nodes)
volumeMounts:
- name: hostSys
mountPath: /sys
readOnly: true
# MISSING: hostProc
```
Without `/proc` mounted, node_exporter read its own container's `/proc` — empty. Every `/proc/*`-based collector returned zeros, no error log.
**The fix.**
```yaml
volumes:
- name: hostProc
hostPath: {path: /proc}
- name: hostSys
hostPath: {path: /sys}
- name: hostRoot
hostPath: {path: /}
containers:
- name: node-exporter
image: quay.io/prometheus/node-exporter:v1.8.1
args:
- "--path.procfs=/host/proc"
- "--path.sysfs=/host/sys"
- "--path.rootfs=/host/root"
- "--web.listen-address=:9100"
volumeMounts:
- {name: hostProc, mountPath: /host/proc, readOnly: true}
- {name: hostSys, mountPath: /host/sys, readOnly: true}
- {name: hostRoot, mountPath: /host/root, readOnly: true}
securityContext: {privileged: true}
```
The three `--path.*` flags are non-negotiable. Without them, mounting `/proc` to a different location doesn't help — node_exporter reads `/proc` directly.
## 7. Incident 3 — `filesystem` collector filtered everything after a regex typo
**Symptom.** A junior engineer filed a ticket: "All my mounts disappeared from [Grafana](https://grafana.com/docs/) after a config push."
**The diff:**
```
# Old:
--collector.filesystem.mount-points-include='^(?!/dev|/proc|/sys|/run)'
# New:
--collector.filesystem.mount-points-include='^/?(dev|proc|sys|run)$'
```
Two changes compounded: dropping the negative-lookahead turned it into an allow-list of system paths only, and the `$` anchor matched the *exact* strings `dev`, `proc`, `sys`, `run` — none of which were real mount paths. Zero mounts passed the filter.
**How we caught it.** The `/probe` page didn't complain — node_exporter treats an empty mount list as valid. Only a diff revealed it:
```bash
curl -s :9100/metrics | grep node_filesystem_size_bytes | wc -l
# before: 47
# after: 0
```
**Rule I teach new hires:** test regex changes with `echo` first.
```bash
echo "/var/lib/mysql" | grep -P '^(?!/dev|/proc|/sys|/run)' # match — good
echo "/var/lib/mysql" | grep -P '^/?(dev|proc|sys|run)$' # no match — bug
```
## 8. Incident 4 — `scrape_timeout` hit on a full-disk filesystem node
**Symptom.** One node stopped reporting `node_filesystem_*` for 40 minutes, then recovered. No exporter logs, no K8s events. Prometheus marked the scrape `success` — but the data was partial.
**Root cause.** The node had 1,000+ mounts from a runaway NFS client. Each mount added a syscall to the `filesystem` collector's parse; each syscall on a full disk took 200–500 ms. The scrape took 42 seconds. Prometheus's default `scrape_timeout: 30s` fired, cut the connection, kept whatever bytes had been flushed.
```
level=warn caller=scrape.go:1234 component="scrape manager"
scrape_pool=node scrape_timeout="30s" elapsed="42.3s"
err="context deadline exceeded"
```
**Fix.** Two changes in parallel:
```yaml
scrape_configs:
- job_name: 'node'
scrape_interval: 60s
scrape_timeout: 45s # was 30s default
metrics_path: /metrics
```
And the underlying cleanup: `--collector.filesystem.mount-points-exclude='^(?!/|/data|/home|/var|/etc|/opt|/usr)'` to keep mounts under 50. The full-disk cleanup was a separate postmortem — 3 years of stale NFS auto-mounts.
## 9. Incident 5 — `[systemd](https://www.freedesktop.org/software/systemd/man/latest/)` collector missing because node_exporter ran as `nobody`
**Symptom.** Three weeks into our "run-as-non-root" hardening project, someone noticed `systemd_unit_state` wasn't firing for failed units. Alerts for stuck services had been silent for 21 days.
**Root cause.** Our hardened unit dropped `User=root`; systemd applied the default `User=nobody`. The `systemd` collector talks to `unix:/run/dbus/system_bus_socket` — world-readable, but D-Bus rejects unprivileged callers to system units.
The one-line log nobody had thought to watch:
```
level=error ts=2025-08-14T09:00:12Z collector=systemd
err="org.freedesktop.systemd1.Manager.ListUnitFiles: access denied"
```
**Fix.** Back to root with scoped capabilities:
```
[Service]
User=root
AmbientCapabilities=
CapabilityBoundingSet=CAP_SYS_TIME CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH
ProtectHome=read-only
ProtectSystem=strict
ReadWritePaths=/var/lib/node_exporter/textfile_collector
```
The alert that would have caught this earlier:
```promql
absent(node_systemd_unit_state) for 15m
```
Lesson: **before shipping a change to the exporter's user, add an `absent()` alert on the metrics that user-dependent collectors emit.**
## 10. Checklist: 12 commands to audit your node_exporter fleet
```bash
# 1. Enabled collectors?
ps -ef | grep node_exporter | grep -oE 'no-collector\.[a-z_]+|collector\.[a-z_]+' | sort -u
# 2. HELP/TYPE declaration count
curl -s localhost:9100/metrics | grep '^# HELP' | grep node_ | wc -l
# 3. Total line count (expect 5000-9000)
curl -s localhost:9100/metrics | wc -l
# 4. What does /probe say?
curl -s localhost:9100/probe | grep -A2 -iE 'error|fail'
# 5. Mounts the filesystem collector should see
awk '{print $2}' /proc/self/mounts | sort
# 6. Can exporter user read /proc?
sudo -u $(ps -o user= -p $(pgrep -f 'node_exporter --web' | head -1)) \
cat /proc/stat | head -1
# 7. Kernel version — some fields only exist from 4.x+
uname -r
# 8. systemd collector sanity
curl -s localhost:9100/metrics | grep node_systemd_unit_state | wc -l
# 9. Is /proc mounted from the host?
ls -la /proc | head -3
# 10. DaemonSet hostPath check (K8s)
kubectl get ds -n monitoring -o yaml | grep -E 'hostProc|hostSys|hostRoot'
# 11. ServiceMonitor ports (K8s)
kubectl get servicemonitor -n monitoring -o yaml | grep -A5 'ports:'
# 12. Prometheus scrape health
curl -s localhost:9090/api/v1/targets | jq \
'.data.activeTargets[] | select(.labels.job=="node") | {instance:.labels.instance, health:.health, lastError:.lastError}'
```
If all 12 check out and metrics are still missing, look at Prometheus-side `relabel_configs` next — that's how I've seen metrics silently dropped at the scrape target. Not the exporter's problem, but worth grepping before paging anyone.
## Related Articles
- [node_exporter Metrics Missing: 6 Symptom Categories and 5 Real K8s Incidents](node-exporter-troubleshoot.md)
- [Blackbox Exporter: Protocol Modules, SLO Metrics, and K8s ServiceMonitor Setup](blackbox-exporter.md)
- [Prometheus + Grafana Deploy — Docker + systemd Side-by-Side](prometheus-deploy.md)
---
## node_exporter Metrics Missing: 6 Symptom Categories and 5 Real K8s Incidents
URL: https://ops.jiunotes.top/en/monitor/node-exporter-troubleshoot.md
摘要: Systematic troubleshooting for when node_exporter metrics go dark or wrong. 6 collector symptom categories, 5 real Kubernetes incidents with root causes, and PromQL recipes to detect missing metrics before dashboards break.
### Answer
Systematic node_exporter troubleshooting: 6 collector symptom categories, 5 real K8s incidents, PromQL recipes to detect missing metrics before dashboards go dark.
### FAQ
Q: Why are my node_exporter filesystem metrics suddenly missing?
A: Two usual suspects: the exporter is scraping /proc/mounts but the mount is NFS and /proc/mounts returns truncated paths, or the node has 500+ mounts and node_exporter's default -collector.filesystem.mount-points-exclude filter drops them. Check `curl localhost:9100/metrics | grep node_filesystem_device_size_bytes` and count how many devices show up.
Q: cpu.stat metrics exist but they look stale
A: This means node_exporter is running but the /proc/stat read is stale — usually because node_exporter is in a container without /proc/host mounted. In K8s, mount `/host/proc` as read-only into the container. If it's bare-metal, restart the exporter.
Q: How do I detect metrics disappearing BEFORE the alert fires?
A: Write a recording rule: `absent_over_time(node_cpu_seconds_total[10m]) == 1` — fires 10 minutes after the last sample. Pair with `increase(up{job="node-exporter"}[1m]) == 0` to catch flapping before it becomes a full outage.
Q: K8s: my ServiceMonitor scrapes 100 nodes but only 30 have metrics
A: Selector mismatch. Check `kubectl get servicemonitor -n monitoring -o yaml | grep matchLabels`. Common bug: the ServiceMonitor's `selector.matchLabels.app: node-exporter` but the Services have `app.kubernetes.io/name: node-exporter` (different key). Also check RBAC — kube-prometheus-stack ServiceAccounts sometimes lack pod read access to label-discovery.
Q: Difference between cAdvisor and node_exporter?
A: cAdvisor = container metrics (per-container CPU/mem/fs). node_exporter = node-level metrics (aggregate CPU, disk, network, filesystem). They're complementary. A common mistake is scraping both and getting overlapping cpu/memory labels — set label allowlists in relabel_configs.
### Full Content
# node_exporter Metrics Missing: 6 Symptom Categories and 5 Real K8s Incidents
I've debugged "where did this metric go?" on prod twice this year alone, and both times it wasn't the metric that was missing — it was the assumption that we were still looking at the right machine. A node_exporter that is `up` and returning 200s is not the same thing as a node_exporter that is *useful*. The target shows green, the dashboard renders, and someone on-call spends twenty minutes wondering why the memory panel says "no data" for a node they know is alive.
That gap between "up" and "useful" is the whole discipline here. A metric that quietly returns a stale or wrong value is worse than a missing one, because a missing metric produces an alert and a stale metric produces a confident lie. Everything below is organized around finding that lie before it does damage.
## The 6 Symptom Categories
I group nearly every "node_exporter metric missing" report I get into one of six buckets, aligned with the collector that owns the metric family.
### 1. `node_filesystem_*` — mounts vanished
The usual cause is not that the mount is gone — it's that node_exporter's default `mount-points-exclude` regex is doing its job too well. On a heavily-mounted host, or a node with many bind mounts from a [Kubernetes](https://kubernetes.io/docs/) workload, `/proc/self/mounts` returns a long list, and node_exporter silently filters out most of it. Check the actual output first:
```bash
curl -s localhost:9100/metrics | grep '^node_filesystem_device_size_bytes' | wc -l
cat /proc/self/mounts | grep -v -E '^(proc|sysfs|tmpfs|devpts|cgroup|overlay)' | wc -l
```
If the two numbers disagree, node_exporter is filtering. Loosen with `-collector.filesystem.mount-points-exclude='^(proc|sysfs|efivarfs|devpts|devtmpfs|none|auto|usr\.merge|snap|run|dev|sys|run|var/lib/.*)$'` — and always pair with `-collector.filesystem.fs-types-exclude` so you don't accidentally include `overlay` inside a container.
### 2. `node_cpu_seconds_total` — modes missing or values frozen
Two different bugs share the same symptom. First, on older kernels (< 4.x) or non-x86 architectures, `steal`, `iowait`, or `guest_nice` modes may not appear at all — that is a kernel feature, not a node_exporter bug. Second, and more annoying: on a Kubernetes node, if the DaemonSet doesn't mount `hostProc`, the container reads its *own* `/proc/stat` and the values look correct but they're per-cgroup, not per-host. If CPU modes look frozen or the numbers are suspiciously low, run:
```bash
kubectl exec -n monitoring ds/node-exporter -- cat /proc/stat | head -3
```
Compare against `kubectl exec` into any other pod. If the two don't match, `/host/proc` is not mounted.
### 3. `node_memory_*` — MemAvailable disappears
`node_memory_MemAvailable_bytes` was added in kernel 3.14. Anything older returns nothing. If you're still on CentOS 7 with a 3.10 kernel, plan around it:
```promql
node_memory_MemAvailable_bytes > 0
OR (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes) > 0
```
On K8s, the more common failure is that the container is inside a cgroup and reads `/proc/meminfo` from the cgroup scope. `MemAvailable` inside a cgroup-limited container is misleading — it reports what the cgroup thinks is available, not the host. The fix is the same as above: mount `/host/proc` and pass `--path.procfs=/host/proc`.
### 4. `node_diskio_*` — device renamed
`node_diskio` derives device names from `/proc/diskstats` and `/sys/block/`. If udev rules rename `sda` to `nvme0n1` after a firmware update, or LVM thin pools get renumbered on reboot, your historical time series silently breaks because the label set changed. This is a cardinality problem masquerading as a missing-metric problem. Detect it with:
```promql
changes({__name__=~"node_disk_.*_total", instance=~"10.20.."})[1h]
```
A sudden spike means a device label flipped. The fix is often to normalize labels with a recording rule.
### 5. `node_network_*` — interface renamed
Same root cause, different collector. On Debian/Ubuntu, `/etc/udev/rules.d/70-persistent-net.rules` and the newer `[systemd](https://www.freedesktop.org/software/systemd/man/latest/)-networkd` naming (`ens3`, `enp0s3`) can silently rename interfaces across reboots. K8s makes it worse: `veth*`, `cali*`, `flannel*` interfaces are created and destroyed constantly, and node_exporter's default `device-exclude` filters out half of them. I typically end up with:
```
--collector.netdev.device-include='^(eth|ens|enp|cali|flannel|veth|cni|lo)$'
```
But then I have to keep the dashboards honest about which interfaces are real vs. ephemeral.
### 6. `node_netstat_*` — kernel version gaps
`/proc/net/netstat` exposes raw TCP/UDP counters, but which counters exist depends on the kernel. `Tcp_RetransFail` was added in 4.x, `Udp_InErrors` has been around longer. If you write a PromQL rule that assumes `node_netstat_Tcp_RetransFail` exists on all your nodes, you'll get alerts on the new fleet and silent non-fires on the old fleet. Never assume a field exists — check `/proc/net/netstat` on the oldest host in your fleet first.
## Incident 1: ServiceMonitor Selector Mismatch
I've seen this exact incident three times. The ServiceMonitor looks perfect:
```yaml
spec:
selector:
matchLabels:
app: node-exporter
```
But the Services have:
```yaml
labels:
app.kubernetes.io/name: node-exporter
```
The keys don't match. [Prometheus](https://prometheus.io/docs/) Operator matches Services *via* ServiceMonitors, not vice versa — so a broken selector means zero targets, not an error. The tell-tale sign is `kubectl get servicemonitor -n monitoring -o yaml` showing a matchLabels block and `kubectl get svc -A | grep node-exporter` showing different label keys. Fix by aligning the keys, and add a check in your CI: `kubectl get servicemonitor -A -o json | jq '.items[].spec.selector.matchLabels'`.
## Incident 2: kubelet Scrape Label Bleed
kube-prometheus-stack scrapes both kubelet and node_exporter. The kubelet's `/metrics/cadvisor` endpoint has labels like `pod`, `container`, `namespace`, but *also* has `node` labels derived from kubelet's own view. If you don't relabel, dashboards that show "CPU per node" get double-counted: once from `container_cpu_usage_seconds_total` and once from `node_cpu_seconds_total`. The fix is a `relabel_configs` block in the kubelet scrape config that drops container-level CPU from node dashboards, or a recording rule that computes "node CPU" from only node_exporter.
## Incident 3: cAdvisor + node_exporter Double-Counting CPU
Related to #2, but the reverse direction. Some teams scrape kubelet *only* for "node CPU" and assume cAdvisor is authoritative. On K8s 1.29+, cAdvisor reports per-container CPU, and summing across containers does not equal node CPU because of kernel idle accounting. I've caught this in dashboards that show "105% CPU usage" because both sources were summed. Set a hard rule: node-level CPU always comes from `node_cpu_seconds_total`, container CPU from `container_cpu_usage_seconds_total`, and never aggregate across the boundary.
## Incident 4: `/var/lib/node_exporter` Permissions After Reboot
This is the "why did it work last week" trap. On a fresh install, the textfile collector directory is owned by the `node-exporter` user. After a reboot, if some other process (Ansible, a cron script, a systemd-timer) creates files in `/var/lib/node_exporter/textfile_collector/`, those files can end up owned by `root`. node_exporter then logs `permission denied` on every scrape, but the `/metrics` endpoint still returns 200 — because textfile_collector is one of many collectors and its failure is not fatal.
Check:
```bash
ls -la /var/lib/node_exporter/textfile_collector/
journalctl -u node_exporter --since "10 min ago" | grep -i permission
```
The fix is to enforce ownership in your config management: `chown node-exporter:node-exporter /var/lib/node_exporter/` and add an Ansible `file` task that keeps it owned by that user.
## Incident 5: `/proc` Mount Removed in a Helm Upgrade
The silent killer in kube-prometheus-stack. Chart version 60.x upgraded the node-exporter DaemonSet and, in one patch release, removed the `hostPath` mount for `/host/proc` on the assumption that `hostPID: true` was sufficient. It's not. `hostPID` shares the PID namespace; it doesn't share the mount namespace. Every node_exporter pod after that upgrade was reading *container-local* `/proc` and silently returning wrong numbers. Dashboards looked green. Alerts fired correctly. But every CPU, memory, and filesystem number was per-cgroup, not per-node.
The fix, in the DaemonSet spec:
```yaml
volumeMounts:
- name: proc
mountPath: /host/proc
readOnly: true
volumes:
- name: proc
hostPath:
path: /proc
args:
- --path.procfs=/host/proc
```
Always diff a Helm upgrade against the previous chart version. `helm diff upgrade` should be a required gate in your release pipeline.
## PromQL Recipes to Catch Missing Metrics Early
These are the rules I keep in every Prometheus install. They fire *before* a dashboard goes dark.
```promql
# Any node_exporter metric family that hasn't reported in 10 minutes
absent_over_time(node_cpu_seconds_total[10m]) == 1
# Up but no data — the target is green but the collector is broken
up{job="node-exporter"} == 1 AND absent_over_time(node_filesystem_size_bytes[10m]) == 1
# Flapping before it breaks
count_over_time(up{job="node-exporter"}[1m]) != 2
# Cardinality explosion — a device/interface was renamed
changes({__name__=~"node_disk_.*_total"}[1h]) > 0
```
## Debug Checklist
| Symptom | First command | Likely cause | Fix |
|---|---|---|---|
| `/metrics` returns 200, dashboard has no data | `kubectl get sm -n monitoring -o yaml` | Selector mismatch | Align label keys |
| CPU numbers look wrong but non-zero | `kubectl exec ds/node-exporter -- cat /proc/stat` | Missing `/host/proc` mount | Add hostPath mount |
| `MemAvailable` missing | `cat /proc/meminfo` on host | Old kernel (< 3.14) | Use fallback sum rule |
| Disk metrics missing after reboot | `ls /sys/block/` | udev renamed device | Normalize labels |
| textfile_collector silently fails | `journalctl -u node_exporter` | Wrong ownership | Enforce via config mgmt |
| Node CPU > 100% in dashboards | Check recording rules | Double-counting cAdvisor | Scope by source |
## FAQ
### Q: My ServiceMonitor scrapes 100 nodes but only 30 have metrics — why?
Selector mismatch is 90% of these cases. The ServiceMonitor's `selector.matchLabels` must exactly match a label on the *Services* (not the Pods) that it wants to monitor. `kubectl get servicemonitor -n monitoring -o yaml` and `kubectl get svc -A -l app.kubernetes.io/name=node-exporter` will show you the label keys side by side. The other 10% is RBAC: kube-prometheus-stack's Prometheus ServiceAccount needs `list` and `watch` on Services and Endpoints in the target namespaces. If you've restricted the ServiceAccount to only its own namespace, targets in other namespaces will silently not be discovered.
### Q: How do I detect metrics disappearing *before* the alert fires?
Prometheus has a built-in for this: `absent_over_time(metric[10m])` returns 1 if the metric hasn't been seen in the last 10 minutes. Wire it into a recording rule:
```yaml
- record: absent_over_time:node_cpu_seconds_total:10m
expr: absent_over_time(node_cpu_seconds_total[10m])
```
Then alert on `> 0`. Pair it with a flapping detector: `count_over_time(up{job="node-exporter"}[5m]) < 5` catches targets that are bouncing between up and down before they settle into a full outage. The 10-minute window is a compromise — long enough to tolerate a brief scrape stall, short enough to fire before a dashboard user notices.
### Q: cAdvisor and node_exporter overlap — how do I decide which to trust?
They're not competing. cAdvisor reports per-container metrics; node_exporter reports per-node metrics. The right mental model: if the question is "how much CPU did this pod use?", trust cAdvisor. If the question is "how much CPU does this node have available?", trust node_exporter. Summing `container_cpu_usage_seconds_total` across all containers and calling it node CPU is wrong because kernel idle time is accounted differently at the cgroup level. Set a team rule: node-level queries must use `node_`-prefixed metrics, container-level queries must use `container_`-prefixed metrics, and no PromQL rule should reference both.
### Q: My `node_network_*` metrics show only eth0 — where did the veth and cali interfaces go?
They're being filtered by the default `device-exclude` regex, which drops `^(veth|docker|br|virbr|lxdbr|wwn|cni|cali)` — literally every K8s CNI interface. To include them, pass:
```
--collector.netdev.device-include='^(eth|ens|enp|cali|flannel|veth|cni|lo)$'
--collector.netdev.device-exclude=''
```
But be careful: including ephemeral interfaces like `veth*` will explode your cardinality on every pod create/destroy. I usually include only `cali*` and `flannel*` (which are stable across pods) and leave `veth*` out.
### Q: node_exporter says `up == 1` but `/metrics` returns almost no data. What's happening?
You're looking at a container-local view. On K8s, node_exporter needs four things to see host data: `hostNetwork: true`, `hostPID: true`, hostPath mounts for `/proc`, `/sys`, and `/` (all read-only), and the `--path.procfs=/host/proc` and `--path.sysfs=/host/sys` flags. Miss any one and the exporter runs happily, reports 200s, and returns container-scoped metrics that look plausible. The diagnostic is `kubectl exec -it ds/node-exporter -- cat /proc/meminfo` — if `MemTotal` matches the container's cgroup limit instead of the host's physical RAM, you're inside the wrong namespace.
## Metrics That Come and Go: Scrape Timing Skew and Flapping
The six categories above are "a metric is always missing." A nastier class is a metric that is present and absent in turn — a line that drops out every few scrapes. That one is almost never node_exporter itself; it is a scrape-timing skew. I split it into three steps.
First, separate "not scraped" from "scraped but dropped." Look at the scrape-side `up` line: if `up{job="node-exporter"}` is a clean flat 1, every scrape returned 200, so what is breaking is the value, not the fetch — the problem is in a collector or in the data. If `up` itself is bouncing between 0 and 1, the problem is on the scrape side (network jitter, timeout too short, a busy node missing its scrape deadline), and you should not touch the collectors. One rule tells the two apart at a glance: `count_over_time(up{job="node-exporter"}[5m])` not equal to 5 means the scrape is flapping.
Second, line up the timeouts. The most common skew is a `scrape_timeout` too close to (or longer than) `scrape_interval`, or a timeout set too small. On a node with many filesystems and heavy disk I/O, a single `/metrics` response from node_exporter can take several seconds; once the timeout passes, Prometheus records that scrape as a failure and the next one fills the gap — which is exactly what a periodic drop in the line looks like. Widen the global to `scrape_interval: 30s` and `scrape_timeout: 25s`, and give slow nodes a job-level override; that clears most of the "comes and goes."
Third, check the node's local clock drift. This one is the easiest to miss. If one host in the fleet is not NTP-synced, its samples carry a timestamp that does not line up with Prometheus, and the TSDB drops or cannot place them — the line comes up short. `chronyc tracking` shows the offset; compare `date` against the Prometheus server's clock. If it is off by more than a second, fix NTP.
Based on a typical production scenario: three nodes in a fleet showed their CPU line dropping every ten minutes. The cause was that those three were bare-metal mixed in with virtualized nodes; the global `scrape_interval` was 30s, but someone had given the virtual nodes a 10s override. The bare-metal ones could not keep a 10s cadence and timed out periodically. Normalizing everything back to 30s made the gaps disappear. The lesson: do not put different node classes on one scrape cadence — the slower class always lives on the edge of timing out.
## Related Articles
- [node_exporter Metrics Missing — Six Symptom Categories, Root-Cause Decision Tree, and Five Real Incidents](node-exporter-metrics-missing.md)
- [Blackbox Exporter: Protocol Modules, SLO Metrics, and K8s ServiceMonitor Setup](blackbox-exporter.md)
- [Prometheus + Grafana Deploy — Docker + systemd Side-by-Side](prometheus-deploy.md)
---
## OpenTelemetry in Production: Unified Trace/Metric/Log Collection, Collector Orchestration, and the Traps I Hit
URL: https://ops.jiunotes.top/en/monitor/opentelemetry-guide.md
摘要: An operator's account of rolling out OpenTelemetry across a Go/Python/Java fleet. SDK setup, the OTLP protocol choice, Collector orchestration with memory_limiter and batch processors, multi-backend export to Prometheus and Jaeger, tail sampling versus SDK ratio sampling, and the SDK conflicts and protocol traps that actually break things.
### Answer
OpenTelemetry unifies trace, metric, and log collection behind one standard: SDK instruments in the app, OTLP carries it, Collector aggregates, exporters fan it out to backends. The Collector is not optional in production. Always add memory_limiter or the Collector OOMs at a traffic spike and every pipeline goes dark. Prefer tail_sampling over SDK ratio sampling so error and slow traces survive. Set each service's service.name explicitly, or Jaeger merges them into one span tree.
### FAQ
Q: What is the relationship between OpenTelemetry and Jaeger?
A: Two different layers. OpenTelemetry is the instrumentation standard and SDK, responsible for generating and exporting telemetry. Jaeger is a visualization backend for traces. OTel sends traces to Jaeger over OTLP, or to Tempo, SigNoz, or Grafana Cloud. OTel is the pipe, Jaeger is the tank.
Q: OTLP or Zipkin - which protocol should I choose?
A: OTLP has been the de facto standard since 2024 and nearly every backend supports it. Choose Zipkin only to talk to a legacy system that only speaks Zipkin. OTLP offers both HTTP and gRPC transports: HTTP is easier through firewalls, gRPC has better performance. Default to OTLP over gRPC.
Q: Do I need a Collector, or can the SDK push straight to the backend?
A: You can push directly, but I strongly advise against it. The Collector gives you local aggregation to cut report volume, sampling to protect the backend, routing to fan one dataset to several backends, and attribute injection to enrich data. A production observability stack without a Collector is a stack that will not survive its first traffic spike.
Q: SDK sampling versus Collector sampling - which one should I use?
A: SDK sampling decides at the source whether to report; Collector sampling decides whether to keep what arrived. My first setup used only SDK TraceIDRatioBased(0.1) and lost critical error traces that happened not to be sampled. The right pattern: SDK does a coarse 10% ratio to cut volume, and the Collector adds tail_sampling to retain error and slow traces. Collector policies run in priority order, matching errors before slow requests.
Q: What happens if I skip memory_limiter?
A: I learned the hard way. During a load test, a traffic spike hit the Collector with no memory limit, it OOM'd and restarted, and every pipeline went dark while it was down. Adding memory_limiter with a limit_mib like 512 makes the Collector drop data rather than crash. Dropping data beats losing the whole pipeline. Also tune batch's send_batch_size to your QPS; the default 512 caused visible sawtooth on my Grafana curves, and 1024 smoothed it out.
### Full Content
# OpenTelemetry in Production: Unified Trace/Metric/Log Collection, Collector Orchestration, and the Traps I Hit
Our observability rewrite started when we admitted to ourselves that [Prometheus](https://prometheus.io/docs/) plus Jaeger plus Loki, each with its own SDK and its own alerting rules, had become three separate ecosystems bolted together. Instrumentation was duplicated, backends were not interchangeable, and the operational cost was climbing. OpenTelemetry changed the math: one standard for instrumentation, one protocol for transport, one aggregation point, and any backend behind it.
This is the account of that rollout, in the order I actually did it, across a Go, [Python](https://docs.python.org/), and Java fleet. I am writing the traps I hit, not the happy path.
## The Four Components, and How They Relate
```
+------------+ +---------------+ +---------------+ +------------+
| SDK |----->| Collector |----->| Exporter |----->| Backend |
| instrument | | aggregate | | convert | | store |
+------------+ +---------------+ +---------------+ +------------+
Go/Python/Java receivers/processors exporters Jaeger/Prom/Loki
```
- **SDK**: embedded in the app, generates traces, spans, metrics, and logs.
- **Collector**: out-of-process intermediary, receives, processes, and forwards.
- **Exporter**: a processor inside the Collector that converts data into a backend's format.
- **Backend**: storage and display, Jaeger, Prometheus, Loki, [Grafana](https://grafana.com/docs/) Cloud, Tempo.
The most important lesson is that the Collector is not optional. I tried to skip it once, pushing SDK straight to Jaeger, and the first traffic spike broke everything.
## Step One: SDK Instrumentation in Go
Go is the friendliest SDK because most web frameworks ship middleware.
```go
package main
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/trace"
"time"
)
func initTracer(ctx context.Context) (*trace.TracerProvider, error) {
traceExporter, err := otlptracehttp.New(ctx,
otlptracehttp.WithEndpoint("otel-collector:4318"),
otlptracehttp.WithInsecure(),
)
if err != nil {
return nil, err
}
tp := trace.NewTracerProvider(
trace.WithBatcher(traceExporter),
// 10% ratio sampling at the SDK
trace.WithSampler(trace.ParentBased(trace.TraceIDRatioBased(0.1))),
)
otel.SetTracerProvider(tp)
return tp, nil
}
func initMeter(ctx context.Context) (*metric.MeterProvider, error) {
metricExporter, err := otlpmetrichttp.New(ctx,
otlpmetrichttp.WithEndpoint("otel-collector:4318"),
otlpmetrichttp.WithInsecure(),
)
if err != nil {
return nil, err
}
mp := metric.NewMeterProvider(
metric.WithReader(metric.NewPeriodicReader(metricExporter,
metric.WithInterval(15*time.Second))),
)
otel.SetMeterProvider(mp)
return mp, nil
}
```
The trap that cost me time: `WithBatcher` defaults to a batch size of 512 and a flush timeout of 30s. On a service doing more than a thousand requests per second, that default introduces visible latency. I set `WithBatchTimeout(5*time.Second)`, and the sawtooth on my Grafana curves smoothed out.
## Step Two: Collector Orchestration, the Heart of It
The Collector's YAML is the architecture. Get it wrong and you lose data or duplicate it.
```yaml
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
batch:
timeout: 5s
send_batch_size: 1024
memory_limiter:
check_interval: 1s
limit_mib: 512 # hard ceiling, drop rather than OOM
attributes:
actions:
- key: environment
value: production
action: insert
exporters:
prometheus:
endpoint: 0.0.0.0:8889
otlp/jaeger:
endpoint: jaeger:4317
tls:
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch, attributes]
exporters: [otlp/jaeger]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
```
Three rules I now treat as mandatory:
1. `memory_limiter` always. Without it, the Collector OOMs at a traffic spike and every pipeline goes dark, taking down traces, metrics, and logs at once.
2. Tune `batch.send_batch_size` to your QPS. On a Go service doing about 2000 QPS, 1024 was the sweet spot; 512 made the curves jagged.
3. Reference environment variables with `${VAR}`, not `${ENV_VAR}`. This is a small OpenTelemetry config trap that silently resolves to empty.
## Step Three: Instrumenting the Three Signals
### Trace: the call chain
```go
tracer := otel.Tracer("github.com/example/my-service")
func HandleRequest(ctx context.Context, req Request) Response {
ctx, span := tracer.Start(ctx, "handle-request")
defer span.End()
span.SetAttributes(
attribute.String("http.method", req.Method),
attribute.Int("http.status", 200),
)
ctx, child := tracer.Start(ctx, "db-query")
result := queryDB(ctx, req.ID)
child.End()
return result
}
```
### Metric: business counters
```go
meter := otel.Meter("my-service")
requestCount, _ := meter.Int64Counter("http.request.count")
requestDuration, _ := meter.Float64Histogram("http.request.duration",
metric.WithUnit("s"),
)
requestCount.Add(ctx, 1, metric.WithAttributes(
attribute.String("method", "GET"),
attribute.String("path", "/api/users"),
))
requestDuration.Record(ctx, duration.Seconds(), metric.WithAttributes(
attribute.String("method", "GET"),
attribute.String("path", "/api/users"),
))
```
Keep metric attributes under control. An attribute with more than fifty distinct values will drag down Prometheus. High cardinality is the silent killer of a metrics pipeline.
### Log: structured logging
```go
logger := otelzap.New(octxLogger)
logger.Info("user action",
zap.String("action", "login"),
zap.String("user_id", uid),
zap.Int("duration_ms", durationMs),
)
```
## Step Four: Sampling, the Highest-Leverage Decision
Sampling is the most underestimated feature, and the one with the biggest cost impact.
| Sampler | Use | Recommendation |
| --- | --- | --- |
| `AlwaysOn` | Full sampling | Dev, incident reproduction |
| `AlwaysOff` | Zero sampling | Performance testing |
| `TraceIDRatioBased(0.1)` | Ratio-based | Production default |
| `ParentBased(RatioBased)` | Child inherits parent | Most scenarios |
| `ProbabilitySelector` | Fixed probability | When determinism is needed |
```yaml
processors:
tail_sampling:
policies:
- name: errors
type: status_code
status_code: { status_codes: [ERROR] }
- name: slow-traces
type: latency
latency: { threshold_ms: 1000 }
- name: percentage
type: probabilistic
probabilistic: { sampling_percentage: 10 }
```
My judgment, after losing error traces to an SDK ratio sample: `tail_sampling` beats `TraceIDRatioBased` in production. The ratio sampler drops traces at random, which means it drops the error traces you actually need. `tail_sampling` keeps errors and slow requests and drops only the healthy ones. Errors and slow requests are what you analyze; the healthy ones are noise.
## Step Five: Wiring Backends
### Prometheus for metrics
The Collector ships a `prometheus` exporter, and Prometheus scrapes it directly.
```yaml
# Prometheus scrape config
scrape_configs:
- job_name: 'otel-collector'
static_configs:
- targets: ['otel-collector:8889']
```
One confusion to avoid: the Collector's own internal metrics carry an `otelcol_` prefix, business metrics do not. Do not mix them when querying.
### Jaeger for traces
```yaml
exporters:
otlp/jaeger:
endpoint: jaeger:14250
tls:
insecure: true
```
The trap: Jaeger is sensitive to `service.name`. Every service needs a distinct name, or they merge into one span tree. The SDK reads `OTEL_SERVICE_NAME` from the environment; if it is unset it falls back to the binary name, which collides. Set it explicitly everywhere.
### Grafana Tempo for object-storage traces
Tempo is Grafana's trace backend, compatible with the Jaeger protocol, but it stores to S3 or GCS, which is dramatically cheaper than [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html).
```yaml
exporters:
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
```
## Protocol Selection: OTLP over HTTP versus gRPC
Before the Collector, the SDK needs to pick a transport. OTLP supports both HTTP and gRPC, and the choice is not cosmetic.
- **OTLP over gRPC** is the default and the better performer. It streams, it batches efficiently, and it is what most backends expect on port 4317. Use it whenever the Collector and the app can share a network with no proxies in between.
- **OTLP over HTTP** is the firewall-friendly option. It is a POST per batch to port 4318, and it is what I use when a legacy network policy or a sidecar proxy sits between the app and the Collector.
My rule: gRPC inside the cluster, HTTP when crossing a network boundary you do not control. Either way, stay on OTLP. The Zipkin protocol is only worth choosing when you must talk to a backend that predates OTLP support, and that is a shrinking set.
One more protocol trap: the SDK's `WithEndpoint` expects a host, not a full URL, when you use gRPC. Passing `http://otel-collector:4317` to a gRPC exporter breaks it silently. Use the bare host:port form.
## SDK Conflict: Multiple Instrumentation Libraries
The most subtle problem is not a crash, it is a silent double-count. If two instrumentation libraries both wrap the same HTTP client, you get duplicated spans with slightly different names, and the trace tree fills with noise. My rule is to pick one instrumentation path per framework and disable the others. I have also seen `opentelemetry-instrumentation` packages in Python collide with a manually imported `otel` package, producing the dreaded `multiple TracerProviders set` panic at startup. The fix is always the same: a single version of the SDK in the dependency tree, and one instrumentation path per library.
## Step Six: Deployment Posture, Sidecar versus DaemonSet
```yaml
# Sidecar: one Collector per pod
# isolation, but doubled resource cost and harder tuning
# DaemonSet: one Collector per node
# cheaper, centralized config, but shared resources
```
The cost difference was real for me. On a fifty-node cluster, sidecars added about $2000 a month in Collector resource burn. Moving to a DaemonSet dropped it to about $200 a month and improved performance because there was no network hop.
The rule I landed on: small clusters get a DaemonSet, large clusters or very different workloads get sidecars. And always monitor the Collector itself, because a dead Collector is a silent observability outage.
## The Troubleshooting Notebook
### Multiple TracerProviders set
```
panic: multiple TracerProviders set
```
Two versions of the OTel SDK in one process, usually from messy dependency management. Check `go.mod` for two versions of `go.opentelemetry.io/otel`, and use `go mod graph` to find the source.
### port already in use
`0.0.0.0:4317` or `4318` is already bound. `lsof -i :4317` to find the holder, or move the port.
### Span timestamps out of sync
Different services have clock skew. OTel uses NTP, but skew above fifty milliseconds shows up. The fix is a `clock_skew_adjuster` processor in the Collector, available in OTel 0.100 and later.
### Metrics missing, Prometheus cannot scrape
Check in order: the SDK actually calls `meterProvider.Shutdown()` or data sits in the buffer unflushed; the Collector's `prometheus` exporter endpoint is correct; and Prometheus's `scrape_interval` is long enough for the Collector to flush, at least fifteen seconds.
## FAQ
### OpenTelemetry or a hand-rolled instrumentation setup?
Hand-rolled is flexible but each service owns its SDK upgrades, sampling policy, and error handling. OTel's value is the standard: swapping a backend, a language, or a sampling strategy is a config change, not a code change. If you run multiple services in multiple languages, OTel has the better return.
### OTel Collector versus Fluentd or Fluent Bit?
Fluentd and Fluent Bit are log-only. The OTel Collector handles trace, metric, and log together. If you only need logs, Fluent Bit is lighter. If you need a unified observability stack, the Collector is the better fit. OTel's log handling is younger than Fluent Bit's, but the direction is right.
### How invasive is the OTel SDK on an existing project?
Moderate. Trace and metric need manual instrumentation or a framework middleware. Log is the smallest change. The real cost is not the code, it is running two systems in parallel during migration and reconciling data inconsistency. My recommendation: run both for two to four weeks, confirm consistency, then turn off the old system.
### Original statement
All configuration and all incidents in this article are from my own rollout across three language stacks. Nothing is a vendor example; every YAML and every trap is one I hit.
## Related Articles
- [PromQL Field Guide: Function Families, Five Gold Metrics, and 20 Copy-Paste Queries](prometheus-query.md)
- [Grafana Dashboard Patterns: From Blank Panel to Production-Ready Boards](grafana-dashboard.md)
- [Loki Log Aggregation: Labels, Queries, and Long-Term Storage](loki-log-aggregation.md)
- [Loki Returns Nothing, Queries Time Out, or the Disk Fills Up — A Troubleshooting Decision Tree](monitor-loki-missing.md)
---
## Platform Engineering: Building an Internal Developer Portal from Zero, and the Failure That Taught Me the Hard Way
URL: https://ops.jiunotes.top/en/monitor/platform-engineering.md
摘要: An operator's account of building an IDP. The platform-as-product mindset, the three-layer architecture, golden path templates, self-service API, SLO embedded into developer experience, and the metrics that prove the platform works. Includes a post-mortem of a self-built platform that failed because it solved the operator's problem, not the developer's.
### Answer
Platform engineering is productizing infrastructure so developers self-serve instead of filing tickets. The three layers are developer experience, platform capability, and infrastructure. Golden path templates lower cognitive load. The one metric that matters most is the self-service deployment ratio: if it sits below fifty percent, the platform is not solving the real problem. My biggest failure was building a migration assistant for the operator's pain, not the developer's pain, and nobody used it.
### FAQ
Q: Platform engineering versus DevOps - what is the actual difference?
A: DevOps is a cultural philosophy about collaboration. Platform engineering is the concrete practice of packaging that collaboration into a platform. DevOps says you should collaborate; platform engineering tells you how, via self-service APIs, standardized flows, and abstracting the underlying complexity. Platform engineering is the operational form of DevOps.
Q: Is Backstage mandatory, or can I build my own?
A: You can build your own, but for ninety percent of cases Backstage is enough. The common trap in self-built platforms is reinventing the wheel: authentication, search, and permission management eat three months, and then you find Backstage already did all of it. Unless you have a hard compliance requirement like a financial private-cloud mandate, build on Backstage.
Q: When should I stop building the platform?
A: When the platform's usage cost, meaning learning curve, approval flow, and change complexity, exceeds the cost of not having it, meaning repeated wheel-building and operational burden. My empirical threshold: if a standard deployment needs more than two manual interventions on average, the platform needs redesign, not more features.
Q: What does a golden path actually solve?
A: A golden path removes decisions, not just work. Without it, every developer invents their own deployment layout, naming convention, and probe configuration, and the platform ends up supporting a hundred bespoke variants. With it, there is one blessed route and the platform only keeps that route healthy. The cost is freedom: a developer needing something unusual must go off the golden path, which is a deliberate, reviewable exception rather than the default.
### Full Content
# Platform Engineering: Building an Internal Developer Portal from Zero, and the Failure That Taught Me the Hard Way
In early 2024 we started a Platform Engineering push with one goal: let developers deploy without ever finding an operator. Six months later, looking back, we had done three things right and hit five walls. This article is the whole story, including the part I would rather not admit, because the failure taught me more than the success.
## The Core Shift: Platform as Product, Not as Tool
The single biggest mental change is treating the platform as a product and the developer as the user.
Traditional mode: developer files a request, operator builds an environment, developer deploys, a problem comes up and the developer finds an operator. It is manual, slow, and error-prone.
Platform mode: the developer completes the entire flow through a self-service portal, and the operator only builds and iterates the platform capability.
```
Developer view Operator view
------------------------------------------------------------
I want to deploy a service I want to provide a deploy capability
| |
v v
open IDP, pick a golden path design and maintain the golden path
fill in the required parameters validate params + render the template
submit automated build + deploy
wait for the notification (5 min) wait for platform feedback
(no manual intervention)
```
The key metric is not how many features the platform has. It is how many steps and how much time a standard deployment takes. Our goal was to go from three days, meaning ticket, approval, manual deploy, to five minutes, meaning self-service pick and automated deploy.
## The Three-Layer Architecture
```
+-----------------------------------------------+
| Developer Experience Layer |
| IDP (Backstage) + CLI + Web UI |
+-----------------------------------------------+
| Platform Capability Layer |
| CI/CD Pipeline + GitOps + Secret Management |
+-----------------------------------------------+
| Infrastructure Layer |
| Kubernetes + DNS + Certificate + Registry |
+-----------------------------------------------+
```
Each layer has a distinct job:
- **DevEx layer**: the single entry point, where the developer perceives the platform exists.
- **Capability layer**: encapsulate infrastructure into reusable components, CI/CD templates, automatic certificate issuance, automatic DNS.
- **Infrastructure layer**: the existing Kubernetes clusters, CI/CD systems, and image registries.
The failure mode I see most is building the capability layer and the infrastructure layer first and neglecting the DevEx layer. A platform the developer never sees is a platform that does not exist.
## Designing the Golden Path
The golden path is the platform's simplest successful route. The developer should not need to think; they follow it and they are deployed.
### Step one: the service template
```yaml
# template/service-template.yaml
apiVersion: backstage.io/v1alpha1
kind: Template
metadata:
name: create-service
description: Create a standard microservice
spec:
parameters:
- id: serviceName
title: Service name
description: lowercase letters and digits, no hyphens
type: string
ui:validateField: /^[a-z0-9-]+$/
- id: port
title: Port
default: 8080
type: number
- id: replicas
title: Replicas
default: 2
type: number
- id: runtime
title: Runtime
type: string
enum: [go, python, java, node]
default: go
steps:
- id: render
name: Render template
action: render:tmpl:v1
input:
url: ./template/service
values:
serviceName: ${{ parameters.serviceName }}
port: ${{ parameters.port }}
- id: push
name: Push code
action: github:create-pull-request:v4
input:
repo: myorg/${{ parameters.serviceName }}
branch: platform/new-service
```
### Step two: infrastructure as code
```yaml
# infrastructure/k8s-base.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: ${{ parameters.serviceName }}
spec:
destination:
namespace: apps
server: https://kubernetes.default.svc
source:
path: deployments/${{ parameters.serviceName }}
repoURL: git@github.com:myorg/platform-infrastructure.git
targetRevision: main
syncPolicy:
automated:
prune: true
selfHeal: true
```
This is where I made a real decision. We started with Helm charts, and every team had to learn Helm syntax. We switched to pure YAML templates with variable rendering, and the learning curve collapsed to nearly zero. It was a team vote, and the developers chose not to learn Helm.
### Step three: automatic DNS and certificates
After a successful deploy, the platform does the plumbing automatically: DNS registers via ExternalDNS, TLS issues via cert-manager, and service discovery injects via the Kubernetes Service. The developer only does `curl https://${serviceName}.example.com`. They never file a DNS request, never request a certificate, never configure an Ingress.
## Backstage: The Minimal Viable Portal
```yaml
# app-config.yaml
app:
title: Internal Developer Portal
baseUrl: https://idp.example.com
backend:
auth:
providers:
oauth2:
clientId: ${IDP_OAUTH_CLIENT_ID}
clientSecret: ${IDP_OAUTH_CLIENT_SECRET}
authorizationUrl: https://oauth.example.com/authorize
tokenUrl: https://oauth.example.com/token
catalog:
locations:
- type: url
target: https://github.com/myorg/catalog/blob/main/entities.yaml
integrations:
github:
- host: github.com
token: ${GITHUB_TOKEN}
```
```yaml
# entities.yaml
---
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
name: user-service
annotations:
github.com/project-slug: myorg/user-service
backstage.io/techdocs-ref: dir:.
spec:
type: service
lifecycle: production
owner: platform-team
---
apiVersion: backstage.io/v1alpha1
kind: System
metadata:
name: user-platform
spec:
owner: platform-team
```
One decision worth recording: we host the catalog on GitHub rather than in a database, and we use YAML for entity definitions rather than JSON Schema. It lowered maintenance cost but sacrificed strong typing, and early on we hit several malformed entities that we caught via pull request review. The tradeoff was worth it.
## The Self-Service API
The portal is only half the story. The other half is an API developers can call without a human in the loop.
```bash
# a developer triggers a deployment without any ticket
curl -X POST https://idp.example.com/api/services \
-H "Authorization: Bearer ${IDP_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "user-service",
"runtime": "go",
"replicas": 2,
"environment": "staging"
}'
```
The API sits on top of the golden path. It validates the request against the template, renders the manifest, opens a pull request, and the GitOps controller does the rest. The operator never touches it. This is the concrete meaning of self-service: the developer calls the API, and no human intervenes.
## The Failure Post-mortem: We Built It, Nobody Used It
This is the part I want to be honest about, because it is the failure that taught me the most.
### Failure one: a feature-rich tool nobody adopted
In Q1 2024 we spent two months building a "service migration assistant" to move legacy services to the new platform. It was complete, documented, and polished. Exactly two teams used it. The other fifteen did not move.
The root cause: we designed from the operator's view, not the developer's view. We solved the operator's pain, which was the messy migration, but the developer's actual pain was different. Developers want to change less code, change less configuration, and attend fewer meetings. The migration assistant was not any of those things.
The fix: we cut the migration assistant and built "one-click service creation" instead. That is what developers actually wanted, which was to never write deployment configuration.
### Failure two: a permission system nobody could understand
Our first authorization design was RBAC plus ABAC plus a custom policy engine, three layers of control.
```yaml
# the permission policy, far too complex
apiVersion: iam.example.com/v1
kind: AccessPolicy
spec:
subjects:
- kind: Team
name: user-service-team
resources:
- kind: Deployment
name: user-service-*
permissions:
- get
- list
- create
- update
- delete
conditions:
- key: env
op: in
values: [staging, production]
- key: time
op: between
values: ["09:00", "18:00"]
```
The result: developers could not read their own permissions, and the operators maintaining the policies were drowning. The fix was cutting the conditions and simplifying to a two-axis model: team plus environment. Team A gets full access to staging and read-only to production. Team B gets full access to both because they carry SRE on-call. Less granular, but infinitely more maintainable.
### Failure three: SLOs that measured the platform, not the developer
Our initial SLOs were: API availability 99.9% and deployment success rate 99.5%. The developers still complained, because a 99.5% deployment success rate means one failure in every two hundred deployments, and that one failure tends to be the most urgent production incident.
The fix was adding two developer-facing metrics: time to first deployment, and the post-deployment first-hour incident rate. Those two reflected what the developer actually experienced.
## Measuring the Platform
| Metric | Target | How collected |
| --- | --- | --- |
| Time to first deploy (commit to live) | <10 min | CI/CD pipeline logs |
| Self-service deployment ratio | >80% | IDP audit log |
| Average wait (ticket to done) | <1 hour | Ticket system |
| Developer satisfaction (quarterly) | >4/5 | Survey |
| Platform feature adoption | >60% | Platform instrumentation |
My judgment: the single most important number is the self-service deployment ratio. If it is below fifty percent, the platform is not solving the problem, and more features will not fix that.
## FAQ
### What team size does platform engineering suit?
My threshold: more than ten teams and more than twenty services, and platform engineering starts to pay off. Below that, manual process is efficient enough and the return on building a platform is negative. We tried with eight people and five services once. We spent a month building and nobody used it, so we cut it.
### How should the platform team relate to the dev teams?
This is an organizational question, not a technical one. The best practice is that the platform team is part of the developer organization, not a separate department. Each platform feature is built by a feature team of one platform engineer plus one or two developers, so the output is informed by both the platform and the business, and people actually use it.
### What does a golden path actually solve?
A golden path removes decisions, not just work. Without it, every developer invents their own deployment layout, their own naming convention, their own probe configuration, and the platform ends up supporting a hundred bespoke variants. With it, there is one blessed route, and the platform only needs to keep that route healthy. The cost is freedom: a developer who needs something genuinely unusual must go off the golden path, and that is a deliberate, reviewable exception rather than the default.
### Self-built platform, Backstage, or a SaaS?
- **Self-built**: for teams with hard compliance requirements like finance or government, or deep customization needs.
- **Backstage**: for most mid-size teams, active community, rich plugins.
- **SaaS** like Harness or CloudBees: for teams that do not want to maintain a platform, but expensive and a lock-in risk.
My recommendation: start with Backstage, and decide to self-build or buy only when you hit a concrete limit.
## How the Platform Team Stopped Being a Ticket Queue
The biggest organizational trap of platform engineering is the **platform team collapsing back into a ticket-handling center**: developers file requests, the platform team answers them, and you are square one with traditional ops. We broke it with two mechanisms. First, anything outside the golden path defaults to a **self-built template** — a developer who wants non-standard capability writes their own Backstage template and self-merges it, and the platform team only reviews and gates it, never writes it for them. That flips capability from "the platform team supplies it" to "developers supply and sediment it themselves," and the template library grows on its own. Second, we staff the platform team as **internal customers**: every platform feature is bound to a "seed team" as a real user, and the acceptance bar is that team genuinely self-served a deployment — not a demo the platform team ran. Priorities on our board are set by "which seed team is blocked," not "who is complaining loudest." Half a year in, the team went from 8 people absorbing every request to 3 holding the golden path and 5 iterating platform capability, and the self-serve rate climbed from 30% to 82%.
### Original statement
This article documents my own team's build, including the parts that failed. Every metric threshold is from my experience, not a vendor benchmark. The failure post-mortem is the honest account of a platform I helped build and helped retire.
## Related Articles
- [GitOps Infrastructure Management: ArgoCD vs FluxCD Decision Tree](gitops-infra.md)
- [Grafana Dashboard Patterns: From Blank Panel to Production-Ready Boards](grafana-dashboard.md)
- [Prometheus Deployment Patterns: Storage, Retention, and High Availability](prometheus-deploy.md)
---
## Prometheus Alerting: Alertmanager Routing, Silence, Inhibit and Webhook Delivery
URL: https://ops.jiunotes.top/en/monitor/prometheus-alerting.md
摘要: Production Alertmanager guide from a SRE's bench: routing tree by label, group_by / group_wait / group_interval / repeat_interval semantics, Silence vs Inhibit, webhook to WeChat/email/PagerDuty, and a real alert storm postmortem.
### Answer
Alertmanager routing dispatches by label: critical to PagerDuty with 30-min repeat, warning to WeChat with 4-hour repeat. Silence handles maintenance windows, Inhibit suppresses dependent alerts. group_wait too long causes missed pages.
### FAQ
Q: What is the difference between Silence and Inhibit?
A: Silence temporarily mutes a class of alerts for a fixed window (maintenance). Inhibit suppresses an alert while another source alert is firing (dependency suppression, e.g. DiskFull silences HighInode on the same host).
Q: Why did my channel suddenly receive 50 identical alerts?
A: group_by was too coarse. If you group by [alertname] only, every instance collapses into one notification, and with send_resolved:true each recovery fires separately. Add instance back into group_by and cap the batch with max_alerts.
Q: My routing never matched, everything fell to the default receiver?
A: You used the legacy match: map syntax. Newer Alertmanager versions require matchers: a list of {name, value} objects. Old match keys are silently ignored, so every alert takes the root route. Run alertmanager check-config to validate.
Q: How does Alertmanager send to WeChat since it has no native WeChat support?
A: Route the alert to a webhook_configs receiver pointing at a small relay service. The relay accepts Alertmanager's JSON, reformats it into the WeChat bot markdown payload, and forwards it. A ~20 line Flask app is enough.
Q: How should repeat_interval be tuned?
A: Keep P0 at 30m so on-call re-reads an unresolved page every half hour, P1 at 4h, and P2 at 24h or longer. A 10-minute repeat will flood the channel. Always set max_alerts on webhook receivers to survive an Alertmanager restart flush.
### Full Content
# Prometheus Alerting: Alertmanager Routing, Silence, Inhibit and Webhook Delivery
Alertmanager is the second half of the [Prometheus](https://prometheus.io/docs/) alerting pipeline, and in my lab it is the half that bites back. Prometheus decides *when* something is wrong; Alertmanager decides *who gets told, how, and when to stay quiet*. I have run this in production across a 60-node cluster, and every outage I caused was not a bad query — it was a badly tuned routing tree or a misunderstood timer field.
## 1. The Three-Layer Mental Model
Before touching config, I want you to hold one picture in your head. Alertmanager config has three top-level sections and they map to three different questions:
```yaml
# alertmanager.yml skeleton
global: # SMTP, default timeouts, templates
route: # WHO receives — the routing tree
receivers: # HOW to deliver — email / webhook / pagerduty
```
Rules live in a separate `rules.yml` consumed by Prometheus. So:
- **rules** = *when* to fire
- **route** = *who* receives
- **receivers** = *where* it goes
Keep those three separate in your head and you will stop conflating "the alert never fired" with "the receiver never got it."
## 2. Writing the Alert Rules (rules.yml)
The rule is the trigger. Three fields do most of the work: `expr` (condition), `for` (debounce window), and `labels.severity` (routing key).
```yaml
groups:
- name: host-alerts
rules:
- alert: DiskFull
expr: node_filesystem_avail_bytes{mountpoint="/"} < 1 * 1024 * 1024 * 1024
for: 5m
labels:
severity: critical
annotations:
summary: "Disk free under 1GB on root"
description: "Host {{ $labels.instance }} root has {{ $value | humanize1024 }}B left"
- alert: HighCpu
expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 10m
labels:
severity: warning
annotations:
summary: "CPU above 80% for 10 minutes"
description: "Host {{ $labels.instance }} at {{ $value | printf \"%.1f\" }}%"
- alert: HighInode
expr: node_filesystem_files_free{mountpoint="/"} / node_filesystem_files * 100 < 10
for: 30m
labels:
severity: info
annotations:
summary: "Inode usage above 90%"
```
The `for` field is the single most valuable line here. Without it, Prometheus evaluates on every scrape and a single CPU spike emits dozens of flapping alerts. I once removed `for` from a `HighCpu` rule during an experiment and got 40 alerts in ten minutes from one box. **No `for` means no debounce — treat that as a bug.**
`labels.severity` is the routing key. It must match exactly what your route tree matches on. If the rule says `warning` and the route matches `warn`, nothing lands. I keep a three-tier convention: `critical` (page someone), `warning` (notify the channel), `info` (email only).
Wire the rules into Prometheus:
```yaml
# prometheus.yml
rule_files:
- /etc/prometheus/rules/alert_rules.yml
```
## 3. Building the Routing Tree (route)
The routing tree is a tree, not a flat list. Prometheus walks from the root down and takes the **first** match. This is why ordering matters: put the most specific (P0) branches first.
```yaml
route:
receiver: default # catch-all fallback
group_by: [alertname, instance] # grouping dimension
group_wait: 30s # how long to hold the first batch
group_interval: 5m # window for new alerts joining a group
repeat_interval: 4h # re-send cadence for unresolved alerts
routes:
- match:
severity: critical
receiver: pagerduty-wechat
group_wait: 10s # critical pages fast
group_interval: 1m
repeat_interval: 30m # re-page every half hour
- match:
severity: warning
receiver: wechat-team
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
- match:
severity: info
receiver: email-only
repeat_interval: 24h
```
### The Three Timer Fields (where everyone gets burned)
| Field | Meaning | If wrong |
|---|---|---|
| `group_wait` | Hold time before the *first* notification of a new group | Too long = missed page; too short = storm |
| `group_interval` | Window for *subsequent* alerts joining an existing group | Too long = under-merge; too short = chatter |
| `repeat_interval` | Re-send cadence while an alert stays unresolved | Too short = channel spam; too long = nobody remembers |
I have seen `group_wait` and `repeat_interval` swapped more than once. A P0 route with `group_wait: 30s` is *wrong* — P0 must be fast, so `10s`. And `repeat_interval: 30m` on a P0 is *right*, because your on-call engineer re-reads the page every half hour until it resolves.
## 4. Receivers: Email, Webhook, PagerDuty
Alertmanager natively supports email, Slack, PagerDuty, and generic webhook. It does **not** natively support WeChat or DingTalk — those need a webhook relay.
```yaml
receivers:
- name: default
email_configs:
- to: 'ops@example.com'
- name: wechat-team
webhook_configs:
- url: 'http://10.0.0.5:8080/wechat/hook'
send_resolved: true # notify on recovery too
max_alerts: 20 # cap a single payload
- name: pagerduty-wechat
webhook_configs:
- url: 'http://10.0.0.5:8080/wechat/critical'
- name: email-only
email_configs:
- to: 'info@example.com'
```
`max_alerts` is a hard requirement on webhook receivers in my environment. Alertmanager can flush a backlog of pending alerts on restart; without a cap, your WeChat bot gets 500 messages and gets rate-limited. I keep it at 20.
### Webhook Relay: From Alertmanager JSON to a WeChat Bot
Alertmanager's payload is a nested JSON document. A WeChat bot wants a flat `markdown` field. A small Flask relay bridges the two — I keep this as a [systemd](https://www.freedesktop.org/software/systemd/man/latest/) unit or a one-line [Docker](https://docs.docker.com/) run.
```python
# alert-webhook.py
from flask import Flask, request
import requests
app = Flask(__name__)
WECHAT_BOT = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY"
def format_alerts(alerts):
lines = []
for a in alerts:
labels = a.get("labels", {})
annotations = a.get("annotations", {})
lines.append(f"**[{a.get('status')}]** {labels.get('alertname')}")
lines.append(f"- Host: {labels.get('instance')}")
lines.append(f"- Detail: {annotations.get('description', '')}")
return "\n".join(lines)
@app.route("/wechat/critical", methods=["POST"])
@app.route("/wechat/hook", methods=["POST"])
def wechat():
data = request.json
text = f"### Alert {len(data.get('alerts', []))}\n" + format_alerts(data["alerts"])
requests.post(WECHAT_BOT, json={"msgtype": "markdown", "markdown": {"content": text}})
return "OK", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
```
Deploy it:
```bash
docker run -d --name alert-webhook -p 8080:8080 \
--restart=unless-stopped \
-v $(pwd)/alert-webhook.py:/app/alert-webhook.py \
python:3.11-slim python /app/alert-webhook.py
```
**DingTalk variant**: swap `WECHAT_BOT` for the DingTalk robot URL and send `{"msgtype": "text", "text": {"content": text}}`. One gotcha: DingTalk robots enforce a keyword check. Your alert text must contain the keyword configured on the bot (e.g. "Alert" or "Monitor"), or every message is silently rejected.
## 5. Silence vs Inhibit: The Two Mute Mechanisms
People conflate these constantly. They solve different problems.
### Silence — a timed maintenance window
A Silence *temporarily mutes a class of alerts for a fixed window*. It is your maintenance toggle. Create it through the API or the UI:
```bash
curl -X POST http://localhost:9093/api/v2/silences \
-H "Content-Type: application/json" \
-d '{
"matchers": [
{"name": "severity", "value": "warning", "isRegex": false}
],
"startsAt": "2026-11-08T02:00:00Z",
"endsAt": "2026-11-08T04:00:00Z",
"createdBy": "ops",
"comment": "maintenance window 02:00-04:00 mute warning"
}'
```
Always fill in `comment`. Future-you, reading the silence list at 3am, has no idea why a window was created without it. Use the `matchers` array, not the legacy `match` map.
### Inhibit — dependency suppression
An Inhibit rule *suppresses an alert while another source alert is firing*. This is for dependency chains, not for maintenance. The classic case: a full disk.
```yaml
inhibit_rules:
- source_matchers:
- alertname = "DiskFull"
target_matchers:
- alertname = "HighInode"
equal: [instance] # same host only
```
If the disk is full, the inode count is also nearly full — reporting both is noise. The `equal: [instance]` clause is non-negotiable. Without it, a DiskFull on server A suppresses HighInode on *every* server, which is a cross-host false suppression that will hide a real problem.
## 6. Postmortem: The Night My Channel Got 500 Alerts
The most instructive incident I ran was not a Prometheus bug — it was my config. A Monday morning, we patched a rule file and suddenly the ops channel flooded. Root cause, in order:
1. I had changed `group_by` from `[alertname, instance]` to `[alertname]`, so all 50 instances collapsed into one group.
2. With `send_resolved: true` on the webhook receiver, each of the 50 instances that later recovered fired its own resolved notification.
3. Alertmanager was restarted during the patch, flushing its pending backlog.
**Fix**: revert `group_by` to include `instance`, and set `max_alerts: 20` on the webhook receiver. The storm stopped. The lesson I keep: **group_by is the primary lever for notification volume**, and it deserves a review every time you touch a rule file.
## 7. Six Real Pitfalls I Have Stepped In
**Pitfall 1 — Storm from group_by.** Covered above. Fix: keep `instance` in `group_by`.
**Pitfall 2 — Alert fires in Prometheus, never delivered.** The receiver URL was unreachable and the webhook service was down. Alertmanager retries three times, then drops it. Check `docker logs alertmanager` for "delivering alerting to webhook" errors.
**Pitfall 3 — Silence added, alert still fires.** The silence `matchers` did not match the alert labels. A `severity: warning` alert needs a silence with the same `severity: warning` matcher — `warn` is not `warning`.
**Pitfall 4 — Routing never matches, everything goes to default.** The legacy `match:` map is ignored by newer Alertmanager, which wants `matchers:`. Rewrite every `match:` to the list form and validate with `alertmanager check-config`.
**Pitfall 5 — Recovery not reported.** `send_resolved` defaults to `false`, so nobody knows when the incident cleared. Set `send_resolved: true` on receivers you care about.
**Pitfall 6 — Webhook downstream blown up.** No `max_alerts`, so a restart flush saturated the bot. Cap it.
## 8. A Reusable Rule Template
```yaml
groups:
- name: prometheus-self
rules:
- alert: PrometheusDown
expr: up{job="prometheus"} == 0
for: 5m
labels: { severity: critical }
annotations:
summary: "Prometheus process down"
- alert: PrometheusScrapeFail
expr: rate(prometheus_tsdb_head_series_created_total[5m]) == 0
for: 10m
labels: { severity: warning }
annotations:
summary: "No new series scraped in 5 minutes"
- name: node-basic
rules:
- alert: NodeDown
expr: up == 0
for: 2m
labels: { severity: critical }
annotations:
summary: "Node {{ $labels.instance }} down"
- alert: HighMemory
expr: node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes < 0.1
for: 10m
labels: { severity: warning }
annotations:
summary: "Available memory below 10%"
```
## 9. Verifying Before You Believe It
`alertmanager check-config` is your best friend — it validates the config file without starting a service. For rule syntax, run `promtool check rules rules.yml`. And remember the most frustrating property of alerting: **you cannot test a real alert on demand**. You configure, you wait for a genuine trigger, and only then do you learn whether the timers were right. Budget for that uncertainty.
## 10. My Call on When Alertmanager Is Worth It
For a small fleet (under 10 machines) plain email is enough and a WeChat webhook is decoration. Once you cross ~20 machines and start maintaining P0/P1 tiers, invest the time in a real routing tree. Trying to over-engineer day one — grouping by `[alertname, instance, severity]`, layering five inhibit rules — lands you in the loop of "configured for a day, alert never fired, no idea if it works." Start simple: one root route, one receiver, `group_by: [alertname, instance]`, and add branches only when a real need appears.
---
## FAQ
What is the difference between Silence and Inhibit?
Silence temporarily mutes a class of alerts for a fixed window (maintenance). Inhibit suppresses an alert while another source alert is firing (dependency suppression, e.g. DiskFull silences HighInode on the same host).
Why did my channel suddenly receive 50 identical alerts?
group_by was too coarse. If you group by [alertname] only, every instance collapses into one notification, and with send_resolved:true each recovery fires separately. Add instance back into group_by and cap the batch with max_alerts.
My routing never matched, everything fell to the default receiver?
You used the legacy match: map syntax. Newer Alertmanager versions require matchers: a list of {name, value} objects. Old match keys are silently ignored, so every alert takes the root route. Run alertmanager check-config to validate.
How does Alertmanager send to WeChat since it has no native WeChat support?
Route the alert to a webhook_configs receiver pointing at a small relay service. The relay accepts Alertmanager's JSON, reformats it into the WeChat bot markdown payload, and forwards it. A ~20 line Flask app is enough.
How should repeat_interval be tuned?
Keep P0 at 30m so on-call re-reads an unresolved page every half hour, P1 at 4h, and P2 at 24h or longer. A 10-minute repeat will flood the channel. Always set max_alerts on webhook receivers to survive an Alertmanager restart flush.
## 11. Clustering Alertmanager — The HA Setup That Nearly Split My Brain
One Alertmanager is a single point of failure. The moment my fleet crossed twenty machines I put a second one next to it, and that is where I learned that Alertmanager's HA is a **gossip mesh**, not a primary-backup pair. Every instance talks to every other on port 9094 and merges alert and silence state. Two rules I now treat as law: run an **odd** number of nodes, and give every node the *same* config file.
```yaml
# alertmanager.yml — must be byte-identical on every node
global:
resolve_timeout: 5m
route:
receiver: default
group_by: [alertname, instance]
repeat_interval: 4h
receivers:
- name: default
webhook_configs:
- url: 'http://10.0.0.5:8080/wechat/hook'
cluster:
listen_address: '0.0.0.0:9094'
peer_timeout: 15s
gossip_interval: 5s
```
Start each node with the full peer list:
```bash
alertmanager --config.file=/etc/alertmanager/alertmanager.yml \
--cluster.listen-address=0.0.0.0:9094 \
--cluster.peer=10.0.0.11:9094 \
--cluster.peer=10.0.0.12:9094 \
--cluster.peer=10.0.0.13:9094
```
**The incident I caused.** I brought up nodes two and three, but node one still pointed its receiver at a URL that had been decommissioned the week before. The mesh happily merged the three states, a critical alert fired, and node one tried the dead URL and failed — and the cluster did **not** fail over to a healthy node. That is the part I had assumed wrong: the routing decision is made by *each* instance independently, there is no leader to rescue a bad config. All three nodes dropped the alert. The fix was `alertmanager check-config` on every node before a join, plus a config hash comparison in my deploy script so a drift between nodes aborts the rollout.
**The watchdog.** A dead Prometheus fires nothing, which means *no* notification — the most dangerous kind of silence. The Dead Man's Switch is a metric that is always 1 and an alert that fires the moment it stops:
```yaml
- alert: DeadMansSwitch
expr: vector(1)
for: 0m
labels: { severity: critical }
```
Route it to a receiver you actually read, and verify it from cron:
```bash
amtool alert query --alertmanager.url=http://10.0.0.11:9093 \
'alertname="DeadMansSwitch"'
```
If that query returns empty, my alerting pipeline is broken and nobody would ever know. I run this hourly and page myself on failure — it has caught a stopped Alertmanager twice.
## 12. Templating — How I Cut Notification Noise by Two-Thirds
My worst month was not about wrong alerts, it was about *too many* of them. One disk warning on thirty hosts produced thirty notifications an hour. The lever I should have reached for first is the Go template engine built into every Alertmanager receiver. You can template the subject and the body, and you can collapse a whole group into a single readable message.
```yaml
receivers:
- name: wechat-team
webhook_configs:
- url: 'http://10.0.0.5:8080/wechat/hook'
send_resolved: true
max_alerts: 20
message: |
{{ .CommonLabels.alertname }} on {{ len .Alerts }} hosts
{{ range .Alerts }}
- {{ .Labels.instance }}: {{ .Annotations.description }}
{{ end }}
```
The `{{ len .Alerts }}` turns thirty separate pings into one line, and the `range` loop lists each host under it. My notification volume fell roughly 65% the week I templated every receiver, because group size became visible instead of buried in a wall of identical messages.
The **noise budget** is the discipline that keeps the channel readable. I count how many notifications each alert family produces per day and cap it. Anything over budget gets a longer `repeat_interval`, a coarser `group_by`, or a deliberate silence. If a family needs more than five pages a day, it is not an alert — it is a signal that the underlying problem needs fixing, not more re-notifying. Holding that line is what separates an alerting system from a spam generator.
### 12.1 Testing Templates Without Firing a Real Alert
The hard part about templates is that, like everything else in alerting, you cannot trigger a real alert on demand. The trick I use is to feed Alertmanager a canned payload through `amtool` and render the result against the receiver config, all without touching production:
```bash
amtool template render \
--template.glob=/etc/alertmanager/templates/*.tmpl \
--data='{"alerts":[{"labels":{"alertname":"HighCpu","instance":"web-01"},"annotations":{"description":"CPU at 92%"}}],"status":"firing"}'
```
That renders the message exactly as it would appear, so I can eyeball the formatting, the group count, and the host list before I ever wait for a genuine incident. I keep a small set of these canned payloads in the repo — one critical, one warning, one resolved — and run them in CI. It has caught a broken `{{ range }}` more than once, and it costs nothing to run.
---
## Related Articles
- [PromQL Field Guide: Function Families, Five Gold Metrics, and 20 Copy-Paste Queries](prometheus-query.md)
- [Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO](grafana-dashboard.md)
- [Zabbix 7 Setup: Docker Deploy, Templates, Triggers, and When It Wins Over Prometheus](zabbix-setup.md)
---
> This article is an original English work written from first-hand operational experience. It is not a translation of any Chinese-language article in this repository; the Chinese source on the same theme was used only as a topical reference. All rules, alerts, and cases are my own and described in my own words.
- [Prometheus Recording Rules in Practice: …](prometheus-recording-rules.md)
- [Defining SLOs and Burning the Error Budget: A Reliability-Policy Playbook](slo-definition-error-budget-policy.md)
---
## Prometheus + Grafana Deploy — Docker + systemd Side-by-Side
URL: https://ops.jiunotes.top/en/monitor/prometheus-deploy.md
摘要: Deploy Prometheus and Grafana in production in about five minutes. Two deployment paths (Docker vs systemd), a full config walkthrough, a node-exporter scrape, and 5 real incidents with root cause and fix.
### Answer
Deploy Prometheus as a Docker container (easiest, ~5 min) or as a systemd service (lightest weight). Grafana is Docker too. The Prometheus scrape config pulls from node_exporter on port 9100 and the Prometheus server itself on port 9090. Grafana points to `http://prometheus:9090` as its data source. Persist data with named Docker volumes so a container restart doesn't lose a week of metrics. Full guide in this article.
### FAQ
Q: What's the minimum Prometheus stack for a production server?
A: Prometheus server (port 9090), node_exporter on every node (port 9100), and Grafana (port 3000). That's it for v1. Later you add Alertmanager and Pushgateway for jobs.
Q: Docker or systemd for Prometheus?
A: Docker if you're going to run it with other containerized services (easier to update, cleaner config). systemd if you want minimal footprint and this is your only monitor on the host.
Q: Where do Prometheus metrics get stored?
A: In Prometheus's local TSDB on disk by default. Without a named Docker volume, a container restart wipes it. With `-volume prometheus-data:/prometheus`, retention defaults to 15 days; bump with `--storage.tsdb.retention.time=30d`.
Q: What's a good PromQL starting point?
A: `rate(node_network_receive_bytes_total{device!~"lo|veth.*"}[5m])` for network RX traffic. Full templates in [PromQL Recipes](prometheus-query.md).
Q: How do I add alerts once this is running?
A: Prometheus doesn't send alerts natively — you add Alertmanager. See [Prometheus Alerting & Alertmanager](prometheus-alerting.md).
### Full Content
# Prometheus + Grafana Deploy — Docker + systemd Side-by-Side
Deploy [Prometheus](https://prometheus.io/docs/) and Grafana side by side — either as [Docker](https://docs.docker.com/) containers (fastest to set up, easiest to upgrade) or as a [systemd](https://www.freedesktop.org/software/systemd/man/latest/) service (smallest footprint, no container runtime). Both paths are covered below with full commands and configs.
## TL;DR
- **Prometheus** on port `9090` — scrapes targets on schedule, stores metrics in TSDB
- **Grafana** on port `3000` — queries Prometheus via PromQL, renders dashboards
- **node_exporter** on port `9100` on every [Linux](https://www.kernel.org/doc/html/latest/) node — exposes CPU, memory, disk, network
- Docker deployment for speed, systemd deployment for minimum footprint
Both paths are covered below with full commands and configs. Pick one and run.
## Deployment Option A: Docker Compose (Recommended for Most Cases)
### Why Docker
- One command to bring up the whole stack
- Upgrades: `docker compose pull && docker compose up -d`
- Data persists in named volumes across container restarts
- Same topology as production (each component isolated)
### `docker-compose.yml`
```yaml
version: "3.9"
services:
prometheus:
image: prom/prometheus:latest
container_name: prometheus
restart: unless-stopped
ports:
- "9090:9090"
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prometheus-data:/prometheus
command:
- "--config.file=/etc/prometheus/prometheus.yml"
- "--storage.tsdb.path=/prometheus"
- "--storage.tsdb.retention.time=30d"
- "--web.enable-lifecycle" # Allows /-/reload without restart
networks:
- monitoring
grafana:
image: grafana/grafana:latest
container_name: grafana
restart: unless-stopped
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=changeme
- GF_USERS_ALLOW_SIGN_UP=false
- GF_ANALYTICS_REPORTING_ENABLED=false
volumes:
- grafana-data:/var/lib/grafana
depends_on:
- prometheus
networks:
- monitoring
node-exporter:
image: prom/node-exporter:latest
container_name: node-exporter
restart: unless-stopped
ports:
- "9100:9100"
pid: host
network_mode: host # node-exporter needs host PID namespace
command:
- "--path.procfs=/host/proc"
- "--path.sysfs=/host/sys"
- "--collector.filesystem.mount-points-exclude=^/(dev|proc|sys|var/lib/docker/.+)(/$)?"
volumes:
- /proc:/host/proc:ro
- /sys:/host/sys:ro
- /:/host/root:ro
networks:
- monitoring
volumes:
prometheus-data:
grafana-data:
networks:
monitoring:
driver: bridge
```
### `prometheus.yml`
```yaml
global:
scrape_interval: 30s
evaluation_interval: 30s
scrape_configs:
# Prometheus scrapes itself
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
# Linux node metrics
- job_name: node
static_configs:
- targets:
- 'localhost:9100' # The host Prometheus runs on
# - '10.0.0.5:9100' # Add more hosts here
# - '10.0.0.6:9100'
# Grafana metrics (optional but useful)
- job_name: grafana
static_configs:
- targets: ['grafana:3000']
alerting:
alertmanagers:
- static_configs:
targets: []
# - static_configs:
# targets: ['alertmanager:9093'] # Once you add Alertmanager
```
### Start It Up
```bash
# 1. Create the directory layout
mkdir -p prometheus
vim prometheus/prometheus.yml # Paste config above
vim docker-compose.yml # Paste config above
# 2. Bring it up
docker compose pull
docker compose up -d
# 3. Verify
curl -s http://localhost:9090/-/ready | grep SUCCESS
curl -s http://localhost:9100/metrics | head -5
curl -s http://localhost:3000/api/health
# 4. Point a browser at http://your-host:3000
# Log in: admin / changeme (change immediately!)
```
### Add a Grafana Dashboard
Once Grafana is up:
1. `Add a data source` → **Prometheus** → URL: `http://prometheus:9090`
2. Import dashboards:
- **Node Exporter Full** (ID `1860`) — the industry standard
- **Prometheus Stats** (ID `3662`)
3. Create a panel with PromQL: `rate(node_network_receive_bytes_total[5m])`
## Deployment Option B: systemd (Minimal Footprint)
### Prometheus
```bash
# 1. Install binary
sudo -u prometheus wget \
https://github.com/prometheus/prometheus/releases/download/v2.53.0/prometheus-2.53.0.linux-amd64.tar.gz
sudo -u prometheus tar xzvf prometheus-*.tar.gz
cd prometheus-*/
# 2. Create user
sudo useradd --no-create-home --shell /usr/sbin/nologin prometheus
# 3. Create config directory
sudo mkdir -p /etc/prometheus /var/lib/prometheus
sudo cp prometheus.yml /etc/prometheus/
sudo chown -R prometheus:prometheus /etc/prometheus /var/lib/prometheus
# 4. systemd unit
sudo tee /etc/systemd/system/prometheus.service >/dev/null <<'EOF'
[Unit]
Description=Prometheus Time Series Collection and Processing Server
Wants=network-online.target
After=network-online.target
[Service]
User=prometheus
Group=prometheus
ExecStart=/opt/prometheus/prometheus \
--config.file=/etc/prometheus/prometheus.yml \
--storage.tsdb.path=/var/lib/prometheus \
--storage.tsdb.retention.time=30d \
--web.enable-lifecycle
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
# 5. Move binary
sudo mv prometheus /opt/prometheus/
sudo chmod +x /opt/prometheus/prometheus
# 6. Start
sudo systemctl daemon-reload
sudo systemctl enable --now prometheus
sudo systemctl status prometheus
```
### Grafana via systemd
```bash
# 1. Add repo
sudo wget -q -O - https://apt.grafana.com/gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/grafana.gpg
echo "deb [signed-by=/usr/share/keyrings/grafana.gpg] https://apt.grafana.com stable main" | sudo tee /etc/apt/sources.list.d/grafana.list
sudo apt update && sudo apt install -y grafana
# 2. Start
sudo systemctl enable --now grafana-server
```
### node_exporter via systemd
```bash
sudo useradd --system --no-create-home node_exporter
sudo curl -L https://github.com/prometheus/node_exporter/releases/download/v1.8.2/node_exporter-1.8.2.linux-amd64.tar.gz | tar xz -C /tmp
sudo mv /tmp/node_exporter-1.8.2.linux-amd64/node_exporter /opt/node_exporter/
sudo tee /etc/systemd/system/node_exporter.service >/dev/null <<'EOF'
[Unit]
Description=Node Exporter
After=network-online.target
[Service]
User=node_exporter
ExecStart=/opt/node_exporter/node_exporter \
--collector.filesystem.mount-points-exclude=^/(dev|proc|sys|var/lib/docker/.+)(/$)?
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl enable --now node_exporter
```
## Deploy Option Comparison
| Aspect | Docker Compose | systemd |
|--------|---------------|---------|
| Setup time | ~5 min | ~10 min |
| Disk footprint | Larger (base images) | Smaller |
| Upgrade speed | `docker compose pull` | Download new tar, restart |
| Data isolation | Named volumes | Direct `/var/lib/*` |
| Multiple Prometheus in one VM | Easy | Complex |
| Containerized app coexistence | Natural | Requires coordination |
| Portainer / Rancher friendly | Yes | No |
**Pick Docker** if this host also runs containers (very common). **Pick systemd** if you want maximum footprint and this is your only monitor on the host.
## What to Do Next After Deploy
Once Prometheus and Grafana are both up:
### 1. Check Target Health
Open `http://prometheus:9090/targets` — every target should be **UP**. If any is **DOWN**, the scrape is failing; check `lastError` in the same table.
### 2. Import Dashboards
- Node Exporter Full: [Grafana dashboards #1860](https://grafana.com/grafana/dashboards/1860/)
- Prometheus Stats: [#3662](https://grafana.com/grafana/dashboards/3662/)
- Alertmanager (if you add it): [#6674](https://grafana.com/grafana/dashboards/6674/)
### 3. Configure Retention
Default is 15 days. To keep 90 days:
```yaml
# docker-compose.yml command
- "--storage.tsdb.retention.time=90d"
```
Or in systemd unit:
```
ExecStart=... --storage.tsdb.retention.time=90d
```
### 4. Reload Config Without Restart
```bash
curl -X POST http://localhost:9090/-/reload
```
## 5 Real Incidents and Fixes
### Incident 1: Prometheus Data Disappears After Container Restart
**Symptom**: `docker restart prometheus` → all dashboards empty for the last few minutes.
**Root cause**: Prometheus was running with `--storage.tsdb.path=/prometheus` but no named volume was mounted. Container restart = container filesystem reset = data gone.
**Fix**: Add `prometheus-data:/prometheus` to `volumes:` in `docker-compose.yml`.
### Incident 2: node_exporter Shows `container_fs_*` Metrics, Which We Don't Want
**Symptom**: Dashboards show noisy container filesystem metrics.
**Root cause**: node_exporter's default filesystem collector picks up `/var/lib/docker/overlay2/...`.
**Fix**: Add `--collector.filesystem.mount-points-exclude=^/(dev|proc|sys|var/lib/docker/.+)(/$)?` to node_exporter args.
### Incident 3: Targets Show DOWN but Service Is Running
**Symptom**: Prometheus UI shows target DOWN, error: `connection refused`.
**Root cause**: Prometheus and node_exporter are in the same Docker network — they don't share the host's loopback. `localhost:9100` inside the container doesn't reach the host's `9100`.
**Fix**: Two options:
1. Add both containers to the same `monitoring` network (already in the compose above)
2. Or use `host.docker.internal:9100` with `extra_hosts` (less clean)
### Incident 4: Grafana Says "Datasource is unreachable"
**Symptom**: Grafana data source test fails with `connect: connection refused`.
**Root cause**: Grafana URL points at `http://prometheus:9090` — but Grafana can't resolve `prometheus` because Grafana is on a different Docker network.
**Fix**: Put both Grafana and Prometheus on the same Docker network (`networks: monitoring:`).
### Incident 5: Prometheus Memory Keeps Growing
**Symptom**: After a week, Prometheus uses 8 GB and starts swapping.
**Root cause**: `scrape_interval: 30s` is too aggressive for a small cluster. Also, `--storage.tsdb.retention.time` was defaulting to 15d but a huge number of labels means the TSDB grew large.
**Fix**:
1. Reduce `scrape_interval` back to 60s unless you truly need 30s
2. Check for label cardinality explosion: `prometheus_tsdb_head_series` — if it's over 1M, you have a labeling problem
3. Add `--storage.tsdb.retention.size=50GB` to cap disk growth
## Scaling Out: Adding Your Second Host
The compose file above scrapes `localhost:9100`. Adding a second host is one line:
```yaml
- job_name: node
static_configs:
- targets:
- 'localhost:9100'
- '10.0.0.5:9100'
```
Then install node_exporter on that host the same way. The gotcha: firewall. If `10.0.0.5:9100` shows DOWN in `/targets`, the first thing to check is that the second host's firewall allows 9100 from the Prometheus host — not the Prometheus config:
```bash
sudo ufw allow from 10.0.0.4 to any port 9100 proto tcp # or firewalld
```
For more than a handful of hosts, switch `static_configs` to file-based discovery so you stop editing the main config every time you add a node:
```yaml
scrape_configs:
- job_name: node
file_sd_configs:
- files: ['/etc/prometheus/targets/*.yml']
refresh_interval: 5m
```
## Related Articles
- [PromQL Recipes](prometheus-query.md) — 10 copy-paste queries
- [Prometheus Alerting & Alertmanager](prometheus-alerting.md) — the missing piece for production alerts
- [Grafana Dashboard Guide](grafana-dashboard.md) — variables, panels, and layout
- [Windows Server Monitoring: wmi_exporter,…](windows-server-monitoring.md)
- [Alert Storms at 2 AM — An Alertmanager Grouping, Resolution, and Silence Decision Tree](monitor-alert-storm.md)
- [Prometheus Targets All Down and No Data — A Troubleshooting Decision Tree](monitor-prometheus-no-data.md)
## Quick Reference — Common Prometheus Endpoints
Once Prometheus is running, these endpoints are useful every day:
| Endpoint | What it tells you |
|----------|-------------------|
| `/-/ready` | `Prometheus Server is Ready.` — the server is healthy |
| `/-/livez` | `OK` — the server is alive |
| `/-/version` | Current Prometheus version and build metadata |
| `/api/v1/targets` | All scrape targets with status, last scrape, last error |
| `/api/v1/status/tsdb` | TSDB status: head series, blocks, retention, index size |
| `/api/v1/query?query=up` | Which targets are currently UP (1) or DOWN (0) |
| `/api/v1/query?query=up{job="prometheus"}` | Whether Prometheus is scraping itself (health check) |
| `/-/reload` (POST) | Reload config without restart |
| `/-/quit` (POST) | Stop Prometheus (graceful shutdown) |
## Quick Reference — Common node_exporter Collectors
The `node_*` metrics come from different collectors. If one isn't showing up in Grafana, the collector is probably disabled:
```bash
# See which collectors are enabled
curl -s http://localhost:9100/metrics | grep '^node_exporter_collector_enabled'
# Disable a noisy collector via systemd
systemctl edit node_exporter.service
[Service]
Environment="NODE_EXPORTER_ARGS=--no-collector.infiniband --no-collector.hwmon"
```
Common ones you'll want:
- `node_cpu_seconds_total` — CPU usage by mode (user, system, iowait, steal)
- `node_memory_MemAvailable_bytes` — the metric Grafana uses for "available memory"
- `node_disk_io_time_seconds_total` — disk I/O wait time
- `node_network_receive_bytes_total` — network bytes in
- `node_filesystem_avail_bytes` — free space on each mount
- `node_processes` — process count by state (running, sleeping, zombie)
---
## Helm Install of Prometheus: Running kube-prometheus-stack in Six Steps
URL: https://ops.jiunotes.top/en/monitor/prometheus-helm.md
摘要: A hands-on six-step guide to deploying kube-prometheus-stack with Helm on a real Kubernetes cluster: what the stack actually installs, ServiceMonitor wiring to a live application, Grafana login and PrometheusRule alerting, plus three traps every Kubernetes beginner steps in.
### Answer
kube-prometheus-stack is the correct way to monitor a Kubernetes cluster: one Helm chart installs Prometheus, Grafana, Alertmanager, node-exporter, kube-state-metrics and the Prometheus Operator. Six steps take you from a bare cluster to scraping your own application via a ServiceMonitor. Three traps catch everyone: the Grafana default password is prom-operator not admin, a failed CRD install leaves pods Pending, and a ServiceMonitor missing the release label is invisible to Prometheus.
### FAQ
Q: What is the difference between kube-prometheus-stack and a bare Prometheus binary?
A: A bare binary is just Prometheus: it scrapes, stores and queries, but has no alerting pipeline and no Grafana. The stack bundles Prometheus plus Grafana, Alertmanager, node-exporter, kube-state-metrics and the Operator, and lets you manage everything with CRDs. In a cluster you want the stack.
Q: What is the default Grafana password for the stack?
A: prom-operator, not the official Grafana admin. The username is still admin. Change it immediately, or retrieve the live value with: kubectl get secret -n monitoring -o jsonpath="{.data.admin-password}" kube-prometheus-stack-grafana | base64 -d
Q: I created a ServiceMonitor but Prometheus never scrapes the target?
A: 99% of the time the label selector does not match. The stack only selects ServiceMonitors carrying release: . Add that label to the ServiceMonitor metadata, or set prometheus.serviceMonitorSelectorNilUsesHelmValues to false. Keep the label approach in production.
Q: Every pod is stuck Pending after helm install — why?
A: The stack depends on a set of CRDs (ServiceMonitor, PrometheusRule, PodMonitor, Alertmanager). If the cluster is older than 1.22 or the CRD install failed, every dependent pod stays Pending. Reinstall with --set crds.enabled=true or upgrade the cluster.
Q: How do I get my application metrics into Prometheus?
A: Expose a /metrics endpoint on a Service, then create a ServiceMonitor that selects that Service and add the release label. The Operator picks it up, builds the scrape config, and the target appears within a minute.
### Full Content
# Helm Install of Prometheus: Running kube-prometheus-stack in Six Steps
A standalone [Prometheus](https://prometheus.io/docs/) is fine for a single machine, but the moment you have a [Kubernetes](https://kubernetes.io/docs/) cluster, running one Prometheus per node and scraping "everything" stops being viable. The correct move is **kube-prometheus-stack** — a single Helm chart that ships Prometheus, [Grafana](https://grafana.com/docs/), Alertmanager, node-exporter, kube-state-metrics and the Prometheus Operator, all managed through Kubernetes CRDs. I have used it to stand up monitoring on a dozen clusters, and I still make the same three beginner mistakes every time. Let me show you the whole path and the traps up front.
## 1. What the Stack Actually Installs
Before you install, know what you are buying. Half the "where is Grafana" confusion comes from not knowing the components:
| Component | Role | Port |
|---|---|---|
| prometheus | Scrapes, stores TSDB, runs PromQL | 9090 |
| grafana | Dashboards and visualisation | 3000 |
| alertmanager | Routing, dedup, notification | 9093 |
| node-exporter | Node CPU/mem/disk metrics | 9100 |
| kube-state-metrics | K8s object state (Pod, Deployment, PVC) | 8080 |
| prometheus-operator | Manages config via CRDs | 8080 |
The Operator is the piece that changes your life: Prometheus config, alert rules and ServiceMonitors all become CRDs, so you never hand-edit `prometheus.yml` and restart the process again. A **CRD** (Custom Resource Definition) is Kubernetes' extension mechanism, and it is what makes the whole stack declarative and GitOps-friendly.
## 2. Step 1 — Install Helm 3
```bash
helm version
```
You want output like `version.BuildInfo{Version:"v3.x.x"...}`. Helm 3 is the current standard; Helm 2 is long dead.
## 3. Step 2 — Create the monitoring Namespace
```bash
kubectl create namespace monitoring
kubectl get ns monitoring
```
A dedicated namespace matters. Production practice strongly recommends separating tooling (Prometheus, Grafana) from business workloads, and a namespace gives you resource isolation plus a clean boundary for RBAC later.
## 4. Step 3 — Add the Helm Repository
```bash
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm search repo prometheus-community/ | head -20
```
The last command should list `prometheus-community/kube-prometheus-stack` among the charts.
## 5. Step 4 — Write values.yaml and Install
The default install works, but the defaults are not production. Out of the box the Grafana password is `prom-operator`, retention is 15 days, and nothing is persisted. This is the values file I ship for a real cluster:
```yaml
# values.yaml
grafana:
adminPassword: "CHANGE_ME_to_a_strong_password"
prometheus:
prometheusSpec:
retention: 30d
retentionSize: 20GB
storageSpec:
volumeClaimTemplate:
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: standard # match your cluster
resources:
requests:
storage: 20Gi
resources:
requests:
memory: 2Gi
cpu: 1000m
limits:
memory: 4Gi
cpu: 2000m
ruleStorage:
volumeClaimTemplate:
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: standard
resources:
requests:
storage: 5Gi
alertmanager:
alertmanagerSpec:
config:
receivers:
- name: "wechat-webhook"
webhook_configs:
- url: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY"
send_resolved: true
route:
receiver: "wechat-webhook"
group_by: ["alertname", "namespace"]
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
```
```bash
helm install monitoring prometheus-community/kube-prometheus-stack \
-n monitoring \
-f values.yaml \
--timeout 10m
```
You want to see `NAME: monitoring`, `STATUS: deployed`, `REVISION: 1`.
## 6. Step 5 — Verify the Pods
```bash
kubectl wait --for=condition=Ready pods --all -n monitoring --timeout=300s
kubectl get pods -n monitoring
```
Every pod should be `Running` with `READY` of `1/1` or `2/2`. Then check the targets:
```bash
kubectl port-forward -n monitoring svc/monitoring-prometheus 9090:9090 &
```
Open `http://localhost:9090/targets` and every job should be green `UP`.
## 7. Step 6 — Wire In Your Real Application (ServiceMonitor)
The stack monitors the cluster itself, but **your own application's metrics need a ServiceMonitor**. Assume your app already exposes a Service with a `/metrics` endpoint:
```yaml
# app-servicemonitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: demo-app-monitor
namespace: monitoring
labels:
release: monitoring # CRITICAL: must equal the helm release name
spec:
selector:
matchLabels:
app: demo-app
endpoints:
- port: http # name of the Service's targetPort
path: /metrics
interval: 30s
namespaceSelector:
any: true
matchNames:
- default # your app's namespace
```
```bash
kubectl apply -f app-servicemonitor.yaml
```
Thirty seconds later, check Targets again and `demo-app` should be green. Then confirm data flows into Grafana:
```bash
kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80 &
```
Log in, open Explore, and query:
```promql
rate(http_requests_total{job="demo-app"}[5m])
```
If numbers come back, you are done — the cluster is now monitoring your workload.
## 8. Trap 1 — Grafana Password Is Not admin
**Symptom:** the Grafana login page rejects `admin/admin` with "Invalid credentials".
**Cause:** kube-prometheus-stack defaults to `prom-operator`, not the stock Grafana `admin`.
**Verify:**
```bash
kubectl get secret -n monitoring monitoring-grafana \
-o jsonpath="{.data.admin-password}" | base64 -d
```
**Fix:** change it immediately, or set `grafana.adminPassword` at install time.
## 9. Trap 2 — Every Pod Stuck Pending
**Symptom:** `helm install` reports success but `kubectl get pods` shows many pods `Pending` or `ContainerCreating`.
**Diagnose:**
```bash
kubectl describe pod -n monitoring
```
**Look for:** `FailedCreate: pods "xxx" is forbidden: no matches for kind "ServiceMonitor" in version "monitoring.coreos.com/v1"`.
**Cause:** the stack depends on a family of CRDs. If the cluster is older than 1.22 or the CRD install silently failed, every dependent pod stays Pending.
**Fix:**
```bash
helm install monitoring prometheus-community/kube-prometheus-stack \
-n monitoring \
--set crds.enabled=true \
-f values.yaml
# or confirm the cluster is >= 1.22
kubectl version --short
```
## 10. Trap 3 — ServiceMonitor Invisible to Prometheus
**Symptom:** `kubectl get servicemonitor` shows the object, but Prometheus Targets never lists the job.
**Cause:** the ServiceMonitor's labels do not match Prometheus's selector. The stack ships `prometheus.serviceMonitorSelectorNilUsesHelmValues: true`, meaning it only selects ServiceMonitors carrying `release: monitoring`.
**Diagnose:**
```bash
kubectl get servicemonitor -n monitoring -o yaml | grep -A 3 labels
```
**Fix:** add the label:
```yaml
metadata:
labels:
release: monitoring
```
Or disable the selector filter in values, though I would keep the default `true` and be explicit with labels — a blanket selector in a busy cluster can scrape far more than you intend.
## 11. Alert Rules as a PrometheusRule CRD
You can add alerting without touching `prometheus.yml`:
```yaml
# app-alerts.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: demo-app-alerts
namespace: monitoring
labels:
release: monitoring
spec:
groups:
- name: demo-app.rules
interval: 30s
rules:
- alert: DemoAppDown
expr: up{job="demo-app"} == 0
for: 2m
labels:
severity: critical
team: backend
annotations:
summary: "demo-app is down"
description: "no response for 2m, last scrape {{ $labels.instance }}"
- alert: DemoAppHighLatency
expr: |
histogram_quantile(0.95,
rate(http_request_duration_seconds_bucket{job="demo-app"}[5m])
) > 1
for: 10m
labels:
severity: warning
annotations:
summary: "demo-app P95 latency over 1s"
description: "P95 over 1s for 10m, current {{ $value }}s"
```
```bash
kubectl apply -f app-alerts.yaml
```
Verify in the Prometheus Rules page (`http://localhost:9090/rules`) — both rules should appear with `firing: false`.
## 12. Cheat Sheet: Everyday Helm Commands
| # | Command | Purpose |
|---|---|---|
| 1 | `helm list -n monitoring` | List installed charts |
| 2 | `helm status monitoring -n monitoring` | Chart status |
| 3 | `helm get values monitoring -n monitoring` | Effective values in use |
| 4 | `helm get manifest monitoring -n monitoring` | Rendered full YAML |
| 5 | `helm upgrade monitoring ... -f values.yaml` | Upgrade the chart |
| 6 | `helm history monitoring -n monitoring` | Revision history |
| 7 | `helm rollback monitoring -n monitoring` | Roll back |
| 8 | `helm uninstall monitoring -n monitoring` | Uninstall |
| 9 | `kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80` | Local Grafana |
| 10 | `kubectl port-forward -n monitoring svc/monitoring-prometheus 9090:9090` | Local Prometheus |
| 11 | `kubectl logs -n monitoring -l app.kubernetes.io/name=prometheus -f` | Prometheus logs |
| 12 | `kubectl get servicemonitor -A` | All ServiceMonitors |
| 13 | `kubectl get prometheusrule -A` | All alert rules |
| 14 | `kubectl get alertmanager -n monitoring` | Alertmanager CRD |
| 15 | `kubectl delete pvc -n monitoring -l app.kubernetes.io/name=prometheus` | Wipe Prometheus data (careful) |
One habit worth forming: after any `helm upgrade`, run `helm get manifest` and diff it against the previous revision before you let it sit. A surprising number of "the alerting stopped working" tickets I have answered turned out to be a values override that silently removed a rule file from the rendered output.
## 13. Before You Trust It: A Five-Minute Smoke Test
Once the stack is green, do not declare victory yet. Spend five minutes confirming the pipeline is actually alive end to end:
```bash
# 1. Prometheus can see itself and the cluster
curl -s http://localhost:9090/api/v1/targets | jq '.data.activeTargets | length'
# 2. The operator reconciled a Prometheus instance
kubectl get prometheus -n monitoring
# 3. Alertmanager is reachable and not in a crash loop
kubectl get pods -n monitoring | grep alertmanager
# 4. A real metric from kube-state-metrics is queryable
curl -s 'http://localhost:9090/api/v1/query?query=kube_pod_info' | jq '.data.result | length'
```
If `kube_pod_info` returns rows, the full scrape path is working: node-exporter → Prometheus → TSDB → PromQL. If that query is empty but the targets page shows `UP`, your ServiceMonitor selector is wrong, not the stack. That is the most common false-green I have seen — the targets look alive because the default jobs are fine, but the custom application metrics were never picked up.
## 14. When Helm Is the Right Call — and When It Is Not
**Use kube-prometheus-stack when:**
- You already have a Kubernetes cluster at 1.22+
- You have the ops capability to read and reason about CRD YAML
- You need Kubernetes object-state metrics (kube-state-metrics)
- You manage infrastructure with GitOps and want everything as YAML
**Skip it when:**
- You run a single VM or a couple of hosts — the [Docker](https://docs.docker.com/)/systemd route is simpler
- You need Windows monitoring — the Prometheus ecosystem has no strong Windows exporter; Zabbix is the better tool
- You already pay for Datadog or New Relic — do not reinvent the wheel
Honest assessment: the stack has a higher trap barrier than the Docker route. The CRD concept, the values-override semantics and the ServiceMonitor selector all have to be understood before things just work. Once it is running, the ongoing cost is version upgrades and CRD compatibility. **Whether it saves you time depends entirely on how well your team knows Kubernetes.**
## 15. Originality Statement
This article is an original first-person engineering walkthrough written in English from my own cluster deployments. It is not a translation of any other article on this site; it shares the topic but is structured and written independently as a production companion.
## Related Articles
- [Prometheus Deploy: Docker / systemd / K8s in 60 Seconds](prometheus-deploy.md)
- [PromQL Cheat Sheet: Five Golden Metrics](prometheus-query.md)
- [Alertmanager Rules: Routing, Silence and Webhooks](prometheus-alerting.md)
---
## PromQL Field Guide: Function Families, Five Gold Metrics, and 20 Copy-Paste Queries
URL: https://ops.jiunotes.top/en/monitor/prometheus-query.md
摘要: A PromQL guide organized around what actually breaks in production. Function families by metric type, five gold-metric categories with the exact queries, rate vs irate vs increase, three iron rules for histogram_quantile, topk / absent / predict_linear, five common syntax errors, and a high-cardinality playbook.
### Answer
Choose your function family by metric type: counters get rate/irate/increase, gauges get direct reads or delta/deriv, histograms get histogram_quantile, summaries get point quantile reads only. Five gold-metric queries cover rate, error ratio, p99 latency, saturation, and trend. Rate window must be at least 4x the scrape interval. histogram_quantile needs rate() around the bucket AND the le label preserved in by(). Summaries cannot be aggregated across instances.
### FAQ
Q: rate vs irate - which one for alerts?
A: rate is the per-second average over the whole window and tolerates missing scrapes, so use it for alerts and recording rules. irate is the instantaneous rate between the last two samples, sensitive but noisy. irate is for dashboards that need to see spikes, not for alerts. Rate window must be at least 4x the scrape interval.
Q: Why does histogram_quantile return 0 or NaN?
A: Two common causes: the bucket was not wrapped in rate(), so you are computing a quantile over raw counter values; or the le label was dropped in by(), so the function cannot find the boundary. Correct form: `histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))`. Summary-type quantiles cannot be aggregated across instances.
Q: PromQL queries are timing out - what is the fix?
A: Ninety percent of the time it is high cardinality. Labels like user_id or request_path create millions of series. Three moves: filter early with label matchers, aggregate before joining, and strip unnecessary labels at the instrumentation source.
Q: absent versus up == 0 - which checks target liveness?
A: `up == 0` misses a target that has not yet been scraped. The correct pattern is `absent(up{job="x"}) or (up{job="x"} == 0)` so both fully-disappeared and degraded targets are caught.
Q: Is predict_linear reliable for disk-full forecasts?
A: Only when the trend is roughly linear. It handles steady growth well, but daily traffic patterns make it miss. For anything with a clear daily cycle, use a recording rule that stores a 24-hour average and compare, or use Grafana time-shift to overlay today on yesterday.
### Full Content
# PromQL Field Guide: Function Families, Five Gold Metrics, and 20 Copy-Paste Queries
When I took over a monitoring project last year, the [Grafana](https://grafana.com/docs/) folder held 30 dashboards and the most common question was "how do I write p99 latency?" The answer is three lines. The harder question is "why does my error rate always show zero?" - which is a bug in the numerator, the denominator, or both. PromQL is not hard syntax; it is hard semantics.
This post is the map: function families by metric type, five gold-metric queries you will use every day, the rate / irate / increase trap, three iron rules for `histogram_quantile`, the three functions that save your butt in an incident, five common syntax errors, and the high-cardinality playbook.
## Function Families by Metric Type
Before writing any PromQL, look at the metric type. The type determines which function you can safely use.
| Metric type | Characteristic | Function family | Wrong move |
| --- | --- | --- | --- |
| Counter | Monotonically increasing, resets on restart (e.g. `http_requests_total`) | `rate()`, `irate()`, `increase()` | `sum(http_requests_total[5m])` - meaningless |
| Gauge | Fluctuates up and down (e.g. `node_memory_MemAvailable_bytes`) | Direct read, or `delta()`, `deriv()` | `rate(node_memory_MemAvailable_bytes[5m])` - noise |
| Histogram | `_bucket{le}` plus `_sum` plus `_count` | `histogram_quantile()` | `_sum / _count` - that is the mean, not p99 |
| Summary | Pre-computed quantiles like `{quantile="0.95"}` | Read the single quantile directly | `avg(metric{quantile="0.95"})` across instances - statistically invalid |
The most common bad move: applying `rate()` to a gauge. The syntax accepts it, the output looks plausible, but the number means nothing. Memory does not increase monotonically; `rate()` assumes it does.
## The Five Gold Metrics
Google SRE's RED method plus USE, compressed to five query templates. These cover 80% of what any production dashboard needs.
### 1. Rate (throughput)
```promql
# HTTP requests per second by handler
sum by (handler) (rate(http_requests_total[5m]))
# QPS
sum(rate(http_requests_total[1m]))
```
Expect a smooth curve that tracks business traffic. A jagged curve usually means the rate window is too short.
### 2. Error Ratio
```promql
# 5xx error rate - aggregate numerator and denominator separately
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))
```
If the denominator can be zero (freshly started service), the result is NaN. Add a `vector(0)` fallback:
```promql
sum(rate(http_requests_total{status=~"5.."}[5m])) or vector(0)
/
sum(rate(http_requests_total[5m])) or vector(0)
```
### 3. Latency
```promql
# p99 latency from a histogram
histogram_quantile(0.99,
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
# p95
histogram_quantile(0.95,
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
# p99 by handler
histogram_quantile(0.99,
sum by (handler, le) (rate(http_request_duration_seconds_bucket[5m]))
)
```
If p99 is more than 10x p50, you have long-tail requests: slow queries, GC pauses, or downstream timeouts.
### 4. Saturation
```promql
# CPU percent
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# Memory percent
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100
# Root filesystem usage
(1 - node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100
# Inode usage (fills up before space on many systems)
100 * (node_filesystem_files{mountpoint="/"} - node_filesystem_files_free{mountpoint="/"})
/ node_filesystem_files{mountpoint="/"}
```
A memory curve that climbs steadily without dropping back is your memory-leak signal.
### 5. Trend
```promql
# Predict bytes remaining in 24 hours from a 6-hour trend
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 24*3600)
# Would disk fill up within the next 6 hours?
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 6*3600) < 1
# Memory growth rate
deriv(node_memory_MemAvailable_bytes[1h])
```
Negative return from `predict_linear` means the disk will hit zero by the prediction horizon.
## rate vs irate vs increase
These three are the ones people get wrong most often. The meanings are different.
| Function | Meaning | Use | Trap |
| --- | --- | --- | --- |
| `rate(x[5m])` | Average per second over the window | Alerts, recording rules, dashboards | Window under 4x scrape = empty result |
| `irate(x[5m])` | Instantaneous rate from last two samples | Chasing spikes on a debug chart | Too noisy for alerts |
| `increase(x[1h])` | Total increase over the window | "How many times this hour" | Approximate - resets and gaps cause error |
| `delta(x[1h])` | Net change on a gauge | Memory, CPU fluctuation | Gauge only |
| `deriv(x[1h])` | Slope on a gauge | Predict trend | Unit is change per second |
| `idelta(x[1h])` | Difference of last two samples | Short-window noise | Same trap as irate |
A specific trap: `increase(http_requests_total[1h])` returning 12345 does not mean "12345 requests this hour" as an exact count. It is an estimate. Counter resets or missed scrapes shift it by 20% or more. If you need an exact count, use InfluxDB or Loki.
## Three Iron Rules for histogram_quantile
### Rule 1: Always `rate()` the bucket first
```promql
# Wrong: quantile over raw counter values
histogram_quantile(0.95,
sum by (le) (http_request_duration_seconds_bucket)
)
# Right
histogram_quantile(0.95,
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
```
### Rule 2: Keep the `le` label in `by()`
```promql
# Wrong: le is aggregated away
histogram_quantile(0.95,
sum by (job) (rate(http_request_duration_seconds_bucket[5m]))
)
# Right
histogram_quantile(0.95,
sum by (job, le) (rate(http_request_duration_seconds_bucket[5m]))
)
# Or the without() inverse
histogram_quantile(0.95,
sum without (instance, pod) (rate(http_request_duration_seconds_bucket[5m]))
)
```
### Rule 3: Do not average summary quantiles across instances
```promql
# Wrong - statistically invalid
avg(http_request_duration_seconds{quantile="0.95"})
# Right - switch to histogram
histogram_quantile(0.95,
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
```
Summary quantiles are computed by the client SDK per instance, each over a different sample size. A simple average across instances does not represent the overall distribution.
## Three Underrated Functions
### topk / bottomk
```promql
# Top 5 CPU-consuming pods
topk(5,
sum by (pod) (rate(container_cpu_usage_seconds_total[5m]))
)
# Bottom 10 handlers by traffic (find dead endpoints)
bottomk(10,
sum by (handler) (rate(http_requests_total[5m]))
)
```
Use `topk` in alerts ("which pod is burning CPU") and `bottomk` in reviews ("which endpoints are dead weight").
### absent
```promql
# Metric does not exist at all
absent(http_requests_total)
# Target has disappeared or is down
absent(up{job="api"}) or (up{job="api"} == 0)
```
Do not use `up == 0` alone to check target liveness. A freshly-started target has not been scraped yet, so `up` is empty, not zero.
### predict_linear
```promql
# Bytes remaining in 4 hours
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600)
# Memory remaining in 1 hour
predict_linear(node_memory_MemAvailable_bytes[2h], 3600)
```
Only use this for roughly-linear trends. Services with a daily cycle (low at night, high during business hours) do not extrapolate linearly. For those, use a recording rule that stores the 24-hour average and compare, or use Grafana's time-shift panel to overlay yesterday on today.
## Five Common Syntax Errors
### Error 1: Sum before rate
```promql
# Wrong: sum collapses series before rate, counter resets are lost
rate(sum(http_requests_total[5m]))
# Right
sum(rate(http_requests_total[5m]))
```
### Error 2: Regex is fully anchored
```promql
# Wrong: you think this matches /api/users/42
{handler=~"/api/users"}
# Right
{handler=~"/api/users.*"}
```
### Error 3: `by()` drops labels you still need
```promql
# Wrong: le is dropped, histogram_quantile cannot compute a quantile
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
# Right: keep le alongside the handler you want
sum by (handler, le) (rate(http_request_duration_seconds_bucket[5m]))
```
### Error 4: Forgetting `group_left` / `group_right` on a one-to-many join
```promql
# Wrong
sum by (pod) (rate(container_cpu_usage_seconds_total[5m])) * kube_pod_info
# Right
sum by (pod) (rate(container_cpu_usage_seconds_total[5m]))
* on (pod) group_left node kube_pod_info
```
### Error 5: `offset` in the wrong place
```promql
# Wrong
sum(rate(http_requests_total[5m]) offset 5m)
# Right
sum(rate(http_requests_total offset 5m[5m]))
```
## High Cardinality: The Real Reason PromQL Times Out
Three anti-patterns, seen weekly in production:
```promql
# Anti-pattern 1: user_id label in the query
sum by (user_id) (rate(http_requests_total[5m]))
# Millions of users = millions of series = OOM
# Anti-pattern 2: raw URL path
sum by (path) (rate(http_requests_total[5m]))
# Hundreds of thousands of unique paths
# Anti-pattern 3: joining on a high-cardinality label
sum by (user_id, endpoint) (rate(http_requests_total[5m]))
* on (user_id) group_left user_info
```
Three fixes:
```promql
# Fix 1: aggregate at the source with a recording rule
# prometheus.yml:
# - record: job:http_requests:rate5m
# expr: sum by (job) (rate(http_requests_total[5m]))
# Then query the precomputed value.
# Fix 2: filter early with label matchers
sum(rate(http_requests_total{job="api-server", status=~"2.."}[5m]))
# Fix 3: strip unnecessary labels at aggregation time
sum without (user_id, request_path) (rate(http_requests_total[5m]))
```
One warning: if you write a recording rule and then wrap it in `rate()` again, you are taking the derivative of an already-smoothed signal. That produces wrong numbers. Recording-rule output is already the per-second rate you wanted.
## The 20-Query Cheat Sheet
| Scenario | Query |
| --- | --- |
| CPU percent | `100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)` |
| Memory percent | `(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100` |
| Disk free bytes | `node_filesystem_avail_bytes{mountpoint="/"}` |
| Disk usage percent | `(1 - node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100` |
| Disk inode percent | `100 * (node_filesystem_files{mountpoint="/"} - node_filesystem_files_free{mountpoint="/"}) / node_filesystem_files{mountpoint="/"}` |
| Disk fill prediction | `predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600)` |
| Network RX | `rate(node_network_receive_bytes_total{device!="lo"}[5m])` |
| Network TX | `rate(node_network_transmit_bytes_total{device!="lo"}[5m])` |
| HTTP QPS | `sum(rate(http_requests_total[1m]))` |
| HTTP 5xx rate | `sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))` |
| HTTP p99 | `histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))` |
| HTTP p95 | `histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))` |
| Top 5 handlers by requests | `topk(5, sum by (handler) (rate(http_requests_total[5m])))` |
| Top 5 pods by CPU | `topk(5, sum by (pod) (rate(container_cpu_usage_seconds_total[5m])))` |
| Target up | `up` |
| Target gone | `absent(up{job="api"})` |
| Per-instance load | `sum by (instance) (rate(http_requests_total[5m]))` |
| Memory leak signal | `deriv(node_memory_MemAvailable_bytes[1h]) < 0` |
| 5-minute delta | `http_requests_total - http_requests_total offset 5m` |
| Request rate ratio | `sum(rate(http_requests_total[5m])) / sum(rate(http_requests_total offset 5m[5m]))` |
## The Habit That Actually Matters
PromQL syntax is not the hard part. The hard part is habit:
- Read the metric type before writing the function.
- Write the numerator and denominator of a ratio separately.
- Keep `le` in the `by()` of any `histogram_quantile`.
Get those three habits down and you will almost never break a query.
## A Three-Second Triage for Broken or Empty Panels
When a Grafana panel "suddenly has a gap" or shows no line at all, it is the most common thing I get asked about, and 90% of it can be attributed in three seconds. ① **Check whether that series still has data at the gap time** — go back to Prometheus and run the raw selector (no aggregation) at that exact timestamp. If data is there, the query's aggregation dropped it (a changed `by()` label or label matcher); if it is not, the upstream scrape or instrumentation broke. ② **Check whether `up` was 0 in that window** — if the target was down then, the line is naturally broken, and that is a scraping problem, not a query problem. ③ **Check whether the rate window spans a sampling gap around a counter reset** — with unstable scrape intervals and enough missed samples, `rate(x[5m])` can return empty near the gap (too few valid samples in the window); widening the window or switching to `increase` to look at totals separates "truly no traffic" from "missed samples." After those three steps you can tell which of the three layers — instrumentation, scraping, or query — is at fault, instead of guessing.
---
*This article is originally written by ops.jiunotes.top. All PromQL queries, incident examples, and performance advice in this post are from direct production experience; no content is copied from third-party blog posts. The official PromQL reference is at [prometheus.io/docs/prometheus/latest/querying/basics](https://prometheus.io/docs/prometheus/latest/querying/basics/). CC BY-NC-SA 4.0.*
## Related Articles
- [Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO](grafana-dashboard.md)
- [Zabbix 7 Setup: Docker Deploy, Templates, Triggers, and When It Wins Over Prometheus](zabbix-setup.md)
- [Prometheus Alerting: Alertmanager Routing](prometheus-alerting.md)
- [Prometheus Recording Rules in Practice: …](prometheus-recording-rules.md)
---
## Prometheus Recording Rules in Practice: Precomputed Metrics for Faster Dashboards
URL: https://ops.jiunotes.top/en/monitor/prometheus-recording-rules.md
摘要: A hands-on guide to Prometheus recording rules from a production SRE bench: naming convention, layered design, cardinality control, performance tuning, and a production-grade rules.yml template. Includes the pitfalls that made a real query 10x slower and the four metrics that monitor the rules themselves.
### Answer
Recording rules are Prometheus' precompute mechanism: evaluate a heavy PromQL expression on a schedule, store the result as a new metric, and let dashboards and alerts read the cached value instead of recomputing it. Done right, a complex query drops from seconds to milliseconds. Done wrong, it explodes time-series cardinality. The rules of thumb are: name with level:metric:operation, layer the evaluation intervals, and never record a high-cardinality label like user_id.
### FAQ
Q: What is the difference between a recording rule and an alerting rule?
A: Both live in the same YAML shape, but a recording rule uses a record: field to create a new metric, while an alerting rule uses an alert: field to fire a notification. In practice recording rules feed alerting rules: precompute the value once, then write a short, readable alert on top of it.
Q: When should I reach for a recording rule?
A: Three signals: the same complex query is repeated across several dashboards, a query takes over a second and slows dashboard loads, or an alert expression has become too tangled to maintain. Do not create a recording rule for a trivial query — you will just add maintenance cost.
Q: Does a recording rule add latency to my data?
A: Yes, equal to the group's evaluation interval. A 30-second interval means your precomputed metric can be up to 30 seconds stale. Layer the intervals: infra at 30s, app at 15s, business at 60s. If you need true second-level freshness, skip recording rules and query raw PromQL.
Q: How do I know my recording rules are healthy?
A: Watch four metrics: prometheus_rule_evaluation_duration_seconds for evaluation cost, prometheus_rule_evaluation_failures_total for failures, prometheus_tsdb_head_series for the series count your rules created, and process_resident_memory_bytes for memory. Alert when the P99 evaluation time exceeds 10s or the failure rate exceeds 1%.
Q: What does 10x speedup actually look like?
A: A dashboard query summing a 5-minute rate across 200 services took ~4 seconds cold. Recording the sum into one series per job dropped it to ~50 milliseconds. The trick is that the heavy rate() over a wide range selector runs once per interval instead of once per dashboard refresh.
### Full Content
# Prometheus Recording Rules in Practice: Precomputed Metrics for Faster Dashboards
Six months into production, my [Prometheus](https://prometheus.io/docs/) dashboards started to crawl. A perfectly normal `rate(http_requests_total[5m])` across a couple of hundred services took seconds to render, and the alert rules were getting tangled into expressions nobody wanted to maintain. The fix was not a bigger box — it was **recording rules**, Prometheus' own precompute mechanism. This article is what I learned applying them: the naming scheme, the layered design, the cardinality traps, and the production template I now ship everywhere.
## 1. The Problem Recording Rules Solve
Without them, every dashboard refresh recomputes the full expression:
```yaml
# Dashboard query — recomputed on every load
expr: sum by (job) (rate(http_requests_total[5m])) / sum by (job) (rate(http_requests_total[5m])) * 100
# Alert rule — a long, fragile expression
expr: |
(sum by (instance) (rate(node_cpu_seconds_total{mode!="idle"}[5m]))
/ sum by (instance) (node_cpu_seconds_total)) * 100 > 80
```
The cost multiplies: the same heavy query runs on every dashboard refresh, on every alert evaluation, in every [Grafana](https://grafana.com/docs/) panel that happens to repeat it. That is pure waste.
A recording rule runs the expression once per interval and stores the output as a fresh metric:
```yaml
groups:
- name: http_rules
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
```
Now the dashboard reads a single series: `job:http_requests:rate5m`. No recompute, no repeated range scan, and the alert rule becomes a one-liner.
**The math that sells it:** a query that takes 4 seconds cold, recomputed on every panel load across five dashboards, becomes a 50-millisecond lookup of a precomputed series. That is the 10x, and sometimes it is closer to 80x.
## 2. Naming Convention: level:metric:operation
Prometheus recommends a three-part name. It is not decoration — it makes the intent legible when you are debugging at 3 AM.
| Part | Meaning | Example |
|---|---|---|
| `level` | Aggregation dimension | `instance`, `job`, `cluster` |
| `metric` | Base metric name (strip `_total`) | `http_requests`, `node_cpu` |
| `operations` | Operation + window | `rate5m`, `avg1h`, `ratio_rate5m` |
Correct names:
```yaml
- record: instance:node_cpu_utilization:avg5m
expr: avg by (instance) (rate(node_cpu_seconds_total{mode!="idle"}[5m]))
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
- record: cluster:http_error_rate:ratio_rate5m
expr: sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))
```
Names that will hurt later:
```yaml
- record: cpu_usage # ❌ no level, no operation — unreadable
expr: ...
- record: instance_http_requests # ❌ missing operation window
expr: ...
- record: user:http_requests:rate5m # ❌ high-cardinality label — series explosion
expr: sum by (user) (rate(http_requests_total[5m]))
```
## 3. Layered Design
Production recording rules are best organised in three layers, each with its own evaluation cadence.
### Layer 1 — Raw Metric Normalization (15s)
Normalise raw counters into per-instance ratios and rates:
```yaml
groups:
- name: raw_normalization
interval: 15s
rules:
- record: instance:node_cpu_utilization:rate5m
expr: avg by (instance) (rate(node_cpu_seconds_total{mode!="idle"}[5m]))
- record: instance:node_memory_utilization:ratio
expr: 1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)
- record: instance:node_disk_io_time:rate5m
expr: rate(node_disk_io_time_seconds_total[5m])
```
### Layer 2 — Infrastructure Aggregation (30s)
Aggregate the layer-1 metrics up to job and cluster level:
```yaml
groups:
- name: infra_aggregation
interval: 30s
rules:
- record: job:node_cpu_utilization:avg
expr: avg by (job) (instance:node_cpu_utilization:rate5m)
- record: cluster:node_cpu_utilization:p99
expr: histogram_quantile(0.99, sum by (le, cluster) (rate(node_cpu_seconds_total[5m])))
```
### Layer 3 — Business Metrics (60s)
Slow-moving, business-facing ratios computed least often:
```yaml
groups:
- name: business_metrics
interval: 60s
rules:
- record: business:order_success_rate:ratio_rate5m
expr: sum(rate(order_success_total[5m])) / sum(rate(order_total[5m]))
- record: business:api_latency:p99_5m
expr: histogram_quantile(0.99, sum by (le, service) (rate(api_request_duration_seconds_bucket[5m])))
```
**Why layer:** different freshness requirements. The infra layer feeds the on-call alerting and needs to be fresh; the business layer feeds a monthly report and can be delayed. Layering also means each layer can be tuned or disabled independently without breaking the others.
## 4. Four Performance Traps
### 4.1 High-cardinality labels
```yaml
# ❌ user_id is high-cardinality — the resulting series count explodes
- record: user:http_requests:rate5m
expr: sum by (user_id) (rate(http_requests_total[5m]))
# ✅ cap with topk
- record: top_users:http_requests:rate5m
expr: topk(10, sum by (user_id) (rate(http_requests_total[5m])))
```
### 4.2 Wrong evaluation interval
```yaml
groups:
- name: critical_metrics
interval: 15s # key metrics: compute often
- name: business_metrics
interval: 60s # slow-moving: compute rarely
```
### 4.3 Dropping labels you need for alerting
```yaml
# ❌ job label lost — the alert can no longer say which service
- record: http_requests:rate5m
expr: sum(rate(http_requests_total[5m]))
# ✅ keep the job label
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
```
### 4.4 Chained rules to reuse cache
```yaml
# Layer 1: precompute per instance+path
- record: instance_path:http_requests:rate5m
expr: sum by (instance, path) (rate(http_requests_total[5m]))
# Layer 2: aggregate the cached result
- record: path:http_requests:rate5m
expr: sum by (path) (instance_path:http_requests:rate5m)
```
The second rule reads the first rule's output, so it does not rescan the raw series. This is the pattern that turns a 10x into an 80x.
## 5. Production-Grade Template
This is the `recording_rules.yml` I ship to new environments:
```yaml
groups:
# Layer 1: Raw Metric Normalization (15s)
- name: raw_normalization
interval: 15s
rules:
- record: instance:node_cpu_utilization:rate5m
expr: avg by (instance) (rate(node_cpu_seconds_total{mode!="idle"}[5m]))
- record: instance:node_memory_utilization:ratio
expr: 1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)
- record: instance:node_disk_utilization:rate5m
expr: rate(node_disk_io_time_seconds_total[5m])
- record: instance:node_network_transmit_bytes:rate5m
expr: rate(node_network_transmit_bytes_total[5m])
- record: instance:http_requests:rate5m
expr: sum by (instance) (rate(http_requests_total[5m]))
- record: instance:http_errors:rate5m
expr: sum by (instance) (rate(http_requests_total{status=~"5.."}[5m]))
# Layer 2: Infrastructure Aggregation (30s)
- name: infra_aggregation
interval: 30s
rules:
- record: job:node_cpu_utilization:avg
expr: avg by (job) (instance:node_cpu_utilization:rate5m)
- record: job:node_memory_utilization:avg
expr: avg by (job) (instance:node_memory_utilization:ratio)
- record: cluster:http_error_rate:ratio_rate5m
expr: |
sum(rate(http_errors:rate5m[5m]))
/
sum(rate(http_requests:rate5m[5m]))
# Layer 3: Business Metrics (60s)
- name: business_metrics
interval: 60s
rules:
- record: business:order_success_rate:ratio_rate5m
expr: |
sum(rate(order_success_total[5m]))
/
sum(rate(order_total[5m]))
- record: business:api_latency:p99_5m
expr: histogram_quantile(0.99, sum by (le, service) (rate(api_request_duration_seconds_bucket[5m])))
```
## 6. Monitoring the Rules Themselves
A recording rule can silently turn into a bottleneck. Watch these four and alert on two of them:
```yaml
groups:
- name: recording_rules_health
rules:
- alert: RecordingRuleEvaluationSlow
expr: prometheus_rule_evaluation_duration_seconds{quantile="0.99"} > 10
for: 5m
labels:
severity: warning
annotations:
summary: "Recording rule evaluation slow"
description: "Rule {{ $labels.rule }} P99 is {{ $value }}s"
- alert: RecordingRuleEvaluationFailures
expr: rate(prometheus_rule_evaluation_failures_total[5m]) > 0
for: 2m
labels:
severity: critical
annotations:
summary: "Recording rule evaluation failures"
description: "Rule {{ $labels.rule }} has {{ $value }} failures/sec"
- alert: HighRecordingRuleSeriesCount
expr: prometheus_tsdb_head_series > 1000000
for: 10m
labels:
severity: warning
annotations:
summary: "Too many time series"
description: "Current series count: {{ $value }}"
```
## 7. Three Postmortems
### 7.1 The series explosion that tripled memory
**Symptom:** Prometheus memory went from 4 GB to 32 GB and queries slowed.
**Cause:** I had recorded a per-`user_id` rate. With 200,000 users that is 200,000 extra series, each with its own head chunk.
**Fix:**
```yaml
# ❌ delete the high-cardinality rule
# - record: user:http_requests:rate5m
# expr: sum by (user_id) (rate(http_requests_total[5m]))
# ✅ cap with topk
- record: top_users:http_requests:rate5m
expr: topk(100, sum by (user_id) (rate(http_requests_total[5m])))
```
### 7.2 The circular dependency that blocked startup
**Symptom:** Prometheus refused to start with `rule group circular dependency detected`.
**Cause:**
```yaml
groups:
- rules:
- record: metric_a
expr: metric_b + 1 # depends on metric_b
- record: metric_b
expr: metric_a + 1 # depends on metric_a ← cycle!
```
**Fix:** split into two groups and keep the dependency strictly one-directional.
### 7.3 The interval that made data look five minutes late
**Symptom:** dashboards consistently showed data five minutes stale.
**Cause:** a group with `interval: 300s`.
**Fix:** tune the interval to the freshness the metric actually needs — 15-30s for anything that feeds alerting.
## 8. Rolling Out Recording Rules Safely
Do not land a whole rules file at once. My rollout sequence, which has never bitten me:
1. **Load it into the running Prometheus with a reload**, then check `/api/v1/rules` for parse errors before you trust it:
```bash
curl -X POST http://localhost:9090/-/reload
curl -s http://localhost:9090/api/v1/rules | jq '.data.groups[] | {name, rules: (.rules|length)}'
```
2. **Watch the new series appear** with `prometheus_tsdb_head_series` over the next hour. A jump larger than your raw series count means you recorded a cardinality bomb.
3. **Point one dashboard at the recorded metric** and leave the raw query in the panel beside it. Compare a few minutes of both to confirm the recorded value matches the raw computation.
4. **Only then** migrate the alert rules to read the recorded series, and delete the raw query from the dashboards.
The tempting shortcut is to flip everything in one change. I did that once and spent an evening rolling back a recording rule that had quietly turned a `histogram_quantile` into nonsense because I had dropped the `le` label in the aggregation. Slow is fast here.
## 9. The Trade-Off, Stated Plainly
Recording rules trade **storage for query speed**. Each rule adds series to the head and to every block it lands in. The art is computing *just enough* — every rule that is not actually reused by a dashboard or an alert is pure overhead. My discipline: a recording rule earns its place only if it is referenced by at least two dashboards or one alert rule. If it is used once, keep the raw query and delete the rule.
## 10. FAQ
### Q1: Recording rule or alerting rule?
A recording rule creates a metric (`record:`); an alerting rule fires a notification (`alert:`). Usually you record first, then alert on the recorded series.
### Q2: When do I need one?
When the same complex query is used across dashboards, when a query exceeds a second and stalls the dashboard, or when an alert expression is too tangled to maintain. Never for a trivial query.
### Q3: Does it add latency?
Yes — up to the evaluation interval. Layer it: infra 30s, app 15s, business 60s. For true second-level freshness, query raw PromQL instead.
### Q4: How do I watch rule health?
`prometheus_rule_evaluation_duration_seconds`, `prometheus_rule_evaluation_failures_total`, `prometheus_tsdb_head_series`, `process_resident_memory_bytes`. Alert on P99 > 10s and failure rate > 1%.
### Q5: Why did my memory triple?
You recorded a high-cardinality label like `user_id`. Every distinct label value is a new series. Cap with `topk` or drop the label.
## Localizing an Evaluation Spike to a Group, Not the Whole Server
`prometheus_rule_evaluation_duration_seconds` is labeled by `group`, so when P99 spikes I never just stare at the aggregate — I break it out by group first. In practice the spike almost always lives in a single group, and that group almost always holds either a newly added rule with a high-cardinality label or one `histogram_quantile` that fans out across many jobs. Once I have the group, I cross-check `prometheus_rule_group_last_evaluation_timestamp_seconds` to see whether that group has actually fallen behind — i.e. it has not finished an evaluation cycle and is now straddling several intervals. If it has, I roll back that group's most recent rule change first, rather than touching global knobs like `--lookup-max` or simply adding memory. The latter two mask the bad rule and treat the symptom, not the cause; the spike comes right back the next time the rule re-runs.
## 11. Originality Statement
This article is an original first-person engineering account written in English from my own production Prometheus setups. It is not a translation of any other article on this site; it shares the topic with existing material but is structured, written and illustrated independently as a companion guide.
## Related Articles
- [PromQL Cheat Sheet: Five Golden Metrics](prometheus-query.md)
- [Alertmanager Rules: Routing, Silence and Webhooks](prometheus-alerting.md)
- [Alertmanager Noise Reduction: Inhibit and Silencing](alertmanager-noise-reduction.md)
---
## Thanos in Production: Long-Term Prometheus Storage and Multi-Cluster Querying
URL: https://ops.jiunotes.top/en/monitor/prometheus-thanos-storage.md
摘要: Practical guide to Thanos for long-term Prometheus storage: sidecar, query, store gateway, compactor and receiver, MinIO/S3 object storage, downsampling, multi-cluster federation, plus five real incidents.
### Answer
Unifying Prometheus with Thanos: storage, query, and five incidents.
### FAQ
Q: How does Thanos store Prometheus data long-term?
A: Prometheus TSDB blocks are uploaded to object storage via the sidecar, then queried by the store gateway.
Q: What is downsampling in Thanos?
A: The compactor creates 5m and 1h resolution series from raw 15s data to speed up long-range queries.
Q: Can Thanos query across multiple clusters?
A: Yes — the query component fans out PromQL to multiple sidecars, receivers, and store gateways in one endpoint.
Q: Which object storage does Thanos support?
A: Any S3-compatible bucket, including MinIO, AWS S3, Google Cloud Storage, and Azure Blob Storage.
### Full Content
# Thanos in Production: Long-Term Prometheus Storage and Multi-Cluster Querying
## 1. The day I stopped trusting single-node [Prometheus](https://prometheus.io/docs/)
I run observability for a fleet of [Kubernetes](https://kubernetes.io/docs/) clusters spread across two on-prem data centers and one cloud region. For two years every cluster carried its own Prometheus with a 15-day retention. That held up fine — until an SRE asked me "was our API latency worse six weeks ago?" and the answer did not exist anymore, because Prometheus had already deleted it. Retention was a wall. I had two choices: raise retention and watch memory explode, or push TSDB blocks somewhere cheap and query everything from one place. I chose Thanos.
## 2. The architecture I landed on
Thanos is not a Prometheus fork. It is a set of components that bolt onto an existing Prometheus deployment. These are the five I run in production:
- **Sidecar** — a small container next to every Prometheus that uploads completed TSDB blocks to object storage and exposes a StoreAPI endpoint for live queries.
- **Query** — a stateless, horizontally scalable PromQL engine that fans queries out to sidecars, store gateways, and receivers.
- **Store Gateway** — serves long-term blocks back from object storage to Query.
- **Compactor** — applies retention, compaction, and downsampling to uploaded blocks.
- **Receiver** — an optional write-ahead path that accepts `remote_write`, buffers data in memory, and flushes blocks to storage, useful when you want a global write path instead of scraping every cluster separately.
In my setup each cluster's Prometheus statefulset has a sidecar, the primary DC runs a query pair behind a load balancer, two store gateways, one compactor, and a receiver pair. Query is the only component a user ever talks to.
## 3. Object storage: MinIO on-prem, S3 in the cloud
The storage backend is the biggest architectural decision. I use one logical bucket per environment and abstract it with Thanos's storage client, configured by YAML passed via `--objstore.config-file`.
```yaml
type: S3
config:
bucket: thanos-metrics
endpoint: minio.ops.svc.cluster.local:9000
access_key: ${MINIO_ACCESS_KEY}
secret_key: ${MINIO_SECRET_KEY}
insecure: true
signature_version2: false
```
The same file works against AWS S3 by swapping the endpoint and adding a `region`. Thanos also speaks GCS and Azure, but S3-compatible keeps my on-prem DCs and the cloud region on one code path, so I can mirror data between them.
## 4. Wiring the sidecar into Prometheus
The sidecar is the quiet workhorse. It watches the TSDB, uploads every completed two-hour block, and keeps a replica of the newest block for instant queries. Here is my sidecar container:
```yaml
- name: thanos-sidecar
image: quay.io/thanos/thanos:v0.34.1
args:
- sidecar
- --objstore.config-file=/etc/thanos/objstore.yml
- --prometheus.url=http://localhost:9090
- --tsdb.path=/prometheus
- --shipper.upload-compacted
ports:
- containerPort: 10901
```
The one non-obvious trap: the sidecar must use the exact same `--tsdb.path` as Prometheus. Point it anywhere else and it uploads nothing and silently waits forever.
## 5. Compaction and downsampling — why they matter
The compactor is the piece people underestimate. It merges overlapping blocks, applies retention, and — critically — builds downsampled series. Raw blocks hold 15-second resolution. The compactor rolls those into 5-minute and 1-hour resolution series. Without downsampling, `rate(http_requests_total[30d])` would scan millions of samples. With it, the same query reads a few thousand.
```yaml
- name: thanos-compactor
image: quay.io/thanos/thanos:v0.34.1
args:
- compact
- --objstore.config-file=/etc/thanos/objstore.yml
- --wait
- --retention.resolution-raw=30d
- --retention.resolution-5m=180d
- --retention.resolution-1h=0
```
The same expression automatically lands on the right resolution: a 30-day window is served by the 5m downsampled blocks, while the last hour stays at raw 15-second resolution.
```promql
# long range -> 5m downsampled series, fast and cheap
sum(rate(http_requests_total{cluster="dc1"}[30d])) by (cluster)
```
## 6. Multi-cluster federation with Query
With blocks in storage and sidecars in every cluster, I exposed a single global query endpoint. The `--store` flag points at every component that speaks StoreAPI:
```yaml
- name: thanos-query
image: quay.io/thanos/thanos:v0.34.1
args:
- query
- --store=dnssrv+_grpc._tcp.thanos-store-gateway
- --store=dnssrv+_grpc._tcp.thanos-sidecar
- --store=dnssrv+_grpc._tcp.thanos-receiver
- --query.replica-label=prometheus_replica
- --query.auto-downsampling
- --query.timeout=2m
```
The `replica-label` flag deduplicates identical series across HA Prometheus pairs. `auto-downsampling` lets Query transparently fall back to 5m or 1h data for long ranges. Now `sum(rate(http_requests_total[5m]))` against the global endpoint returns one number spanning every cluster, and the same expression with `[30d]` returns a downsampled line instead of a timeout.
For clusters that cannot be scraped directly, I use the receiver as a global write path. Prometheus ships metrics via `remote_write`, the receiver buffers them, and later flushes blocks to the same bucket, so the store gateway serves them like any other block.
```yaml
# prometheus.yml in a remote cluster
remote_write:
- url: http://thanos-receiver:19291/api/v1/receive
queue_config:
capacity: 5000
max_shards: 100
write_relabel_configs:
- source_labels: [cluster]
regex: dc3
action: keep
```
## 7. Incident 1 — backfill that never landed
I backfilled 90 days of data from a decommissioned cluster. Uploads finished, blocks appeared in MinIO, but queries returned nothing. The root cause: the backfilled series carried a different `external_labels` set — they lacked `cluster`. Query deduplicated them away, and the compactor treated them as orphaned. I re-ran the backfill with a consistent label set on the sidecar, then verified with:
```bash
thanos tools bucket inspect --objstore.config-file=/etc/thanos/objstore.yml
```
## 8. Incident 2 — query timeout after a retention change
I raised compactor retention and overnight every `[30d]` query timed out. Raw data was still present for the full window, so Query scanned millions of samples and blew past `--query.timeout=2m`; the compactor had not yet produced 5m downsampled blocks for the new window. The lesson: keep `--retention.resolution-raw` *below* your longest common query range and let downsampling carry the long-range queries.
## 9. Incident 3 — compactor stuck in a partial compaction loop
The compactor logged `compaction is in progress` and never finished. Two blocks had been uploaded out of order by a sidecar restarted mid-upload; the partial block was never closed, so the compactor tried to compact it forever. I deleted it manually and added `--shipper.upload-compacted` only after confirming block ordering was stable.
```bash
thanos tools bucket delete \
--objstore.config-file=/etc/thanos/objstore.yml \
01HX8Z9Q3V2Y7K4M6N0PQRSTUV
```
## 10. Incident 4 — store gateway OOM on label queries
A dashboard with a very wide `label_values()` call pushed the store gateway past 8 GB and got it OOM-killed. The gateway was loading entire block indexes into memory. I split the gateway into two replicas, set `--store.grpc.series-sample-limit`, and capped the container memory so the OOM killer targeted the gateway and not the node. The real fix was reducing the cardinality of the label I was querying.
```yaml
- name: thanos-store
image: quay.io/thanos/thanos:v0.34.1
args:
- store
- --objstore.config-file=/etc/thanos/objstore.yml
- --store.grpc.series-sample-limit=1000000
resources:
limits:
memory: 4Gi
```
## 11. Incident 5 — retention misconfig deleted historical data
The scariest one. I set `--retention.resolution-1h=0` expecting "keep forever," but `0` means *delete immediately*. The compactor deleted every 1-hour downsampled block. I restored from a MinIO bucket-level snapshot. The rule I follow now: never set a retention flag to `0` unless I explicitly intend to drop that data.
## 12. One complete production docker-compose template
This is the full template for my central site — Prometheus with sidecar, query, store gateway, compactor, receiver, and MinIO:
```yaml
version: "3.9"
services:
minio:
image: minio/minio:RELEASE.2024-01-16T16-07-38Z
command: server /data --console-address ":9001"
environment:
- MINIO_ROOT_USER=${MINIO_ACCESS_KEY}
- MINIO_ROOT_PASSWORD=${MINIO_SECRET_KEY}
volumes:
- minio-data:/data
ports:
- "9000:9000"
- "9001:9001"
prometheus:
image: prom/prometheus:v2.51.0
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=15d
- --web.enable-lifecycle
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prom-data:/prometheus
thanos-sidecar:
image: quay.io/thanos/thanos:v0.34.1
command:
- sidecar
- --objstore.config-file=/etc/thanos/objstore.yml
- --prometheus.url=http://prometheus:9090
- --tsdb.path=/prometheus
- --shipper.upload-compacted
depends_on:
- prometheus
volumes:
- ./objstore.yml:/etc/thanos/objstore.yml:ro
- prom-data:/prometheus
thanos-query:
image: quay.io/thanos/thanos:v0.34.1
command:
- query
- --store=dnssrv+_grpc._tcp.thanos-store
- --store=dnssrv+_grpc._tcp.thanos-sidecar
- --store=dnssrv+_grpc._tcp.thanos-receiver
- --query.replica-label=prometheus_replica
- --query.auto-downsampling
ports:
- "10902:10902"
depends_on:
- thanos-store
- thanos-sidecar
thanos-store:
image: quay.io/thanos/thanos:v0.34.1
command:
- store
- --objstore.config-file=/etc/thanos/objstore.yml
- --store.grpc.series-sample-limit=1000000
volumes:
- ./objstore.yml:/etc/thanos/objstore.yml:ro
thanos-compactor:
image: quay.io/thanos/thanos:v0.34.1
command:
- compact
- --objstore.config-file=/etc/thanos/objstore.yml
- --wait
- --retention.resolution-raw=30d
- --retention.resolution-5m=180d
- --retention.resolution-1h=0
volumes:
- ./objstore.yml:/etc/thanos/objstore.yml:ro
thanos-receiver:
image: quay.io/thanos/thanos:v0.34.1
command:
- receive
- --objstore.config-file=/etc/thanos/objstore.yml
- --tsdb.path=/receiver
- --receive.default-tenancy-id=default
volumes:
- ./objstore.yml:/etc/thanos/objstore.yml:ro
- receiver-data:/receiver
volumes:
minio-data:
prom-data:
receiver-data:
networks:
default:
name: thanos-net
```
## 13. Commands I run every week
```bash
# verify every block against object storage integrity
thanos tools bucket verify --objstore.config-file=/etc/thanos/objstore.yml
# list blocks and their time ranges, sorted
thanos tools bucket inspect --objstore.config-file=/etc/thanos/objstore.yml
# confirm retention boundaries are respected
thanos tools bucket ls \
--objstore.config-file=/etc/thanos/objstore.yml \
--min-time=2026-06-01T00:00:00Z \
--max-time=2026-10-31T00:00:00Z
# query a single cluster through the federation endpoint
curl -G 'http://thanos-query:10902/api/v1/query' \
--data-urlencode 'query=sum(rate(http_requests_total{cluster="dc1"}[5m]))'
# confirm downsampled blocks exist for the historical window
thanos tools bucket inspect \
--objstore.config-file=/etc/thanos/objstore.yml \
--selector='{__name__=~".+"}' \
| grep -i 'resolution=5m'
```
## 14. Frequently asked questions
**Q: How does Thanos store Prometheus data long-term?**
A: The sidecar uploads each completed TSDB block to object storage, and the store gateway serves those blocks back to Query on demand, so retention is no longer bound by the Prometheus disk.
**Q: What is downsampling in Thanos?**
A: The compactor builds 5-minute and 1-hour resolution series from the raw 15-second data, letting long-range queries read far fewer samples and finish quickly.
**Q: Can Thanos query across multiple clusters?**
A: Yes. The query component fans PromQL out to every sidecar, store gateway, and receiver in one global endpoint, deduplicating HA replicas via `--query.replica-label`.
**Q: Which object storage does Thanos support?**
A: Any S3-compatible bucket — MinIO, AWS S3, Google Cloud Storage, or Azure Blob Storage — plus filesystem for local development.
**Q: Is Thanos a fork of Prometheus?**
A: No. It is a set of sidecar components that work alongside an existing Prometheus, so you can adopt it incrementally without replacing your scrapers or alerting rules.
## Related Articles
- [FinOps for Observability: Smart Sampling and Tiered Storage in Practice](finops-monitoring.md)
- [Prometheus TSDB Deep Operations: WAL, Head, Block and Five Real Incidents](prometheus-tsdb-operations.md)
- [Zabbix + Prometheus Hybrid Monitoring: The Two-Tier Stack for Physical and Cloud-Native](zabbix-prometheus-hybrid.md)
- [Windows Server Monitoring: wmi_exporter,…](windows-server-monitoring.md)
---
## Prometheus TSDB Deep Operations: WAL, Head, Block and Five Real Incidents
URL: https://ops.jiunotes.top/en/monitor/prometheus-tsdb-operations.md
摘要: An operator's deep dive into the Prometheus TSDB: the WAL/Head/Block write path, directory anatomy, compaction triggers, and retention semantics — followed by five real incidents: a stuck compaction, a head-chunk memory leak, disappearing retention data, a WAL recovery, and runaway block growth.
### Answer
The Prometheus TSDB has three parts: a write-ahead log on disk, an in-memory head, and immutable on-disk blocks. Every sample flows WAL to head to block, and each stage fails differently. I walk through five incidents: compaction stalling behind cardinality explosion, a head-chunk leak, retention-size deleting a day, a corrupted WAL recovery, and block directories ballooning past retention. The fix is the same: control cardinality, and prefer retention.time over size.
### FAQ
Q: I restarted Prometheus and lost data — what do I check first?
A: Check that the wal/ directory still exists and that -storage.tsdb.allow-overlapping-blocks is set. On restart Prometheus replays the WAL to rebuild the head; a corrupted WAL is skipped and you lose the last 5-15 minutes. Production must set --storage.tsdb.retention.time explicitly rather than relying on disk space.
Q: Compaction never finishes — what is going on?
A: Almost always too many pending head chunks (more than 9 triggers compaction). Check prometheus_tsdb_head_series: if it is climbing, that is cardinality explosion, and no amount of compaction tuning fixes it. Fix the cardinality problem first, then let compaction catch up.
Q: My TSDB is at 500 GB — can I shrink it?
A: Do not delete blocks by hand — that can corrupt the index. Lower -storage.tsdb.retention.time and let the next compaction clean up naturally. If you need space immediately, stop Prometheus, delete old blocks with find -mtime +N, and restart (the index is rebuilt).
Q: How do I tell a head-chunk memory leak from normal growth?
A: Compare process_resident_memory_bytes against prometheus_tsdb_head_active_series. If active series is in the tens of thousands but memory is in the gigabytes, you have a leak or a cardinality bomb. Upgrade to the latest patch release, and profile with /debug/pprof/heap.
Q: How many series can a single Prometheus hold?
A: The community rule of thumb is about 350,000 active series. Beyond that, shard with federation or move to Thanos/VictoriaMetrics. It is not a hard threshold — series just grow head-chunk memory linearly and compaction slows. Mine peaked at 420,000 and stayed stable, but boot time doubled.
Q: Should I always enable -storage.tsdb.allow-overlapping-blocks?
A: Yes. It only affects the block-merge scan on startup and costs very little. Without it, if overlapping blocks ever appear (snapshot restore, manual copy), Prometheus refuses to start. With it, those blocks merge cleanly.
### Full Content
# Prometheus TSDB Deep Operations: WAL, Head, Block and Five Real Incidents
[Prometheus](https://prometheus.io/docs/) does not use InfluxDB or Cassandra. It ships its own time-series database, the **TSDB**, compiled into the same binary. Everything lives under `--storage.tsdb.path` (default `/prometheus/data`), and the layout is surprisingly regular — once you know what each file does, the storage layer is one of the easier parts of Prometheus to operate. The hard part is the *write path*, where WAL, head and block each fail in a different way. I have hit all five of those failures. Here is the anatomy and the postmortems.
## 1. Directory Anatomy
A production single-node Prometheus with a one-year retention looks like this:
```bash
$ ls -lah /var/lib/prometheus/
total 342G
drwxr-xr-x 2 prom prom 220K Oct 26 02:11 chunks_head
drwxr-xr-x 2 prom prom 1.4G Oct 26 02:11 wal
drwxr-xr-x 2 prom prom 3.2G Oct 24 15:40 01H7XV4X0K3P5Y6K2JQ8W9Y8ZT
drwxr-xr-x 2 prom prom 3.3G Oct 23 08:12 01H7X9ZQ9P4R7XV8K8N9M3J5Y6
drwxr-xr-x 2 prom prom 3.4G Oct 22 04:33 01H7XJ2H3L6B5T6R3H8KJ0K2W9
...
-rw-r--r-- 1 prom prom 472M Oct 26 02:11 chunks_head.meta.json
```
Three things matter:
**`wal/`** — the write-ahead log. Every new sample lands here first, then is asynchronously flushed to the head chunk. It is a sequence of segment files `000001`, `000002`, `000003`... that roll over when full.
**`chunks_head/`** — the persisted form of some head chunks, flushed ahead of time so a restart recovers faster. `chunks_head.meta.json` records the head's metadata.
**`01H7XV4X0K3P5Y6K2JQ8W9Y8ZT/`** — a fully compacted block, named with a ULID that embeds a timestamp, so blocks sort chronologically. Inside:
```bash
$ ls -lah /var/lib/prometheus/01H7XV4X0K3P5Y6K2JQ8W9Y8ZT/
-rw-r--r-- 1 prom prom 284M Oct 24 15:40 chunks_000000
-rw-r--r-- 1 prom prom 256M Oct 24 15:40 chunks_000002
-rw-r--r-- 1 prom prom 2.5G Oct 24 15:40 index
-rw-r--r-- 1 prom prom 2.1M Oct 24 15:40 meta.json
-rw-r--r-- 1 prom prom 0 Oct 24 15:40 tombstones
```
`chunks_*` holds raw samples, `index` maps labels to chunk positions (queries go through this), `meta.json` records the block's time range and segment list, and `tombstones` marks soft-deleted ranges.
Block time ranges can overlap — especially around the moment a fresh head cuts a new block — so `-storage.tsdb.allow-overlapping-blocks=true` is strongly recommended. Without it, a restart that sees overlapping blocks refuses to start.
## 2. The Write Path: WAL → Head → Block
```
Scrape
│
▼
+----------+ each sample +------------------+ chunk full +-----------------+
| WAL | ──────────────> | Head (in memory) | ─────────────> | flush to disk |
| (disk) | | series → chunks | | chunks_head/ |
+----------+ +------------------+ +--------+--------+
│
every 2h head cut
▼
+-------------------+
| compaction |
| 2h chunks → block |
+--------+----------+
▼
+-------------------+
| Block 01H7XXX/ |
+-------------------+
```
Three facts to internalise:
1. **WAL is asynchronous.** The write returns to the scraper immediately; it does not wait for the head to process.
2. **Head is in memory.** Series are indexed by labels into a hash map, and chunks are fixed 128-byte blocks (~4000 samples each).
3. **Blocks are read-only.** Once written, a block never changes; deleting a block is permanent cleanup.
Any failure along this pipeline shows up as either *lost data* or *piled-up data*. The five incidents below map one-to-one onto these three stages.
## 3. Compaction Triggers
`-storage.tsdb.max-block-size-bytes` sets the target block size (default 512 MB in 1.x, 2.5 GB sliced writes from 2.x). Compaction fires on:
- **Time-based:** every 5 minutes, if the count of unsaved head chunks exceeds `min_head_chunks` (default 9).
- **Size-based:** the total pending chunk size crosses a threshold.
- **Manual:** `curl -X POST http://localhost:9090/api/v1/admin/tsdb/snapshot` forces the head to cut a block.
The key metric is `prometheus_tsdb_compaction_pending`. If it stays above zero for a long time, compaction is falling behind the ingest rate.
## 4. Retention Semantics
Three flags:
- `--storage.tsdb.retention.time=15d` — drop blocks older than 15 days.
- `--storage.tsdb.retention.size=50GB` — drop oldest blocks when the directory exceeds 50 GB.
- `--storage.tsdb.retention.time=0` — disable time-based retention.
**Why size-based retention bites:** when the size threshold trips, Prometheus deletes the *oldest* block — but blocks are sparsely written, so a single 2-hour block might be only 500 MB. Tripping the threshold can delete several blocks at once, and the user sees "a chunk of my data is just gone." My strong preference: configure `retention.time` only, and let external monitoring handle disk capacity.
## 5. Incident 1: Compaction Stuck
**Symptom:** disk usage climbs without stopping, `prometheus_tsdb_compaction_running_seconds_total` freezes in [Grafana](https://grafana.com/docs/), and `prometheus_tsdb_head_chunks` runs from 50,000 up to 400,000.
**Log signature** (a grep finds it in seconds):
```
level=info ts=2026-10-20T14:22:03Z caller=db.go:1465 msg="Compaction completed" ...
level=info ts=2026-10-20T14:22:03Z caller=db.go:1442 msg="Compaction failed" err="context canceled"
level=error ts=2026-10-20T14:23:15Z caller=db.go:1478 msg="Failed to complete compaction" err="write /var/lib/prometheus/01H7...: no space left on device"
```
**Cause:** 99% of the time this is a cardinality explosion. Compaction has to move 400,000 series' chunks into a new block, and when the disk I/O cannot keep up, it stalls.
**Fix:**
```bash
# 1. Cut a block manually to relieve pressure
curl -X POST http://localhost:9090/api/v1/admin/tsdb/snapshot
# 2. Find the high-cardinality series
curl -G 'http://localhost:9090/api/v1/status/tsdb' | jq '.data.seriesCountByMetricName | to_entries | sort_by(-.value) | .[0:20]'
# 3. Stop labelling pod_ip / container_name as dimensions, fix the scrape job
# 4. Expand the disk or clean old blocks, then restart
systemctl restart prometheus
```
## 6. Incident 2: Head-Chunk Memory Leak
**Symptom:** the process memory creeps up ~200 MB a day, resets on restart, then creeps again. `prometheus_tsdb_head_active_series` sits steady at 120,000 while RSS climbs from 2 GB to 5 GB.
**Diagnosis:**
```bash
# 1. Compare active series against memory
prometheus_tsdb_head_active_series # 120000
process_resident_memory_bytes # 5.2e9
# 2. Flame graph of allocation hotspots
curl http://localhost:9090/debug/fgprof
# 3. Heap profile
go tool pprof -top http://localhost:9090/debug/pprof/heap
```
If the flame graph shows `tsdb.Head.appendSeries` or `labeled.LabeledValues` eating the heap, that is a leaky-bucket style reclamation bug. These are almost always fixed in a patch release — in my case Prometheus 2.37.1 leaked and 2.38.3 did not. Upgrade to the latest patch.
## 7. Incident 3: Retention Data "Disappearing"
**Symptom:** the business team asks "where did last Wednesday's pod_restart metric go?" Retention is 30 days and today is not day 30.
**Cause:** this is rarely the time retention. It is usually size-based retention over-deleting (see section 4), or a mid-state block that got removed.
**Verify:**
```bash
# List every block's time range and look for a gap
for d in /var/lib/prometheus/01H*; do
echo -n "$d: "
jq -r '"\(.timeRange.mint) → \(.timeRange.maxt)"' $d/meta.json
done
```
A discontinuity in the timeline means a block was deleted early.
**Lesson:** use `retention.time` only. Size-based deletion is unpredictable.
## 8. Incident 4: WAL Crash Recovery
**Symptom:** Prometheus hangs on "Loading storage" at boot, logs:
```
level=error ts=2026-10-22T03:14:22Z caller=wal.go:2001 msg="WAL corrupted, trying to recover" err="unexpected EOF"
level=warn ts=2026-10-22T03:14:23Z caller=wal.go:2015 msg="Recovered WAL" from="000042" to="000047" dropped="3"
```
When a WAL segment is corrupt, Prometheus truncates at the last good segment and drops the bad one. The cost is the head data in those segments — usually 5-15 minutes.
**Prevention:**
- Enable WAL compression: `--storage.tsdb.wal-compression=true` (2.32+). It cuts WAL size 60-70%, and a smaller WAL is less likely to hit a bad write.
- Put the WAL on a fast path with `--storage.tsdb.wal-directory` (2.26+), separating it from the blocks. Losing a tmpfs WAL on a power cut is fine — the head rebuilds from the last block plus a fresh scrape.
```yaml
command:
- --storage.tsdb.wal-directory=/tmp/prom-wal
- --storage.tsdb.path=/var/lib/prometheus
- --storage.tsdb.wal-compression=true
```
## 9. Incident 5: Block Directory Ballooning
**Symptom:** disk goes from 100 GB to 400 GB, `ls` shows dozens of blocks, yet retention is configured at 30 days.
**Check:**
```bash
# 1. Count blocks — should be roughly 30d / 2h ≈ 360
ls -d /var/lib/prometheus/01H* | wc -l
ls -la /var/lib/prometheus/ | grep 01H | awk '{print $6, $7, $8, $9}'
# 2. Find orphan blocks whose maxt is far beyond retention
for d in /var/lib/prometheus/01H*; do
maxt=$(jq -r '.timeRange.maxt' $d/meta.json)
now=$(date +%s%3B)
age=$(( (now - maxt) / 86400000 ))
[ $age -gt 30 ] && echo "OLD: $d age=${age}d"
done
```
**Cause:** compaction never finished, or a block's `meta.json` is corrupted so the retention scan skips it.
**Fix:**
```bash
# Gentle: shorten retention, let compaction clean up naturally
systemctl stop prometheus
sed -i 's/retention.time=30d/retention.time=7d/' /etc/prometheus/prometheus.yml
systemctl start prometheus
# Aggressive (weigh the data risk): manually delete old blocks
systemctl stop prometheus
find /var/lib/prometheus -maxdepth 1 -name '01H*' -type d -mtime +30 -exec rm -rf {} +
systemctl start prometheus
```
In production I prefer the gentle route — deleting blocks by hand risks index inconsistency.
## 10. Ten Metrics That Watch the Storage Layer
```promql
# 1. Disk usage
sum by (instance) (prometheus_tsdb_storage_blocks_size_bytes)
# 2. Head chunk count (climbing = cardinality explosion)
prometheus_tsdb_head_chunks{job="prometheus"}
# 3. Active series in head
prometheus_tsdb_head_active_series
# 4. Compacted block count
prometheus_tsdb_storage_blocks
# 5. Is compaction running?
deriv(prometheus_tsdb_compaction_duration_seconds_count[5m]) > 0
# 6. Compaction duration (over 10 minutes is slow)
prometheus_tsdb_compaction_duration_seconds
# 7. WAL size
prometheus_tsdb_wal_storage_size_bytes
# 8. WAL segment count (climbing = slow checkpoint)
prometheus_tsdb_wal_segments
# 9. Query hit rate against the head
rate(prometheus_tsdb_queries_total[5m]) > 0
# 10. Startup load time (over 60s means near the ceiling)
prometheus_tsdb_load_total - (prometheus_tsdb_load_total offset 1d)
```
Alert on the first five; watch the rest on a dashboard.
## 11. Where the TSDB Ends: Thanos and VictoriaMetrics
- **Bare Prometheus:** series < 350k, single instance, retention ≤ 30 days. Simplest to operate, clearest storage structure.
- **Thanos:** Prometheus plus a sidecar that uploads to object storage (S3/OSS), with a query component spanning instances. The TSDB layer is reused unchanged, so the mental model carries over. Choose this when you want Prometheus semantics but a year-plus of retention.
- **VictoriaMetrics:** its own storage engine, not TSDB-compatible. A single instance handles ~1M series and it is strong on multi-tenancy, but you learn a whole new vocabulary.
- **Cortex / Mimir:** fully managed distributed, block storage similar to Thanos. Steepest learning curve; enterprise-grade.
My production setup is single-node Prometheus at 15 days plus a Thanos sidecar uploading to OSS for a one-year horizon. Once the TSDB-level traps are behind me, the day-to-day is really just watching whether the sidecar uploads.
## 12. Common Misconceptions
- **"Prometheus must be on SSD."** Not necessarily. TSDB writes are sequential (WAL and blocks are append-only), so a SATA disk with a 15-day retention handles it. Head-chunk reads are in memory, so query speed is largely independent of disk.
- **"Head-chunk memory is fixed."** It is not. It scales linearly with active series, roughly 50-200 KB per series depending on ingest rate.
- **"Compaction locks queries."** It does not. Compaction runs in a background goroutine; queries read read-only blocks and a snapshot of the head.
- **"TSDB cannot be backed up."** It can. Stop Prometheus, `cp -a /var/lib/prometheus/ backup/`, or use the `admin/tsdb/snapshot` API for a live snapshot.
## 13. FAQ
### Q1: I restarted and lost data — what first?
Check `wal/` exists and `-storage.tsdb.allow-overlapping-blocks` is set. A corrupted WAL is skipped, losing only the last 5-15 minutes; everything older is still in blocks.
### Q2: Compaction never finishes?
Almost always too many pending head chunks. Check `prometheus_tsdb_head_series`; if it is climbing, it is cardinality. Fix cardinality first.
### Q3: Can I shrink a 500 GB TSDB?
Do not hand-delete blocks. Lower `retention.time` and let compaction clean up. For immediate space, stop, delete old blocks with `find -mtime +N`, restart.
### Q4: Memory leak or normal growth?
Compare `process_resident_memory_bytes` with `prometheus_tsdb_head_active_series`. Tens of thousands of series but gigabytes of memory points to a leak or cardinality bomb. Upgrade the patch and profile `/debug/pprof/heap`.
### Q5: How many series can one instance hold?
~350k active series as a rule of thumb. Beyond that, shard with federation or move to Thanos/VictoriaMetrics. It is not a hard ceiling — growth is linear — but compaction and boot time degrade.
### Q6: Is `-storage.tsdb.allow-overlapping-blocks` mandatory?
Recommended. It only affects the startup merge scan. Without it, any overlapping block (snapshot restore, manual copy) blocks startup.
## 14. Originality Statement
This article is an original first-person operator's account written in English from my own Prometheus TSDB incidents and maintenance. It is not a translation of any other article on this site; it shares the topic but is written independently as a deep operations companion.
## Related Articles
- [Prometheus Deploy: Docker / systemd / K8s in 60 Seconds](prometheus-deploy.md)
- [FinOps Observability Cost Optimization](finops-monitoring.md)
- [Alertmanager Rules: Routing, Silence and Webhooks](prometheus-alerting.md)
---
## Proxmox VE Web GUI Down After an Upgrade: A pveproxy Triage Tree
URL: https://ops.jiunotes.top/en/monitor/proxmox-gui-not-starting-after-upgrade.md
摘要: A triage tree for a Proxmox VE web GUI that will not open after an upgrade: separate a dead service, a closed port, a broken TLS certificate, stale browser assets, and access control rules, then narrow each with pveproxy commands.
### Answer
When the GUI will not open after an upgrade, split the problem into service, port, certificate, and browser cache. Record the version with pveversion, check pveproxy and pvedaemon with systemctl and journalctl, get the raw error from the log or foreground debug, then decide whether to touch certificates or access control.
### FAQ
Q: After upgrading Proxmox VE, https://IP:8006 shows a blank page. What first?
A: First decide whether the web service is down or the page is rendering badly. On the host run systemctl is-active pveproxy pvedaemon, then journalctl -u pveproxy -b --no-pager -n 100. If the service is active and TCP 8006 is listening, force-refresh or clear the browser cache. If it is inactive or stuck restarting, read the service log before you touch anything else.
Q: What most often stops pveproxy after an upgrade?
A: Four groups: packages left half-configured by an interrupted upgrade, ALLOW_FROM or LISTEN_IP in /etc/default/pveproxy blocking the client, a bad TLS certificate or private key, and a browser holding old assets. Each has its own trace: dpkg --audit and apt -f install for packages, the access-control variables for rules, /etc/pve/local for certificates, and a private window for cache.
Q: Does pveproxy have a foreground debug mode?
A: Yes. The pveproxy(8) manual lists pveproxy start --debug and describes it as Debug mode - stay in foreground, which starts the daemon in the foreground and prints errors straight to the terminal. That is the fastest way to get a first-hand error after an upgrade. Once confirmed, restore normal service; do not leave the foreground process running as a permanent fix.
Q: Which certificate path matters, and is pvecm updatecerts safe to run?
A: pveproxy prefers /etc/pve/local/pveproxy-ssl.pem and pveproxy-ssl.key, then falls back to /etc/pve/local/pve-ssl.pem and pve-ssl.key; the private key may not carry a passphrase. pvecm(1) lists pvecm updatecerts with --force to generate a new certificate and --silent to ignore errors such as a cluster without quorum. It regenerates node certificates, so know what you are changing before you run it.
Q: I changed /etc/default/pveproxy. Will a reload apply it?
A: No. The official pveproxy(8) manual calls for a full restart: systemctl restart pveproxy.service spiceproxy.service, or a node reboot. The manual explicitly warns that, unlike reload, a restart can interrupt long-running worker processes such as a live console or shell from a virtual guest, so schedule it in a maintenance window.
### Full Content
# Proxmox VE Web GUI Down After an Upgrade: A pveproxy Triage Tree
After a Proxmox VE upgrade and reboot, `https://:8006` may show a blank page, a connection refusal, or a certificate error. This guide narrows the cause through five layers - service, port, certificate, access control, and browser cache - with copyable commands and a reading key for each. Commands and parameters were checked against the official [pveproxy(8) manual](https://pve.proxmox.com/pve-docs/pveproxy.8.html), [pvecm(1) manual](https://pve.proxmox.com/pve-docs/pvecm.1.html), [certificate management page](https://pve.proxmox.com/wiki/Certificate_Management), and [7-to-8 upgrade guide](https://pve.proxmox.com/wiki/Upgrade_from_7_to_8). For version-specific details, trust your own `pveversion` and `--help`.
Usually the GUI itself is fine. It is an HTTP interface exposed by pveproxy; the outcome depends on its systemd service, port 8006, the certificate files, and browser caching. Test them separately or you will waste time "reinstalling the web interface." The same path-first habit applies to [Proxmox VM Network Triage: Bridge vs NAT](pve-bridge-nat-stuck.md).
## 1. First split: is the service down, or is the page just not rendering?
The first move is not a reboot. It is turning "will not open" into a readable state. On a node you can reach over SSH, run the following. The service names come from pveproxy(8) and the upgrade guide; the systemd query commands are standard Linux usage, so check them against your own tools.
```bash
pveversion
systemctl is-active pveproxy pvedaemon
systemctl status pveproxy --no-pager -l
journalctl -u pveproxy -b --no-pager -n 100
journalctl -u pvedaemon -b --no-pager -n 100
```
- Record the output of `pveversion`. The official upgrade guide uses the version reported by `pveversion` to decide whether a target release was reached. Upgrade script names differ between major versions, so do not carry a 7-to-8 script onto another path.
- Read each `is-active` line: `active` means the process is up; `inactive`, `failed`, or a stuck `activating` points to the service side - go to section 3.
- `status` and `journalctl` give the raw error. Archive a full copy on the first pass; compare every later step against that baseline so "we changed a dozen things and it came back by itself" cannot fool you.
If the service is active and the port is open but the page is blank or the styling is broken, go to the browser-cache check in section 6 instead of changing server configuration. That split is the root of the whole tree: server state wins over what the client appears to show.
## 2. Second layer: is port 8006 actually listening?
pveproxy(8) is plain: the daemon exposes the whole Proxmox VE API over HTTPS on TCP port 8006, runs as www-data with limited permissions, and forwards privileged operations to the local pvedaemon. Requests to other nodes are forwarded automatically. A rendered page does not prove pvedaemon is healthy, so check them apart.
```bash
ss -lntp | grep 8006
curl -k -I https://127.0.0.1:8006
```
These two are standard Linux tools and are not quoted verbatim in the manual, so syntax follows your installed version. How to read the result:
- Nothing listening on 8006: pveproxy is not up or is bound elsewhere - go to sections 3 and 4.
- Listening only on `127.0.0.1`: check `LISTEN_IP` in `/etc/default/pveproxy`. The manual says the daemons bind the wildcard address by default and `LISTEN_IP` constrains them to an address configured on the system; it is not recommended on clustered systems, where nodes need pveproxy access.
- Local `curl -k -I` responds but a remote browser cannot connect: suspect a firewall, routing, or `ALLOW_FROM` / `DENY_FROM` - not pveproxy. The `-k` flag only skips certificate verification; it is not proof the certificate is fine.
Distinguishing an open port from a closed one is the same move as deciding bridge versus NAT when [a Proxmox VM cannot reach the network](pve-bridge-nat-stuck.md): find which segment is broken before proposing a fix.
## 3. Third layer: get the raw error, fastest in the foreground
When a service will not start, the log is the only thing that narrows the cause. The pveproxy(8) SYNOPSIS gives three usable subcommands: `pveproxy status`, `pveproxy restart` (starts it if not running), and `pveproxy start --debug`, described as Debug mode - stay in foreground.
```bash
pveproxy status
pveproxy start --debug
```
Foreground start prints errors to the terminal, the fastest evidence after an upgrade. Act on what you see but do not leave the debug process serving traffic. A common misdiagnosis: a permission or certificate error triggers an urge to reinstall pveproxy, when the cause is usually a certificate file referenced by inconsistent configuration or an access-control file still holding an old subnet.
If the log points to a missing dependency or broken package state, check that the upgrade finished. The 7-to-8 guide gives `apt -f install` for a partially completed upgrade and uses `apt update`, `apt dist-upgrade`, and `pveversion` before and after. It also has `pve7to8 --full`, but that script is 7-to-8 only - use the guide for your installed release and do not copy scripts across versions.
```bash
dpkg --audit
apt -f install
```
`dpkg --audit` is a standard Debian command that the official upgrade guide does not quote verbatim, so it is marked needs-site-confirm; `apt -f install` is written explicitly in the 7-to-8 guide. Both are evidence for the "upgrade stopped halfway" branch, not routine maintenance.
## 4. Fourth layer: TLS certificate and private key
When the browser reports a certificate error or the log cannot read one, check the paths the manual lists. The Alternative HTTPS certificate section of pveproxy(8) says pveproxy uses `/etc/pve/local/pveproxy-ssl.pem` and `.key` if present, then falls back to `/etc/pve/local/pve-ssl.pem` and `.key`; the private key may not use a passphrase. The certificate page adds that each node's default certificate is `/etc/pve/nodes/NODENAME/pve-ssl.pem`, signed by the cluster CA and not trusted automatically; the CA certificate and key live in pmxcfs.
```bash
ls -l /etc/pve/local/
ls -l /etc/pve/nodes/
```
Check in this order: whether the custom pair was replaced by a passphrase-protected key during the upgrade (the manual forbids a passphrase), then whether the default node certificate is still present. If regeneration is needed, use the commands listed in pvecm(1):
```bash
pvecm updatecerts
pvecm updatecerts --force
pvecm updatecerts --silent
```
The manual defines them as follows: `--force` forces generation of a new SSL certificate, `--silent` ignores errors (for example when the cluster has no quorum), and no option updates node certificates and generates all needed files and directories. Note that `--silent` suppresses errors rather than fixing them. If your node is a cluster member and the GUI turned read-only after the upgrade, that is a quorum problem, not a certificate problem; recover the cluster side. These pvecm commands are verified against the official manual, but confirm your installed version accepts all options with `pvecm updatecerts --help`.
Separate "certificate error" from "blank page." A certificate error still yields a browser warning, so pveproxy is answering; a blank page with no log error points to stale assets - section 6. Mixing them can turn a cache clear into a needless certificate rotation.
## 5. Fifth layer: access control and listening address
An upgrade does not write configuration by itself, but a hand-edited `/etc/default/pveproxy` comes through it, and an old subnet or listening address can shut out the new client. pveproxy(8) lists `ALLOW_FROM`, `DENY_FROM`, and `POLICY` there in apache2-like syntax; addresses accept any Net::IP syntax, `all` aliases `0/0` and `::/0`, and the default policy is allow. `LISTEN_IP` constrains the bind address of pveproxy and spiceproxy to an address configured on the system.
```bash
grep -E 'ALLOW_FROM|DENY_FROM|POLICY|LISTEN_IP' /etc/default/pveproxy
```
If you change it, the manual calls for a full restart of both services, or a node reboot:
```bash
systemctl restart pveproxy.service spiceproxy.service
```
Unlike reload, a restart can interrupt long-running worker processes such as a live guest console or shell, so use a maintenance window. People have restarted pveproxy during business hours and reported the console disconnect as a second incident. Guest console issues belong in [Proxmox Live Migration Triage](pve-live-migration.md), but that is a separate chain - do not debug it while fixing the GUI.
## 6. Sixth layer: browser cache and front-end assets
The official 7-to-8 upgrade guide is direct in its post-upgrade notes: clear the browser cache or force-refresh (`CTRL` + `SHIFT` + `R` on Windows and Linux, `Command` + `Alt` + `R` on macOS). Front-end asset URLs may not change with the release, so the browser feeds old JavaScript to a new API and you get a login box followed by a blank or error-filled page.
Test it cheaply: open the address in a private window or another machine. If that works and the original browser does not, it is cache and the server needs no change. This branch is common on a first GUI opening after an upgrade - the only one where the server is green and the client red. The same cheapest-test-first habit appears in [Proxmox Snapshot Rollback and qcow2 Triage](pve-snapshot-rollback.md): confirm state before touching data.
## 7. One tree: symptom to next cut
Compress the six layers into executable tests:
- Blank page, service active, 8006 listening: clear cache or use a private window; if private works, stop.
- Connection refused, and `ss` shows no 8006: check `pveproxy status` and `journalctl`, then use `pveproxy start --debug` for the raw error.
- Log reports a certificate read failure or the browser gives an explicit certificate error: check the four files under `/etc/pve/local/` in section 4 order. Regenerate only if needed with `pvecm updatecerts`, and first look at `pvecm status` to see whether the cluster is quorate.
- Local works, remote does not: check the firewall and `ALLOW_FROM`, `DENY_FROM`, `POLICY`, and `LISTEN_IP` in `/etc/default/pveproxy`; after changes, restart pveproxy and spiceproxy the way the manual requires.
- Log shows a package dependency error and `dpkg --audit` has output: go back to the upgrade flow and finish it with the official guide for your installed release and `apt -f install`.
- GUI opens but every cluster write is read-only: not a GUI fault. Check quorum; the `Quorate` field of `pvecm status` is the dividing line.
Each step answers one yes/no question. Do not mix the "service is down" and "cache was stale" branches into one round of changes. If the change window also touched the firewall, certificates, and browser settings, roll back and verify in exactly this order.
## 8. Acceptance checklist before calling it done
- [ ] `pveversion` recorded, and the upgrade path matches the official guide used
- [ ] `systemctl is-active pveproxy pvedaemon` reads active for both
- [ ] `ss -lntp | grep 8006` shows a listener bound as expected
- [ ] Errors from foreground debug and `journalctl` archived, with nothing unexplained left
- [ ] Certificate and key paths under `/etc/pve/local/` follow the manual's fallback order, with no passphrase
- [ ] `/etc/default/pveproxy` access control and listening address reviewed; changes made in a maintenance window
- [ ] Verified in a private window so cache is ruled out
- [ ] If certificates were regenerated, quorum was checked first and pvecm options were re-read with `--help`
To script this, combine `pveversion`, `is-active`, `ss`, the log tail, and the certificate list into one diagnostic dump. Walk the six layers by hand once first, or the script will have no reading key.
## Related Articles
- [Proxmox VE Lost Quorum: A pvecm Recovery Triage Tree](proxmox-lost-quorum-recover.md)
---
## Proxmox VE Lost Quorum: A pvecm Recovery Triage Tree
URL: https://ops.jiunotes.top/en/monitor/proxmox-lost-quorum-recover.md
摘要: A recovery triage tree for a Proxmox VE cluster that lost quorum and turned /etc/pve read-only: read pvecm status votes, separate cold start, network partition and permanent node loss, then follow the official pvecm expected and delnode flow.
### Answer
Recovering quorum starts by naming the scene: a cold start after power loss needs only restored communication and waiting; a network partition needs the corosync link fixed before writes are safe; permanent node loss is the only case for pvecm delnode. The Quorate field and vote counts of pvecm status are the dividing line, and pvecm expected 1 is a documented temporary workaround, not a routine repair.
### FAQ
Q: Every write in the PVE GUI fails as read-only. Is quorum lost?
A: Check the Quorate field of pvecm status first. The official Cluster Manager guide states that the cluster switches to read-only mode when it loses quorum; a healthy view reads Quorate: Yes and the Votequorum section shows Expected votes, Total votes and Quorum. If Quorate is No, it is a quorum problem; if Yes, investigate permissions or storage instead of reaching for pvecm expected.
Q: Is pvecm expected 1 a safe repair command?
A: It is a documented workaround, not a routine repair. The pvecm(1) manual says it Tells corosync a new value of expected votes; the Cluster Manager guide mentions it only for changing /etc/pve/corosync.conf without quorum and for a failed node removal, and assumes you understand the consequences. It opens a temporary write window - do only the one thing you came for, with no side edits to VM or storage config.
Q: Why does a 4-node cluster need 3 votes?
A: The official Cluster Manager guide's sample pvecm status shows 4 nodes, Expected votes: 4 and Quorum: 3 - the majority rule, since state changes require a majority of nodes online. So a 4-node cluster loses quorum after two nodes go away; a 2-node cluster needs an external QDevice to tolerate a single failure.
Q: After a power cut all nodes booted, but guests are not starting. Why?
A: The official Cluster Cold Start section explains it: with all nodes offline the cluster is not quorate; at boot the pve-guests service waits for quorum and only then starts guests with the onboot flag. Nodes boot at different speeds, so guest startup is delayed until quorum forms. Restore inter-node communication and wait rather than forcing guests up by hand.
Q: How do I permanently remove a node that will not return?
A: The official flow requires confirming the node is no longer a Ceph member and hosts no Ceph resources, powering it off so it cannot rejoin with its current config, then running pvecm delnode NODE from a remaining node and verifying with pvecm nodes. If removal fails because the remaining node lost quorum, the documented workaround is pvecm expected 1 first, then retry delnode.
### Full Content
# Proxmox VE Lost Quorum: A pvecm Recovery Triage Tree
The image that makes a Proxmox VE admin tense: the GUI turns read-only, VM configuration will not save, HA does nothing, and SSH shows `/etc/pve` is not writable. That is almost always a lost quorum. This guide splits recovery into three scenes - cold start, network partition, permanent node loss - and reads state before acting. Commands, numbers and causal claims were checked against the official [Cluster Manager wiki](https://pve.proxmox.com/wiki/Cluster_Manager), [pvecm(1) manual](https://pve.proxmox.com/pve-docs/pvecm.1.html) and [administration guide](https://pve.proxmox.com/pve-docs/pve-admin-guide.html).
Quorum is not a Proxmox switch but a state corosync computes from votes. Losing it switches the cluster to read-only - a protection, not the fault. The job is finding why votes are short, not bypassing protection. The one official bypass, `pvecm expected 1`, has narrow uses; abusing it removes the consistency guarantee.
## 1. Layer one: read pvecm status
Turn "cluster unavailable" into readable fields. The quorum-relevant parts of `pvecm status` are three sections:
```bash
pvecm status
pvecm nodes
```
In the official four-node example, `Quorum information` holds `Nodes: 4` and `Quorate: Yes`; `Votequorum information` holds `Expected votes: 4`, `Highest expected: 4`, `Total votes: 4`, `Quorum: 3`, `Flags: Quorate`; and `Membership information` lists each node's Nodeid, Votes and Name, marking `(local)`.
How to read it:
- `Quorate: Yes` with `Flags: Quorate`: this node believes the cluster is quorate, so quorum is not the problem. Check permissions, storage, or the API.
- `Quorate: No`: quorum is lost; go to the scene split below.
- `Expected votes` is the expected count, `Total votes` is what is currently visible; the gap tells you how many votes are absent. The official 4-node / Expected 4 / Quorum 3 example is the majority rule: state changes require a majority of nodes online.
- `Membership information` names who is present and who is not - the basis for the scene split.
The pvecm(1) manual describes `pvecm status` as Displays the local view of the cluster status. In a partition, different nodes report different states, so one node is never enough evidence.
## 2. Layer two: name the scene before running a command
Quorum loss has different causes and different recovery paths. Getting this step wrong can enlarge the incident.
**Scene A: cold start after power loss.** The official Cluster Cold Start section is clear: with all nodes offline the cluster is naturally not quorate, a common state after a power cut; at boot the `pve-guests` service waits for quorum and starts guests with the `onboot` flag only once quorate. Nodes boot at different speeds, so guest startup waits for quorum. The right action is to restore inter-node networking, make sure the intended nodes are up, then wait - not force guests up or change vote counts.
**Scene B: partition or partial node loss.** The official Cluster Network section requires latency under 5 milliseconds between nodes for stable operation; with more than three nodes and latency above about 10 ms, stability is unlikely. The Corosync Over Bonds section warns that some bond modes create asymmetric connectivity where corosync cannot form a stable quorum; with HA enabled even healthy nodes may fence themselves, and in the worst case the whole cluster fences. Fix the corosync link, switches and bond configuration first. Changing votes here only hides the link fault.
**Scene C: a node is permanently gone.** The machine failed or was decommissioned and will not return. Only now remove it from cluster configuration with `pvecm delnode`, using `pvecm expected 1` if needed to open a write window. This is the only scene that actually needs vote manipulation.
To tell them apart, read `pvecm nodes` and `Membership information` for who disappeared, then recall whether there was a power cut or a network change. Everyone absent after a power cut is A; some absent with a network change is B; one node confirmed dead and not returning is C. Cluster communication faults and VM egress faults are different chains - the path-first habit in [Proxmox VM Network Triage: Bridge vs NAT](pve-bridge-nat-stuck.md) applies, but bridge/NAT tests do not reach corosync; see also [Proxmox Snapshot Rollback and qcow2 Triage](pve-snapshot-rollback.md) for another state-before-action chain.
## 3. Layer three: correct action for scenes A and B
For a cold start, the core action is waiting - for corosync to form membership and quorum, not for a service to magically recover. The official guide also gives a command to observe how long membership rebuilding takes:
```bash
corosync-cmapctl | grep -Ew 'runtime.config.totem.token|runtime.config.totem.consensus'
```
This command comes from the guide's Changing the Token Coefficient section. Its sample output holds `runtime.config.totem.consensus` and `runtime.config.totem.token`; their sum is the minimum membership-rebuild time after a node goes offline, 10.89 seconds in the example, with optimization recommended above 30 seconds and strongly above 45. Actual tuning depends on your corosync version and network, so trust local `man corosync.conf`.
For a partition, first answer why nodes cannot see each other. Work through the official sub-5 ms requirement and the bond warning: inter-node latency, switch ports, bond mode, LACP settings. The guide notes LACP sends an LACPDU every 30 seconds by default, a 90-second failover, while HA nodes may fence themselves after roughly one minute without stable quorum; it recommends `bond-lacp-rate fast` on both node and switch to cut failover to about 3 seconds. This causal chain is specific to LACP and HA - do not copy it into a non-LACP environment.
Restraint matters. The dangerous impulse during a partition is setting votes to 1 so writes work. That lets two mutually invisible partitions both believe they may write - exactly what quorum exists to prevent. The guide's QDevice analysis stresses partition risk: an even-node cluster gets one extra vote from a QDevice, an odd-node cluster gets (N-1), partly to stop partitions acting independently.
## 4. Layer four: scene C, permanently removing a node
Once the node is confirmed not to return, follow the official Cluster Manager Remove a Cluster Node flow:
1. Confirm the node is no longer a Ceph cluster member and hosts no Ceph resources or services.
2. Power it off and make sure it cannot power on again in this network with its current configuration.
3. Log into any remaining node and remove it.
4. Verify the removal with `pvecm nodes`.
The commands below use `pvecm delnode ` from the pvecm(1) SYNOPSIS, where the argument is the cluster node name:
```bash
pvecm delnode node4
pvecm nodes
```
`node4` is the official example name and a placeholder; substitute the real name. The manual describes `pvecm delnode` as removing a node from cluster configuration. After success, vote counts return to the real online count and no bypass is needed.
If removal fails because the remaining node lost quorum, the official Cluster Manager guide's Separate a Node Without Reinstalling section gives the workaround:
```bash
pvecm expected 1
pvecm delnode node4
```
The source text reads: If the command fails due to a loss of quorum in the remaining node, you can set the expected votes to 1 as a workaround, then repeat the pvecm delnode command. The pvecm(1) manual defines `pvecm expected` as Tells corosync a new value of expected votes; its SYNOPSIS is `pvecm expected ` with `` an integer from 1 to N. Syntax is verified against the official manual; confirm support and the current value with `pvecm help` and `pvecm status` in your environment.
## 5. Layer five: the boundary and risk of pvecm expected
This section stands alone because it is the only operation in the flow that manufactures quorum. The official Cluster Manager guide, in Corosync Configuration to Troubleshooting to Write Configuration When Not Quorate, says that if you need to change `/etc/pve/corosync.conf` on a node with no quorum and you understand what you are doing, use `pvecm expected 1`. The pvecm(1) manual adds: This sets the expected vote count to 1 and makes the cluster quorate. You can then fix your configuration, or revert it back to the last working backup.
Three hard boundaries follow:
- **Purpose limited**: the official guide mentions it only for changing corosync.conf without quorum and as a workaround for a failed node removal. It is not a switch for day-to-day operation.
- **Window limited**: the window exists to finish one concrete task (restore config or delete a node), after which votes should return to reality. Inside the window the system believes it has quorum when it does not; if a second node blips, inconsistent configuration can be written to `/etc/pve` and propagated to nodes that never agreed to it.
- **Subject limited**: it changes corosync's view of expected votes, not the config file. Real persistence for a removal comes from `pvecm delnode` rewriting configuration; stopping at `expected 1` leaves the cluster genuinely unrepaired.
HA adds another concern. The guide notes in its QDevice and bond sections that HA relies on watchdog fencing and stable quorum, and nodes may fence themselves when quorum is unstable, up to the whole cluster. Keep window operations away from HA peak times and expect fencing as a real possibility. Guest migration triage belongs in [Proxmox Live Migration Triage](pve-live-migration.md), but a failed migration and a lost quorum are separate chains.
## 6. One tree: from status field to action
- `Quorate: Yes` in `pvecm status`: not a quorum problem. Stop using `pvecm expected` and check permissions or storage.
- `Quorate: No`, all nodes absent, right after a power cut: scene A. Restore node networking and power, wait for `pve-guests` to start guests after quorum, no manual intervention.
- `Quorate: No`, some nodes present, network or switch changed: scene B. Fix the corosync link, latency and bond config; do not restore writes by changing votes.
- `Quorate: No`, one node confirmed permanently gone: scene C. Do the Ceph cleanup, power it off, `pvecm delnode`, verify with `pvecm nodes`.
- Removal fails due to quorum: documented workaround of `pvecm expected 1` then a retry of `pvecm delnode`, with no other work inside the window.
- Need to change `/etc/pve/corosync.conf` without quorum: again start with `pvecm expected 1`, and only if you understand the consequences.
- Membership keeps rebuilding, latency suspicious: inspect token plus consensus with `corosync-cmapctl` and judge against the official thresholds.
Each step answers one yes/no question. The greatest danger is using `pvecm expected 1` before the scene is clear: it silences the alarm without removing the cause.
## 7. Acceptance checklist before calling it done
- [ ] `pvecm status` reads `Quorate: Yes`, with `Expected votes` and `Total votes` back at the real online node count
- [ ] `pvecm nodes` no longer lists the permanently removed node; deletion verified
- [ ] If `pvecm expected 1` was used, only for a documented scenario, with no unrelated VM or storage edits in the window
- [ ] Inter-node latency meets the official 5 ms requirement; bond/LACP checked against official advice
- [ ] HA and Ceph prerequisites confirmed: the removed node holds no Ceph resources and HA services are stable
- [ ] `onboot` guests started through the official mechanism after quorum, not started ahead of it by hand
- [ ] Installed PVE version and `pvecm help` output recorded; command syntax verified locally
To make these tests recurring, sample `pvecm status` votes and `Quorate`, latency, and membership changes. Walk the three scenes by hand first, or an alarm will ring with nobody sure which branch to take.
## Related Articles
- [Proxmox VE cluster and VM triage helper (symptom to command chain)](../tools/pve-triage/index.md)
- [Proxmox VE Web GUI Down After an Upgrade: A pveproxy Triage Tree](proxmox-gui-not-starting-after-upgrade.md)
---
## Proxmox VM Cannot Reach the Network: A Bridge vs NAT Triage Tree
URL: https://ops.jiunotes.top/en/monitor/pve-bridge-nat-stuck.md
摘要: A triage decision tree for Proxmox VE VMs that cannot reach the network: first decide whether the VM rides a Linux Bridge or NAT, then check whether the guest ever obtained an IP, whether vmbr0 is bound to the wrong physical NIC, whether /etc/network/interfaces or the VLAN tag is misconfigured, and whether Open vSwitch and a Linux bridge are being mixed on the same port. Pin it down with qm showconfig, ip, and iptables.
### Answer
When a Proxmox VM cannot reach the network, start by deciding which path it takes: a Linux Bridge or NAT. On a bridge the guest sits directly on vmbr0 with an IP on the same subnet as the host, no SNAT involved; on NAT everything rides the host's forwarding and nat tables. First confirm whether the guest actually got an IP. No IP points to the wrong physical NIC on vmbr0, a bad VLAN tag, or OVS and a Linux bridge fighting over one port. An IP that cannot reach the gateway points to tag/port mismatches or a broken FORWARD and MASQUERADE chain. Read net0 with qm showconfig, then work host-side, one branch at a time.
### FAQ
Q: A Proxmox VM cannot even ping its gateway. What should I check first?
A: Decide first whether this VM is on a bridge or NAT. Look at the net0 line in qm showconfig: a bridge pointing at vmbr0 usually means bridge mode, where the guest should get an IP on the host's subnet. Inside the guest, run nmcli -p dev show and check whether it has an IP at all. If it has none, the problem is at layer two or a wrong NIC. If it has one but cannot reach the gateway, move up to VLAN tags and the host's forwarding chain. Do not reboot before you have read that line.
Q: vmbr0 is up and the host reaches the internet, so why is the VM on it still stuck?
A: Usually vmbr0 is bound to the wrong physical NIC. The host being online does not mean the NIC under vmbr0 is on the same L2 domain. Run ip link to see which physical port vmbr0 has as a member, then confirm which switch port and VLAN that port is on. A guest that never gets an address almost always means the wrong port was chosen.
Q: After I added a VLAN tag to a VM it went fully silent. How do I track it down?
A: Go host-side first: ip -d link show tells you the VLAN protocol state of vmbr0, then confirm whether the upstream switch port is access or trunk and which VLANs it allows. The tag number must line up one-to-one with the physical network. The trap most people fall into is treating a tag like a switch that "gives the guest a different subnet." It changes L2 framing; get it wrong and the whole link dies at layer two.
Q: Can I mix Open vSwitch and a Linux bridge in Proxmox?
A: I would not. OVS and a Linux bridge are two separate bridging stacks. Do not let the same physical NIC be claimed by both vmbr0's bridge rule and an OVS port. Mix them and the forwarding path is no longer unique, so you get an intermittent link with visible drops in the capture. Either go all OVS or all Linux bridge.
Q: Should a new VM use bridge or NAT?
A: Default to bridge. The guest goes straight onto vmbr0 with an IP on the same subnet, so egress does not depend on host SNAT; the path is short and the diagnosis is straightforward. NAT fits the case where you do not want to expose the guest into the production subnet and you also do not want to wire up a dedicated switch VLAN; the cost is one more layer to inspect: the host FORWARD chain and the nat table.
### Full Content
# Proxmox VM Cannot Reach the Network: A Triage Tree
When a Proxmox VM suddenly loses egress, the worst reflex is to restart things without
knowing which mode it runs in. This note splits the failure by **whether the VM rides a
Linux Bridge or NAT**: first confirm whether the guest ever got an IP, then follow vmbr0's
physical NIC, `/etc/network/interfaces`, the VLAN tag, and any OVS / Linux-bridge mix down
one branch at a time.
I have had vmbr0 bound to the wrong physical port take an entire batch of VMs offline, and
I have had a VLAN tag treated as a subnet switch that cut the link at layer two. Get bridge
versus NAT right first, and the rest of the tree pays off. External references live in the
[Proxmox networking docs](https://pve.proxmox.com/pve-docs/chapter-network.html), the
[Linux bridge mechanism](https://www.kernel.org/doc/html/latest/networking/bridge.html), and
the [iptables NAT tables](https://iptables.netfilter.org/).
## Sixty seconds: bridge or NAT first
Run these in order; the output usually maps the failure to one class.
```bash
# host side: which bridge this VM's NIC points at, any tag, which model
qm showconfig 100 | grep -E "^net0:"
# host side: is vmbr0 up, and which physical port is bound to it
ip -br link show
ip route
# guest side: did it get an IP at all (splits "no address" from "address, no egress")
nmcli -p dev show | grep -E "IP4.ADDRESS|IP4.GATEWAY|IP4.DNS"
```
- `net0` points at `vmbr0` and the guest holds a subnet-matched IP: **bridge mode**, no
host SNAT for egress.
- `net0` points at a non-vmbr0 bridge, or SNAT is configured: **NAT mode**, egress depends
on host forwarding.
- `IP4.ADDRESS` in the guest is `127.0.0.1` or empty: **layer two is down**, branch 1.
- An IP is present but `ping ` fails: branch 2 or 3.
- OVS is in use and a physical port is claimed by two bridges: branch 4.
The branches as a tree (land on "did it get an IP" first, then drill in):
```text
VM cannot reach the network
|
+-- guest has no IP (nmcli shows none / only 127.0.0.1)
| +-- vmbr0 member is not the real uplink --> wrong physical NIC -> fix interfaces
| +-- tag set but upstream port does not allow it -> VLAN L2 break -> align tag/port
| \-- OVS and a Linux bridge mixed? -> non-unique path -> pick one, split the mix
|
+-- guest has an IP but cannot ping the gateway
| +-- bridge mode yet vmbr0 forwarding missing -> interfaces wrong / bridge not up
| +-- NAT mode with no SNAT rule in the nat table -> host chain broken -> add FORWARD + MASQUERADE
| \-- gateway reachable, outside world not -> upstream NAT/firewall -> out of this box's scope
|
\-- intermittent, captures show drops
+-- an OVS port and vmbr0 fighting over one physical port -> mix -> split
\-- physical port / transceiver flapping -> watch ip -s link error counters
```
## Branch 1: the guest never gets an IP (layer two is down)
Symptom: inside the guest, `nmcli -p dev show` shows no `IP4.ADDRESS`, or only `127.0.0.1`,
and `ip a` reports `NO-CARRIER` on the interface. **This is a layer-two problem, not an IP
problem.**
```bash
# host side: which NIC is the current member of vmbr0
ip -d link show vmbr0
# host side: is that physical link up, any error counters
ip -s link show
# guest side: is the physical link detected
ethtool | grep -E "Link detected|Speed"
```
How to branch further:
- **the `ip -d link show vmbr0` member is not the real uplink**: vmbr0 is bound to the
wrong physical NIC. This is the most common root cause. The host is online through eno2,
but `/etc/network/interfaces` put eno1 in vmbr0's `bridge-ports`. Every guest hangs on
eno1, and eno1's L2 domain has no default gateway at all. **Point bridge-ports at the real
uplink and `ifreload`** - this is the step people miss most.
- **the member port shows `NO-CARRIER` or heavy error counters**: a physical link problem.
Check the cable and the switch port before you keep digging at the VM.
- **the guest interface reads `Link detected: no`**: follow the host-side port down to the
physical layer. The virtio driver itself rarely drops a link; when it does, the host port
is usually the real culprit.
The trap I hit most often (a scenario built from a typical production case): during a host
migration I copied the old vmbr0 `bridge-ports` over verbatim, but the new box names its
NICs differently, so the names did not match and a whole batch of VMs went silent while the
host stayed online. **The host reaching the internet does not prove the NIC under vmbr0 is
correct.** One line, `ip -d link show vmbr0`, settles it, yet it is the first thing people
skip.
## Branch 2: an IP is present, but the gateway is unreachable (config layer)
Symptom: the guest holds an IP and `ip route` shows a default route, but `ping `
fails.
```bash
# host side: how vmbr0 is written in interfaces (bridge-ports / bridge-stp / vlan-raw-device)
grep -A6 "^auto vmbr0" /etc/network/interfaces
# host side: VLAN protocol state of vmbr0 (any tag, which one)
ip -d -s link show vmbr0
# guest side: is the gateway and route actually present
ip -br -4 addr
ip route
```
How to branch further:
- **bridge-ports points at the right port, but a `vlan-raw-device` or a `net0` tag is set
while the upstream switch port is access**: the VLAN tag is misconfigured. A tag changes
the 802.1Q L2 framing; it is not a "put me on a different subnet" switch. When the tag and
the switch port mode disagree, the switch drops the frame and the guest sees a gateway
that will not answer.
- **vmbr0 is missing `bridge-ports`, or it has `bridge-stp 1` but no matching
`bridge-vlan-aware` for the tag**: the bridge is not coming up right and frames will not
cross it.
- **config is correct, one tag works but another does not**: most often `bridge-vlan-aware`
is off, so vmbr0 behaves as a plain L3 forwarder and the tag never isolates anything.
The decisive point: **a tag is L2 framing, not an IP switch.** Equating "give this VM a
different subnet" with "add a tag" is the most common misread in this failure class. Before
touching a tag, confirm whether the upstream switch port is trunk or access and which VLANs
it carries - that part depends on your on-site switch configuration.
## Branch 3: NAT mode depends on the host's forwarding chain
Symptom: `net0` is not a vmbr0 straight-through to the production subnet but a NAT bridge;
the guest can ping the host but not the outside world.
```bash
# host side: does FORWARD let the VM subnet through
iptables -L FORWARD -n -v | head -20
# host side: is there a MASQUERADE/SNAT for the VM subnet in the nat table
iptables -t nat -L POSTROUTING -n -v | head -20
# host side: is kernel forwarding on
cat /proc/sys/net/ipv4/ip_forward
```
How to branch further:
- **`ip_forward` is 0**: the host is not forwarding at all, NAT is dead. `sysctl -w
net.ipv4.ip_forward=1` applies immediately; persist it under `/etc/sysctl.d/`.
- **`POSTROUTING` has no `-j MASQUERADE` for the VM subnet**: the SNAT chain is broken.
Traffic leaves without a rewritten source, so return packets have nowhere to go. Add a
MASQUERADE that matches the VM subnet.
- **FORWARD drops the VM subnet**: the forwarding chain is blocking it. Allow the in and out
directions on the NAT bridge.
A judgment call I stand by: if bridge will do, do not reach for NAT. NAT adds a host
forwarding layer plus the nat table, so the surface to inspect grows from "watch the guest's
L2" to "watch host FORWARD plus the nat table." Each extra layer is another place it can
break. NAT earns its keep only when you would rather keep the guest out of the production
subnet and would rather not wire a dedicated switch VLAN.
## Branch 4: OVS and a Linux bridge mixed
Symptom: intermittent, captures show drops, and `ovs-vsctl show` and `ip link` each
describe a different set of bridges.
```bash
# host side: which ports the OVS side holds
ovs-vsctl show
ovs-vsctl port-to-br
# host side: which ports the Linux bridge side holds (two bridges on one physical port?)
ip -d link show
```
How to branch further:
- **the same physical port appears in both vmbr0's bridge-ports and an OVS port**: the
forwarding path is no longer unique; whichever bridge wins first carries the frame, so the
link comes and goes. **Go all OVS or all Linux bridge and split the mix.**
- **the OVS bridge is up but its member port was taken by the Linux bridge**: traffic never
enters OVS. Go back to the Linux bridge side and check there.
I worked through one (a scenario built from a typical production case): during an upgrade I
built an OVS bridge but never removed the old vmbr0, so one 10GbE port was claimed by both.
The service came and went, and a capture showed each port carrying about half the traffic.
**The fingerprint of a mix is two bridges, one port, half the traffic dropped.**
## Quick reference
| Symptom | First guess (misread) | Real cause | Where to look |
|---|---|---|---|
| guest has no IP, `NO-CARRIER` | reinstall the OS | vmbr0 bound to the wrong NIC | `ip -d link show vmbr0` |
| host online, all VMs silent | a VM problem | vmbr0's port not on the same L2 domain | interfaces bridge-ports |
| silent after adding a tag | guest has no IP | bad VLAN tag L2 framing / switch not allowing it | switch port trunk/access |
| has an IP, cannot reach gateway | wrong netmask | tag and switch port mode disagree | `ip -d -s link show vmbr0` |
| NAT guest cannot egress | wrong gateway | host ip_forward / nat table broken | `iptables -t nat -L` |
| intermittent, drops in capture | failing NIC | OVS and a Linux bridge mixed | `ovs-vsctl show` comparison |
This is the "what it is most often misdiagnosed as" table in working form. Tickets like
these start as "the VM OS is broken" or "the network is flaky"; reading the table backwards
saves most of the wasted poking.
## Related
- [Linux disk IO monitoring](linux-disk-io-monitor.md) - once egress works, slow VMs usually live in the disk IO virtualization layer
- [Node Exporter missing metrics](node-exporter-troubleshoot.md) - turn vmbr0 error counters and traffic into alerts
- [Kubernetes pod troubleshooting](kubernetes-pod-troubleshoot.md) - the same "egress broken" shape on the container side
- [Linux CPU monitoring](linux-cpu-monitor.md) - if the VM is still slow after the network heals, check whether the host CPU is being squeezed by a neighbor
**Originality note**: Every command, the decision tree, and the case studies in this article
were compiled by the author from production troubleshooting on Proxmox VE. Commands are
labeled for host-side versus guest-side context. The case studies are built from typical
production scenarios and contain no real company names, IP addresses, or timelines. The parts
that touch switch port mode and VLAN assignment depend on your on-site device configuration.
## Related Articles
- [Proxmox LXC Stuck Mounting Root Filesystem: Start Failure Triage](pve-lxc-rootfs-mount-stuck.md)
---
## Proxmox VM Migration Pitfalls: Cold vs Live, KVM-to-VMware vmdk Conversion, MAC/IP Drift and Storage Mismatch
URL: https://ops.jiunotes.top/en/monitor/pve-live-migration.md
摘要: A four-fork decision tree for migrating Proxmox VE virtual machines. Fork one decides cold vs live migration (guest stopped or running). Fork two decides whether source and target storage match (shared Ceph or LVMoCeph vs heterogeneous local disks, which changes whether a full data copy is needed). Fork three decides whether the source is KVM or VMware (vmdk format requires qemu-img convert before it can be attached to a Proxmox VM). Fork four decides whether the MAC address and IP actually survive the move, because qm migrate preserves MAC but does not change the guest IP, and a static IP from the source subnet is invalid on the target subnet.
### Answer
Work the four forks in order; skipping one is what causes most migration failures. Fork one: cold or live. A stopped guest uses qm migrate without the --online flag. A running guest needs --online, and that flag only completes quickly when source and target share storage (Ceph, LVMoCeph, NFS). With heterogeneous local disks, --online triggers a full data copy and the progress bar runs for the duration of disk-size divided by network-bandwidth. Fork two: storage match. If source and target use the same shared storage, live migration is a seconds-level switchover. If they differ, qm migrate performs a full data copy by default (cap the bandwidth with --bwlimit, in KiB/s) or use vzdump plus the GUI/CLI restore flow on the target (PVE has no qm restore subcommand; vzdump produces a .vma.zst archive). Fork three: source format. If the VM came from VMware, the vmdk must be converted with qemu-img convert before it is attached to a Proxmox VM. Attaching vmdk directly works in QEMU but adds a format-parsing layer that degrades random-read latency and removes built-in snapshot support. Fork four: MAC and IP. qm migrate preserves the MAC address by default. If the source and target are on different subnets, the guest IP is still the source-subnet address and will not reach the target gateway. Either reconfigure the IP inside the guest or add a static route on the target subnet pointing back to the source gateway.
### FAQ
Q: A live migration between two Proxmox nodes is stuck at 99 percent and the progress bar is not moving. Is it broken?
A: Not necessarily. The final phase of a live migration is dirty-page synchronisation: the guest is still writing to memory and the source QEMU process must flush the last batch of dirty pages before the switchover. Check whether the source QEMU process is still consuming CPU and network IO with top. If it is still active, the migration is in progress and you should wait. If the process has stopped, the migration was interrupted. The source VM is still running and you can simply re-run qm migrate without restoring from backup.
Q: I exported a vmdk from VMware Workstation and attached it directly to a Proxmox VM. Performance is much worse. Why?
A: vmdk is not a native block format for KVM. QEMU has a vmdk block driver that can read it, but every IO goes through an extra format-parsing layer, which adds significant random-read latency. vmdk also has no built-in snapshot support in Proxmox. The correct path is to convert first: qemu-img convert -f vmdk -O qcow2 source.vmdk target.qcow2, then attach the qcow2 file to the VM. For a large vmdk over 100 GB the conversion takes a while, so schedule it in advance.
Q: After qm migrate the guest IP is still on the source subnet and it cannot reach the target gateway. How do I fix it?
A: qm migrate preserves the MAC address but does not change the guest IP. If the source and target are on different subnets, the static IP inside the guest is invalid on the target subnet. Two options: reconfigure the IP inside the guest with nmcli con mod and nmcli con up, or add a static route on the target subnet router pointing to the source gateway. In DHCP environments the MAC is unchanged but the target subnet DHCP pool may not have a lease for that MAC, so the guest gets no address. Add a static MAC-to-IP mapping in the target DHCP pool.
Q: After a cold migration the target node reports a disk format not supported error. What is wrong?
A: The source disk format is not compatible with the target storage backend. The most common case is a raw-format disk on the source and LVM-Thin or Ceph on the target; qm migrate does not perform format conversion automatically. Confirm the target storage supports the source disk format before running the migration. If it does not, convert with qemu-img first, or use vzdump to create a backup and restore it on the target (vzdump produces a .vma.zst archive; PVE has no qm restore subcommand, restoration goes through the GUI or the vzdump API flow, and any storage backend can host the result).
Q: The source Proxmox is version 8.4 and the target is 8.2. Can I run qm migrate directly?
A: Minor version differences usually work, but the target must be at the same or newer version than the source, or some configuration fields introduced in the newer version will not be recognised by the older qm binary and the migration will fail with a config parse error. Upgrade the target first, then run the migration. For large version gaps (e.g. 7.x to 8.x), use the vzdump backup plus restore path instead of qm migrate, because the config format has changed between major versions. vzdump produces a .vma.zst archive; PVE has no qm restore subcommand, so restore goes through the GUI or the vzdump API flow.
### Full Content
# Proxmox VM Migration Pitfalls
Migrating a Proxmox VE virtual machine is not a single qm migrate command.
Four forks must be worked in order, and skipping any one of them is what
produces the most common migration failures: a stuck progress bar, an IP
that no longer reaches the target gateway, a disk that the target storage
backend does not accept, or a config parse error from a version mismatch.
External references:
[Proxmox Migration Documentation](https://pve.proxmox.com/pve-docs/chapter-migrate.html),
[QEMU Block Format Specification](https://www.qemu.org/docs/master/docs/interop.html),
[VMware vmdk Format](https://kb.vmware.com/s/article/1004790).
## Fork 1: Cold or Live Migration
```bash
# Cold migration (guest stopped)
qm shutdown
qm migrate --node
# Live migration (guest running, requires --online)
qm migrate --node --online
# Prerequisite: source and target share storage (Ceph / LVMoCeph / NFS)
# OR target accepts a full data copy
# (duration = disk-size / network-bandwidth)
# Decision criteria:
# Shared storage -> live migrate (seconds-level switchover)
# Heterogeneous local disks -> live migrate triggers full copy
# Guest cannot stop -> must live migrate; estimate copy time in advance
```
**Why a live migration stalls at 99 percent**: the final phase is
dirty-page synchronisation. The guest is still writing to memory and the
source QEMU must flush the last batch of dirty pages before the switchover.
A stalled progress bar at 99 percent that is still showing CPU and network
activity on the source is in progress, not broken. If the source process
has stopped, the migration was interrupted and you can re-run qm migrate
without restoring from backup.
## Fork 2: Does Storage Match?
```bash
# Check source storage type
qm showconfig | grep -E 'scsi|virtio'
# Look at which storage each disk is attached to
# Same shared storage (Ceph / LVMoCeph / NFS)
# Live migrate directly, no data copy needed
qm migrate --node --online
# Heterogeneous local disks (source local-lvm -> target local directory)
# Live migrate does a full data copy by default (disk size / network
# bandwidth). Use --bwlimit to cap bandwidth, --online to avoid downtime.
qm migrate --node --online --bwlimit 102400
# Or use vzdump first, then restore (safer, survives interruption)
vzdump --mode snapshot
# On the target: right-click the VM in the GUI -> Restore, or call the
# vzdump API / Pvesnippet restore flow. PVE has NO qm restore command.
```
## Fork 3: KVM or VMware Source?
**Migrating from VMware to Proxmox (the most common path)**:
```bash
# 1. Export vmdk from VMware (Workstation export or ESXi download)
# 2. Transfer to the Proxmox node
scp vmdk-file user@proxmox-node:/tmp/
# 3. Convert to a Proxmox-supported format (qcow2 recommended for built-in snapshots)
qemu-img convert -f vmdk -O qcow2 /tmp/source.vmdk /var/lib/vz/images//disk0.qcow2
# 4. Create the VM and attach the converted disk
qm create --name "Migrated-from-VMware" --memory 4096 --net0 virtio,bridge=vmbr0
# Import the vmdk into storage management (qm importdisk converts and registers)
qm importdisk /tmp/source.vmdk local-lvm
# importdisk produces -vm-disk-0.raw; attach it
qm set --scsi0 local-lvm:-vm-disk-0
# 5. Verify
qm start
```
**Why attaching vmdk directly is a problem**: QEMU has a vmdk block driver
that can read vmdk files, but the extra format-parsing layer degrades
random-read latency significantly. vmdk also has no built-in snapshot
support in Proxmox. In production, always convert to qcow2 before attaching.
## Fork 4: MAC Address and IP
```bash
# qm migrate preserves MAC by default; verify:
qm showconfig | grep net0
# Check that the MAC matches the source
# Check the actual IP inside the guest
ssh guest-ip "ip a"
# If source and target subnets differ, the static IP is invalid on the target
# Two options:
# a) Reconfigure the IP inside the guest:
# nmcli con mod ipv4.addresses
# nmcli con up
# b) Add a static route on the target subnet router pointing to the
# source gateway (when the guest IP cannot be changed)
# DHCP scenario: MAC is preserved but the target subnet DHCP pool
# may not have a lease for this MAC -> guest gets no address
# Fix: add a static MAC-to-IP mapping in the target DHCP pool
```
## Four High-Frequency Failure Cases (based on typical production scenarios)
**Case 1: Live migration stuck at 99 percent for twenty minutes**
A 500 GB data disk on a source with heterogeneous local-disk target. The
live migration was performing a full data copy at 1 Gbps, theoretical
completion time approximately 40 minutes. The 99 percent stall was the
final dirty-page sync phase. The source QEMU process was still active and
network IO was still moving, so the migration was in progress, not broken.
After approximately 25 more minutes the progress reached 100 percent and
the VM switched to the target node successfully.
**Case 2: vmdk attached directly to Proxmox, random-read latency 8x worse than qcow2**
A vmdk file was attached without conversion. QEMU's vmdk block driver added
a format-parsing layer that increased random-read latency from 1 ms to
8 ms. Resolution: qemu-img convert to qcow2, reattach the disk, latency
returned to 1.2 ms. Conversion of a large vmdk over 100 GB takes
considerable time; schedule in advance.
**Case 3: After cold migration the guest IP is still on the source subnet**
Source subnet 192.168.1.0/24, target subnet 10.0.1.0/24. The guest static
IP 192.168.1.50 is invalid on the target subnet. Resolution: reconfigure
the guest IP to 10.0.1.50, or add a static route on the target subnet
router for 192.168.1.0/24 via the source gateway. MAC address was
preserved by qm migrate; in DHCP environments the target subnet DHCP pool
must have a lease or static mapping for the preserved MAC.
**Case 4: Target node version older than source (8.4 source to 8.2 target)**
Proxmox 8.4 introduced configuration fields that the 8.2 qm binary does not
recognise, causing a config parse error and migration failure. Resolution:
upgrade the target node to 8.4 before running the live migration, or use
the vzdump backup plus restore path instead of qm migrate. vzdump produces
a .vma.zst archive; restoration goes through the GUI or the vzdump API
flow (PVE has no qm restore subcommand), so version compatibility with
the target node is not a blocker.
## Related Articles
- [Proxmox VE cluster and VM triage helper (migration failure branch)](../tools/pve-triage/index.md)
- [Proxmox VM Cannot Reach the Network: Bridge vs NAT Triage Tree (P47)](/en/monitor/pve-bridge-nat-stuck)
- [Proxmox VM Slowness: CPU, Memory, and Disk IO Deep Dive (P48)](/en/monitor/pve-perf-steal-ballooning)
- [Proxmox VM Device Passthrough Hardening Checklist (P49)](/en/monitor/pve-passthrough-iommu)
- [Proxmox Snapshot and Rollback Deep Dive (P50)](/en/monitor/pve-snapshot-rollback)
- [Proxmox VE Web GUI Down After an Upgrade: A pveproxy Triage Tree](proxmox-gui-not-starting-after-upgrade.md)
- [Proxmox VE Lost Quorum: A pvecm Recovery Triage Tree](proxmox-lost-quorum-recover.md)
## Originality Statement
This article is fully original. The four-fork decision tree is built around
KVM, VMware, and Proxmox heterogeneous migration scenarios. The vmdk
conversion path and MAC/IP drift resolution procedures are drawn from the
author's production environment experience and are not a rewrite of any
existing article.
---
## Proxmox LXC Stuck Mounting Root Filesystem: Start Failure Triage
URL: https://ops.jiunotes.top/en/monitor/pve-lxc-rootfs-mount-stuck.md
摘要: A triage guide for a Proxmox VE LXC container stuck at mounting root filesystem or start failed: narrow rootfs volume, underlying storage, mount points and locks, AppArmor, and namespaces with official pct and lxc-start debug commands.
### Answer
When a container sticks at mounting root filesystem, first capture the log the official way with pct start CTID --debug or lxc-start -n CTID -F -l DEBUG -o /tmp/lxc-CTID.log. Then check rootfs volume, underlying storage, mount points and locks, AppArmor, and namespaces one layer at a time instead of guessing through repeated restarts.
### FAQ
Q: The container reports mounting root filesystem failed. What first?
A: Get the raw log instead of clicking start repeatedly. The Obtaining Debugging Logs section of the official pct(1) manual gives two commands: pct start CTID --debug for a verbose foreground start, or lxc-start -n CTID -F -l DEBUG -o /tmp/lxc-CTID.log to run in the foreground and save the log to a file. The exact failing mount line is what decides the branch; guessing storage or permissions wastes time.
Q: Does a rootfs mount failure always mean the storage is broken?
A: No. Mounting is a chain: the underlying storage must be reachable, the volume present, the mount point creatable, and only then does rootfs exist inside the container namespace. Any broken link reports a mount failure. Read the rootfs line in /etc/pve/lxc/CTID.conf first, then check that storage; do not inspect inside the guest, because it never started.
Q: Can pct mount rescue a broken rootfs?
A: The pct(1) manual says pct mount mounts the container filesystem on the host, is meant for emergency maintenance only, and holds a lock that prevents operations other than start and stop. It can confirm the volume itself is readable, but it does not repair a start failure. Run pct unmount afterwards and check the lock state.
Q: The log shows an AppArmor denial. What now?
A: The pct(1) manual gives dmesg | grep apparmor to trace AppArmor activity and explicitly advises against disabling AppArmor for a container because of privilege-escalation risk. First see which path or mount was denied and whether a custom config or bind mount triggered it. Only consider lxc.apparmor.profile = unconfined if you understand the risk.
Q: How do I stop a foreground lxc-start debug session?
A: The pct(1) manual states that the foreground command attempts to start the container and that, to stop it, you run pct shutdown CTID or pct stop CTID in a second terminal. Closing the terminal is not the same as cleaning up the container process.
### Full Content
# Proxmox LXC Stuck Mounting Root Filesystem: Start Failure Triage
In Proxmox VE, an LXC container that stops at `mounting root filesystem`, reports `start failed`, or leaves a task log ending on a mount line is one of the most misread failures in daily ops. All of them look like "mount failed," but the broken link can be anywhere: storage unavailable, a locked volume, a mount point left inconsistent by a snapshot rollback, AppArmor blocking a custom mount, or a namespace declaration written incorrectly. This guide narrows those through five layers. Every command comes from the official pct(1) manual; commands the manual does not quote verbatim are marked as such, so check them with `--help` in your environment.
The reading key first: once a container is down, you cannot inspect it from inside, so all evidence must be collected on the host. The Obtaining Debugging Logs section of pct(1) is direct: when `pct start` cannot start a container, collect debugging output by passing the `--debug` flag, or use `lxc-start` to save a debug log to a file. Do that properly before proposing a fix. The same evidence-first habit appears in [Proxmox Snapshot Rollback and qcow2 Triage](pve-snapshot-rollback.md), though that article covers VM disks rather than the LXC rootfs chain.
## 1. Layer one: get the raw error with the official debug commands
Everything downstream depends on this log. The pct(1) manual gives two commands verbatim (replace CTID with your container ID):
```bash
pct start CTID --debug
lxc-start -n CTID -F -l DEBUG -o /tmp/lxc-CTID.log
```
The manual explains the second as attempting to start the container in foreground mode and saving the debug log to the file named by `-o`; to stop the container, run `pct shutdown CTID` or `pct stop CTID` in a second terminal, and the log is written to `/tmp/lxc-CTID.log`. It defines `--debug` as enabling a very verbose debug log level on start.
Two field notes. First, writing the log to a file instead of scrolling it means you can archive the failing line with its context; in foreground mode, closing the terminal destroys the scene. Second, do not click start repeatedly: each attempt mixes lock state and log timeline, making the result harder to read. After the foreground check, stop the container the way the manual prescribes, then move to the next layer.
The most valuable line in the log names the object that failed to mount - a path, a volume, or a filesystem type. Copy it down as the baseline for every later layer. If the log fails earlier, before reaching mount (configuration parsing, for example), the problem is not rootfs mounting; fix configuration or namespace declarations first.
## 2. Layer two: which volume is rootfs, and is the storage online?
The container configuration lives at `/etc/pve/lxc/CTID.conf`, which the pct(1) manual lists as the container configuration file, replicated to cluster nodes. Look at its rootfs line:
```bash
grep -E '^(rootfs|mp[0-9]+):' /etc/pve/lxc/CTID.conf
pct config CTID
pvesm status
```
`pct config CTID` is a documented pct(1) subcommand. `pvesm status` is the Proxmox storage command for listing storage state; the pct manual does not quote this syntax verbatim, so trust your `pvesm --help`. How to read it:
- If the storage holding the rootfs volume is down or unavailable, the mount failure is a result, not the cause. Fix storage reachability - link, authentication, target service - before touching container configuration.
- Storage online but the volume missing: it may have been deleted, the path changed after a migration, or a snapshot rollback pointed the volume at a nonexistent object. Only now compare backups and snapshots.
- Shared storage: confirm this node can see the same volume as other nodes. If only one node fails to start, suspect that node's storage path rather than rootfs itself.
The classic mistake is inspecting from inside the container. It never started, so nothing is mounted there. Also, seeing a volume file on the host does not prove it can be mounted: readability and mount semantics are different questions.
## 3. Layer three: mount points, locks, and leftover state
Once the volume itself checks out, failures usually come from who mounts it, where, and whether someone still holds it. The pct(1) manual says `pct mount` mounts the container filesystem on the host, is meant for emergency maintenance only, and holds a lock that prevents operations other than start and stop. That description itself points at two failure sources: a leftover mount and an unreleased lock.
```bash
pct status CTID
pct config CTID
pct mount CTID
pct unmount CTID
pct unlock CTID
```
All five are documented pct(1) subcommands; `unlock` clears locks. Read in this order:
- `pct status CTID` shows current state. If a task is still starting or holding a lock, check for unfinished background tasks before issuing concurrent operations.
- If you ran `pct mount` for maintenance, run `pct unmount` before starting. The manual is explicit that the operation holds a lock; forgetting it makes startup look stuck at mounting.
- Leftover mount points: a stale host directory still holding a dead volume can make a new mount fail. Check those with standard `mount` or `findmnt` commands, which pct(1) does not quote verbatim - verify with local `--help`.
- Snapshot-related failures: a snapshot or rollback can change volume state and mount paths, so compare snapshot and failure timestamps. The VM-side traps are covered in [Proxmox Snapshot Rollback and qcow2 Triage](pve-snapshot-rollback.md), but LXC rootfs and qcow2 are different mechanisms; do not carry conclusions across.
`pct unlock` clears a lock, but the lock is a symptom. If every start leaves one, return to the layer-one log for the real failure or you are only cleaning up after it.
## 4. Layer four: AppArmor and custom mounts
When the log points at permission denial, especially for a custom bind mount or a nonstandard path, go to AppArmor. The pct(1) manual states that AppArmor profiles restrict possibly dangerous actions and that some system calls, mount among them, are prohibited; it gives `dmesg | grep apparmor` to trace AppArmor activity.
```bash
dmesg | grep apparmor
grep -E '^(lxc\.|hookscript|features)' /etc/pve/lxc/CTID.conf
```
The first command is quoted in the manual; the second filters container configuration for declarations that may trigger custom mounts and is standard grep usage. The manual also says that, although not recommended, AppArmor can be disabled by adding `lxc.apparmor.profile = unconfined` to `/etc/pve/lxc/CTID.conf`, and immediately explains the security risk: misconfiguration or an LXC/kernel vulnerability can allow privilege escalation from inside the container.
So proceed in order: confirm it really is an AppArmor denial with `dmesg | grep apparmor`, see which path or operation was denied, and judge whether the custom mount is necessary or can be expressed a supported way. Consider `unconfined` only for a trusted workload where you understand the risk; for multi-tenant or untrusted workloads it is not a solution. There is no "just try it" here: the manual states the risk plainly and whoever uses it owns the consequence.
## 5. Layer five: namespaces and feature declarations
If the first four layers are clean and the log still reports a mount failure, look last at the container's namespace and feature configuration. The pct(1) manual references OS config files such as `/usr/share/lxc/config/.common.conf` and lists `/etc/pve/lxc/.conf` as the container configuration; custom `lxc.*` lines change LXC mount and namespace behavior.
The method here is minimizing difference: comment out the non-default `lxc.*` lines one at a time, restore one at a time, and start after each, using the layer-one log to decide which line introduced the failure. Unprivileged containers, idmaps, nested features, and bind mounts to host paths deserve special suspicion because they change identity and permission mapping at mount time. Note that the manual has no table stating which `lxc.*` line causes a mounting rootfs failure, so this is a method, not a guarantee; trust your installed LXC version and the local `pct help` or container configuration manual.
Containers that survived an upgrade belong in this layer too: a new kernel or LXC version can change defaults and make an old custom declaration invalid. That is a different chain from a host upgrade breaking the GUI, but the discipline is the same - see [Proxmox VM Network Triage: Bridge vs NAT](pve-bridge-nat-stuck.md) and [Proxmox PCI Passthrough and IOMMU Triage](pve-passthrough-iommu.md) for other layered, path-first triage.
## 6. One tree: symptom to next cut
Compress the five layers into executable tests:
- Log fails before mount at all: fix configuration parsing or namespace declarations; return to layer five.
- Log names a specific volume that failed to mount: copy it, then confirm the rootfs line and storage state in layer two.
- Storage down or volume invisible: fix the storage path and authentication; do not touch container configuration.
- Storage fine but start still fails and you previously ran `pct mount`: run `pct unmount`, confirm the lock is gone, then start.
- Permission denial in the log and `dmesg | grep apparmor` has output: go to layer four, judge whether the custom mount is needed, and treat `unconfined` with care.
- All clean, and configuration has non-default `lxc.*` lines: layer five, minimize differences, restore one line at a time.
- Every start fails at the same point and leaves a lock: take a fresh layer-one log; do not just run `pct unlock` and hide the symptom.
Each step answers one yes/no question. The worst habit in container triage is "fixing every suspicious line at once": even if recovery follows, you will not know which change mattered, and the same incident will cost the same time again.
## 7. Acceptance checklist before calling it done
- [ ] Full log captured with `pct start CTID --debug` or `lxc-start -n CTID -F -l DEBUG -o /tmp/lxc-CTID.log`, with the failing mount line archived
- [ ] Volume name and storage location confirmed from the rootfs line of `/etc/pve/lxc/CTID.conf`
- [ ] Storage confirmed online and the volume visible on this node
- [ ] No leftover `pct mount` mount or unreleased lock; `pct status CTID` normal
- [ ] AppArmor denial verified with `dmesg | grep apparmor`; if `unconfined` is used, risk and reason recorded
- [ ] Non-default `lxc.*` declarations checked one at a time, never several changes at once
- [ ] Foreground debug process cleaned up with `pct shutdown CTID` or `pct stop CTID` as the manual prescribes
- [ ] LXC and PVE versions recorded; commands not quoted verbatim in the manual re-checked with `--help`
The entry point for scripting is clear: combine `pct status`, the rootfs line of `pct config`, storage state, AppArmor output, and lock state into one diagnostic dump. Walk the five layers by hand first, though, or the script will collect data without knowing how to read it.
---
## Proxmox VM Device Passthrough Hardening Checklist: IOMMU, VFIO Binding, GPU/USB/PCI Host Conflicts
URL: https://ops.jiunotes.top/en/monitor/pve-passthrough-iommu.md
摘要: A hardening checklist for Proxmox VE PCI device passthrough: IOMMU must be enabled in BIOS and in the kernel boot parameters, vfio-pci must be bound to the target device before the guest can claim it, and the host must not be actively using the same GPU or USB device. Walk through each item with the exact command to verify, so a broken passthrough can be pinned to one specific step rather than guessed at.
### Answer
Before touching qm set, confirm three prerequisites on the host. First, IOMMU: VT-d (Intel) or SVM IOMMU (AMD) must be enabled in BIOS, and the kernel boot line must carry intel_iommu=on or amd_iommu=on plus iommu=pt. Verify with a non-empty listing under /sys/kernel/iommu_groups/. Second, vfio-pci: run lspci -nnk on the target device and confirm the Kernel driver in use field says vfio-pci, not the native driver. Write a udev override rule and reload udev if it does not. Third, host conflict: a GPU driving the host display or a USB device the host is actively using cannot be claimed by a guest at the same time. Stop the host consumer or switch the host to integrated graphics before starting the passthrough VM. Only after all three pass does qm set hostpci make sense. A missing pcie=1 flag on a GPU or NVMe device, or a hostpci BDF pointing at a child device instead of the root port, are the two most common configuration mistakes that make the device invisible inside the guest even when everything upstream is correct.
### FAQ
Q: I passthrough an NVIDIA GPU to a Proxmox VM and the guest shows no display. What should I check first?
A: Verify the host is not using the same GPU for its own display. Run ps aux | grep Xorg on the host. If X is running on that GPU, stop the host display server or switch the host to integrated graphics. A GPU can only serve one display output at a time. If the host is a headless server accessed over SSH, there is no display conflict and the problem is likely elsewhere: check that vfio-pci is bound to the device (lspci -nnk shows vfio-pci in the Kernel driver field) and that the hostpci BDF in qm showconfig points to the root port, not a child function.
Q: I wrote the udev override rule and reloaded udev, but lspci -nnk still shows the native driver. Why?
A: The rule was written but the device may have been claimed by a kernel module that loads before udev. Check whether the device's IOMMU group also contains a PCIe bridge (root port). If so, the bridge must be written into the same override rule; leaving it behind means the group is not fully bound to vfio-pci and the device stays on the native driver. List the group with ls /sys/kernel/iommu_groups//devices/ and add every BDF in that group to the override.
Q: After USB passthrough the host keyboard and mouse stopped responding. Is this a bug?
A: It is expected behaviour, not a bug. When a USB device is passed through, the host driver (usually xhci_hcd) releases it and the guest driver claims it. If you passed through the same keyboard and mouse the host itself is using, the host loses its input. Connect a separate USB keyboard to the host or remove the host's own input devices from the passthrough list.
Q: I added hostpci to qm set but the device is not visible inside the guest. What am I missing?
A: Two checks in order. First, look at the BDF address in qm showconfig: if it is a child device (e.g. 0000:01:00.1) rather than the root port (0000:01:00.0), the guest will not enumerate it. Use the root port BDF. Second, confirm pcie=1 is present on the hostpci line for GPU and NVMe devices. Without it, a GPU may appear in lspci inside the guest but fail to initialise the display, and NVMe will run at drastically reduced speed.
Q: Can I share one GPU across two VMs at the same time?
A: No. A consumer GPU is a single hardware device and can only be bound to one IOMMU group at a time, which in turn means one VM. To serve two VMs with GPU acceleration you need either two separate GPUs or an SR-IOV capable data-centre GPU that can expose virtual functions. Consumer NVIDIA and AMD cards do not support SR-IOV for display.
### Full Content
# Proxmox VM Device Passthrough Hardening Checklist
Passthrough in Proxmox is not a one-line qm set exercise. IOMMU has to be enabled
in both the BIOS and the kernel boot line, vfio-pci has to be bound to the target
device before the guest claims it, and the host must not be actively using the
same GPU or USB port. This checklist walks each prerequisite in order with the
exact verification command, so when something is not showing up inside the guest
you can pin it to one specific step instead of guessing.
External references:
[Proxmox PCI Passthrough Documentation](https://pve.proxmox.com/pve-docs/chapter-pci-devices.html),
[Linux VFIO Subsystem](https://www.kernel.org/doc/html/latest/vfio/vfio.html),
[Intel VT-d Specification](https://www.intel.com/content/www/us/en/developer/articles/technical/ia-virtualization-technology-intel-vt-d.html).
## Step 1: IOMMU Three-Point Check
| Check | Command | Expected | If not met |
|-------|---------|----------|------------|
| BIOS VT-d / SVM | `dmesg \| grep -i "IOMMU"` | AMD-Vi: 64 bits or Intel dmar present | Enter BIOS, enable VT-d (Intel) or SVM IOMMU (AMD), reboot |
| grub IOMMU flags | `cat /proc/cmdline` | intel_iommu=on or amd_iommu=on plus iommu=pt | Edit /etc/default/grub, add flags to GRUB_CMDLINE_LINUX, run grub-mkconfig, reboot |
| IOMMU groups populated | `ls /sys/kernel/iommu_groups/` | Multiple numbered directories present | Groups empty means the first two items did not actually take effect; go back to them. If groups are present, note the group number for the target device |
## Step 2: Bind vfio-pci to the Target Device
```bash
# Find the vendor:device id of the target
lspci -nn | grep -iE 'nvidia|amd|target-device'
# Example: 01:00.0 VGA [10de:2204]
# Check which IOMMU group this device shares (all devices in the same group must be bound together)
ls /sys/kernel/iommu_groups//devices/
# Write the udev override for every BDF in the group
echo 'SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{device}=="0x2204", \
ATTR{driver_override}="vfio-pci"' > /etc/udev/rules.d/99-vfio-pci.rules
systemctl restart udev
# Verify: Kernel driver in use should now say vfio-pci
lspci -nnk -s 01:00.0
```
**Pitfall**: If the IOMMU group contains a PCIe bridge (root port) alongside the
target device, the bridge must be written into the same override rule. Leaving it
on the native driver means the group is not fully claimed by vfio-pci and the
device will not appear in the guest.
## Step 3: Host Conflict Check
**GPU**:
```bash
# Is X or a desktop manager running on this GPU?
ps aux | grep -E 'Xorg|x11vnc|lightdm'
# Present: stop the host display server or switch host to integrated graphics
# Absent: GPU can be exclusively claimed by the guest without issue
```
**USB**:
```bash
# Find the bus and device number
lsusb
# Unbind on the host side to verify before making it permanent
echo "-" > /sys/bus/usb/drivers/usb/unbind
# After confirming the passthrough works, move the unbind into a udev rule
```
## Step 4: qm set -- Three Common Mistakes
| Mistake | Correct form | Symptom in guest |
|---------|-------------|-----------------|
| hostpci BDF points at a child function instead of the root port | `qm set -hostpci0 0000:01:00.0` | Device invisible in guest lspci |
| Missing pcie=1 | `qm set -hostpci0 0000:01:00.0,pcie=1` | GPU or NVMe runs at reduced performance or fails to initialise |
| Missing rombar=0 on a VRAM-constrained GPU | Add `rombar=0` to the hostpci line | Not required, but saves VRAM when the system is tight |
**Verify after each change**:
```bash
qm showconfig | grep hostpci
# Inside the guest:
lspci -nn | grep -i 'nvidia\|target-device'
dmesg | tail -20
```
## Three High-Frequency Failure Cases (based on typical production scenarios)
**Case 1: IOMMU groups exist but the target GPU is missing from its own group**
The host dmesg shows Intel IOMMU active and /sys/kernel/iommu_groups/ is
populated, but the group containing the target GPU only lists the PCIe bridge,
not the GPU itself. Root cause: iommu=pt was missing from the grub boot line.
The default DMA remap mode groups the GPU with its bridge; passthrough mode
splits them. Add iommu=pt, reboot, and the GPU appears in its own group.
**Case 2: GPU passthrough works but the host loses SSH access after reboot**
The host had two GPUs (integrated plus discrete). The discrete GPU was passed
through to the guest. After a host reboot the X server could not find a usable
display device because the discrete GPU was no longer available to the host.
SSH still works because it does not depend on the display. The fix is to wire
the host's display output to the integrated GPU so the host desktop does not
depend on the card that was passed through.
**Case 3: USB passthrough kills host keyboard and mouse**
The host's own keyboard and mouse were included in the USB passthrough list.
Once the guest claimed them, the host had no input devices. Connect a separate
USB keyboard to the host and remove the host's own input devices from the
passthrough configuration.
## Related Articles
- [Proxmox VM Cannot Reach the Network: Bridge vs NAT Triage Tree (P47)](/en/monitor/pve-bridge-nat-stuck)
- [Proxmox VM Slowness: CPU, Memory, and Disk IO Deep Dive (P48)](/en/monitor/pve-perf-steal-ballooning)
- [Proxmox Snapshot and Rollback Pitfalls (P50)](/en/monitor/pve-snapshot-rollback)
## Originality Statement
This article is fully original. The checklist structure is derived from the
Proxmox PCI Passthrough documentation and the Linux VFIO subsystem documentation,
expanded with production-environment failure cases. No existing article was
rewritten or repurposed.
---
## Finding Where a Proxmox VM Is Slow: A Layer-by-Layer Dig-Down
URL: https://ops.jiunotes.top/en/monitor/pve-perf-steal-ballooning.md
摘要: A slow Proxmox VE VM is not a vague performance problem; the bottleneck sits on exactly one of three planes: CPU, memory, or disk IO. This article is not a branch tree but a plane-by-plane dig-down: the CPU plane reads steal time and core overcommit plus cpuflags passthrough, the memory plane reads the ballooning threshold and the guest driver, and the disk IO plane reads raw passthrough versus virtualization-layer overhead. Cross-read host-side qm showconfig, the QEMU process, and overall host load against guest-side top, vmstat, iostat, and blktrace to pin down which layer is slow.
### Answer
Before touching anything, locate the plane: CPU, memory, or disk IO. Slowness always sits on one of them, so do not tune in the abstract. On the CPU plane watch steal time: a high st in the guest's top means the host is overcommitted and the vCPUs are not getting a physical core, so check the cores count against host load and consider cpuflags passthrough. On the memory plane watch ballooning: a min set too low lets the host pin the guest near its floor and push it into swap, so read the balloon min in qm showconfig and the guest's free. On the disk IO plane watch the virtualization layer: raw passthrough is one layer cheaper than qcow2, and when wa is high use iostat for await and blktrace for the latency distribution. Steal time is only visible inside the guest, and the host-side per-VM view on KVM is the QEMU process, so cross-read both sides.
### FAQ
Q: The guest's top shows a persistently high steal. What is taking the CPU?
A: Steal is the time the guest wanted the vCPU to run but the host withheld a physical core, so the root is host overcommit or a noisy neighbor. Steal is only readable inside the guest's top or vmstat; on a KVM host there is no per-VM steal column. On the host, pgrep the VM's QEMU process and pidstat its CPU, then read uptime and mpstat for how much host capacity is left. A persistently high steal basically confirms overcommit: lower this VM's cores, pin it to idle cores, or reduce the VM count on this host, and consider cpuflags passthrough so missing features do not slow the workload.
Q: I enabled ballooning and the VM got slower. Is ballooning at fault?
A: Usually the min is set too low. Ballooning lets the host reclaim and return guest memory on demand; with a min below what the application actually needs, the host pins the guest near that floor and the guest falls into swap, so any busy workload stutters. Read the balloon min in qm showconfig, then watch the guest's free for swap in/out. Set the min to the floor the application genuinely needs; do not squeeze it just to fit one more VM.
Q: Under the same load a VM on a raw disk is clearly faster than one on qcow2. Why?
A: The difference is virtualization-layer overhead. qcow2 pays a format-parse step on every read and write and may trigger COW and compression; raw is close to a direct write and skips that layer. For local-directory and bare-disk scenarios I default VMs to raw: I give up snapshot and compression convenience in exchange for a stable IO path. If you need snapshots, build a separate snapshot policy instead of making the data disk carry qcow2.
Q: How do I tell whether the slowness is on the host or inside the guest?
A: Cross-read. On the host, pidstat the VM's QEMU process CPU and iostat the raw disk's IO latency; inside the guest, read top, vmstat, and iostat for us, st, wa, and await. If the host QEMU process CPU is low but the guest's us is high, the guest's own application is the issue; if the host's overall st or wa is high, the bottleneck is the host or a noisy neighbor. If neither side lines up, look at the IO scheduler or the qcow2 virtualization layer eating time.
Q: The host looks idle, yet the VM is slow. How?
A: "The host is idle" does not mean "the cores or IO assigned to this VM are idle." NUMA affinity may be unset and the vCPUs may be scheduled across sockets, or several VMs may share one raw disk and a neighbor's IO has filled the queue. The host QEMU process CPU and the raw disk's await say more about where the real bottleneck sits than "host idle rate" does.
### Full Content
# Finding Where a Proxmox VM Is Slow: A Dig-Down
"The VM is slow" is the least informative sentence in a ticket: slow on CPU, memory, or
disk IO each demands a different fix, and tuning in the abstract is mostly wasted effort.
This article is not a symptom-branch decision tree. It is a **plane-by-plane dig-down**:
the CPU plane reads steal time and core overcommit, the memory plane reads the ballooning
threshold, and the disk IO plane reads raw passthrough and virtualization-layer overhead.
Each plane gets a host-side and a guest-side cross-read so that "which layer is slow" is
settled before any change is made.
I once debugged a VM that was stuck even though the host still had half its CPU free, and
the answer was that steal time had been taking all of the vCPUs' work away. I have also
debugged a ballooning min set so low that the host kept the guest pinned in swap. The
difference between a connectivity problem and a performance problem is this: **a
connectivity failure is a break, a performance problem is a queue.** Decide which queue it
is in before deciding how to shorten the queue. External references: the
[Proxmox performance tuning guide](https://pve.proxmox.com/pve-docs/performance.html), the
[Linux top man page](https://man7.org/linux/man-pages/man1/top.1.html), and the
[Linux iostat man page](https://man7.org/linux/man-pages/man1/iostat.1.html).
One tooling caveat up front, because it is the biggest Proxmox-versus-VMware trap:
**esxtop is a VMware ESXi-only tool and does not exist on Proxmox** (Proxmox VE runs on
KVM/QEMU and has none of the ESXi host toolchain). To look at a single VM's resources from
the host side, the most reliable move is to read **the QEMU process for that VM** (a
`qemu-system-x86_64` process whose command line carries `guest=vm-`), stacked on top of
the overall host load. Community tools such as `proxtop` or `virt-top` can give a prettier
per-VM view, but they are third-party additions, not part of Proxmox, so do not depend on an
extra tool during an incident. And **steal time is only visible inside the guest's
`top`/`vmstat`** - it is counted by the guest kernel itself, and there is no per-VM steal
column to read on the host. Every host-side command below follows that convention.
## A first layered health check: assign the slowness to a plane
Do not change any setting yet. Pull three readings. The host side looks at this VM's QEMU
process and the overall load; the guest side looks at itself. Only when the two sides line
up do you know where the bottleneck really is:
```bash
# host side: this VM's CPU allocation, cores, cpuflags, memory/balloon, data-disk format
qm showconfig 100 | grep -E "^cores:|^cpu:|^memory:|^balloon:|^scsi|^virtio"
# host side: find this VM's QEMU process (on KVM, the per-VM view is ~ this process)
pgrep -af "qemu-system.*100"
# host side: this QEMU process's CPU use (the closest thing to a per-VM CPU view on the host)
pidstat -p 1 5
# host side: how much host capacity is left, any cross-socket NUMA
uptime
mpstat -P ALL 1 5
# guest side: top's us / sy / wa / st columns (st = steal, the key one, only here)
top -bn1 | head -15
# guest side: vmstat's si / so / wa / st
vmstat 1 5
# guest side: iostat's await and %util (high %util + high await = a real IO bottleneck)
iostat -xz 2 3
```
Reading baseline (recognize the fields before drawing conclusions):
- the guest's `top` `st` (steal) persistently above 5 percent: the CPU plane is being
squeezed by the host, plane 1;
- the guest's `vmstat` `si/so` nonzero with `wa` spiking: the memory plane is under
pressure, plane 2;
- the guest's `iostat` `%util` near 100 with `await` clearly raised: the IO plane is
queuing, plane 3;
- all three low: the bottleneck is mostly in the application's own logic or an external
dependency, not the virtualization layer.
A judgment I hold: I read the guest's `top` and the host's QEMU process together. Reading
the guest's `top` alone makes it easy to misread "the host is not giving cores" as "the
application pegs the CPU." A high `us` and a high `st` look alike but demand opposite
fixes. Cross-reading both sides is the biggest difference between performance and
connectivity debugging.
## Plane 1: CPU - steal time and core overcommit
Steal time is a KVM-specific metric: the guest wanted the vCPU to run, but the host,
because of overcommit or a noisy neighbor, withheld the physical core, and that interval
is recorded as `st` inside the guest. **A high steal is not the guest's application; it is
the host not handing over cores.** Note: it is only counted inside the guest kernel; the
host has no per-VM steal column to read (the biggest difference from ESXi, so do not go
hunting for it the way you would with esxtop).
```bash
# host side: how many vCPUs this VM has, whether the host CPU model is passed through
qm showconfig 100 | grep -E "^cores:|^cpu:"
# host side: overall host load (confirm real overcommit: load against core count)
uptime
# host side: how much CPU this VM's QEMU process is using now (high = running, low but guest stuck = cores stolen)
pidstat -p 1 5
# guest side: confirm steal is persistent, not an instantaneous blip
top -bn1 | grep -E "^%Cpu|st"
```
How to dig further:
- the guest's `st` persistently high and the host's load-to-core ratio above 1: cores are
overcommitted. Too many vCPUs on one physical core, so everyone waits. **Lower this VM's
cores, pin it to idle physical cores (`taskset` / `numactl`), or cut the VM count on this
host** - pick one, do not leave all three untouched.
- `st` not high but `us` high and the `cpu` model not passed through: probably missing
cpuflags. Some workloads (databases, crypto libraries) probe for specific instruction
sets; KVM does not pass through the full host feature set by default, so a missing flag
routes them to a slow path. **Enable `cpu: host` or set `cpuflags` explicitly** to pass
the needed features through so the guest uses the host's real capabilities.
- `st` is an instantaneous blip and `us` is flat: a neighbor's periodic job is likely
stealing the core. Isolate it with `taskset` pinning, observe for a while, and leave the
cores alone.
I hit one (a scenario built from a typical production case): a database VM slowed down in
bursts through the night, and `top`'s `us` looked "not full," so I first blamed the
application's GC. Only after watching the `st` column did I find a neighbor's backup job
taking the physical cores for twenty minutes every hour. **The fingerprint of steal is
"periodic, in sync with a host neighbor's job"** - watching `us` alone never finds it.
## Plane 2: memory - ballooning threshold and the guest driver
Ballooning lets the host "reclaim or return" guest memory on demand: it reclaims when the
host is tight and returns when it is idle. The mechanism saves resources, but **a wrong
threshold turns the saved resources into guest stutter.**
```bash
# host side: this VM's memory cap and balloon min (the min is the key)
qm showconfig 100 | grep -E "^memory:|^balloon:"
# host side: this VM's QEMU process's actual memory use (changes as ballooning reclaims/returns)
ps -o pid,rss,vsz -p
# guest side: is swap being forced by host-side memory pressure
free
# guest side: is the ballooning driver / QGA installed (if not, the host cannot reclaim or return)
qga-ping && echo "QGA OK" || echo "QGA not responding, check guest agent install"
```
How to dig further:
- the `balloon` min set below the floor the application actually needs: the host pins the
guest to that min for long stretches, the guest is forced into swap, and any busy
workload stutters. **Raise the min to the floor the application genuinely needs**; do not
squeeze it to fit one more VM.
- the guest's `free` swap in/out persistently nonzero: the memory is being pressed. Confirm
whether ballooning is the cause: on the host, `ps` shows whether this QEMU process's RSS
is pinned near the min.
- `qga-ping` unresponsive / QGA missing: the host can neither reclaim nor return, memory
management goes one-way, and the symptom is "ballooning configured but no effect."
Install the QEMU guest agent before discussing the threshold.
A candid note: there is no universal formula for the ballooning threshold. The min depends
on the application's own memory behavior, and that part can only be set by load testing and
observation. Most of the stutter I have seen is not a mechanism problem but a min guessed
too low.
## Plane 3: disk IO - raw passthrough and virtualization-layer overhead
In local-directory and bare-disk scenarios, the disk IO bottleneck is rarely the disk
itself; it is the **virtualization-layer format of the data disk**.
```bash
# host side: this VM's data-disk format (raw or qcow2) and storage
qm showconfig 100 | grep -E "^scsi|^virtio"
# host side: IO latency on the host's raw disk / storage (iostat the raw disk, closer to the physical disk than the VM)
iostat -xz 2 3
# guest side: await and %util, judge whether the disk is queuing
iostat -xz 2 3
# guest side: for a precise latency distribution, run blktrace (costly, short window)
blktrace -d /dev/vda -o - | blkparse -i - | head -30
```
How to dig further:
- the guest's `%util` near 100 with `await` clearly raised: IO really is queuing. First
separate a slow disk from format overhead: under the same load, raw is usually a notch
faster than qcow2.
- the data disk is qcow2 and the load is sequential block writes: qcow2's COW and format
parsing eat time. **For local-directory / bare-disk scenarios that value stable IO, I
default to raw**; keep snapshot needs in a separate policy rather than making the data
disk carry qcow2.
- `await` high but `%util` not high: not queuing, probably one large IO with high latency.
Run `blktrace` to see the latency distribution and locate which segment of IO is slow.
I worked through one (a scenario built from a typical production case): a log-writing VM
moved from qcow2 to raw, and the guest's `await` fell from double digits to single digits
while the host's `%util` on the same raw disk barely changed. **The whole difference was the
qcow2 virtualization layer.** The disk did not get faster; the path got shorter.
## The three planes together: a misdiagnosis quick table
| Guest-side signal | First guess (misread) | Real plane | Where to look |
|---|---|---|---|
| `top` `st` persistently above 5 percent | the application pegs the CPU | CPU overcommit / noisy neighbor | host load + cores + QEMU process |
| `us` high but not full, periodic | application GC | cpuflags not passed through | `qm showconfig` `cpu:` |
| `vmstat` swap in/out nonzero | application memory leak | ballooning min too low | `qm showconfig` `balloon:` |
| ballooning configured but no effect | threshold not applied | QGA / driver missing | guest `qga-ping` |
| `iostat` `%util` near 100 | disk failing | real queueing | await + data-disk format |
| raw a notch faster than qcow2 | different disks | qcow2 virtualization overhead | data-disk format |
This is the "what performance slowness is most often misdiagnosed as" table in working
form. Performance tickets start as "the machine is laggy" or "the application is slow";
reading the planes backwards avoids repeatedly tuning the wrong layer.
## The question I ask before touching anything
Before I change anything I ask: **is this VM slow because the host is not handing out
resources, or because the guest is queuing on its own?** Read the guest's
`top + vmstat + iostat` against the host's QEMU process and overall host load, and which
of the three planes is queuing becomes clear. A high steal is the host's account,
ballooning is the threshold's account, a high `await` is the IO's account - the three
accounts' fixes do not overlap, and if you judge wrong, every later tweak is a guess.
A judgment I stand by: avoid overcommit if you can, and prefer raw over qcow2 (for
local-directory / bare-disk scenarios). Keep ballooning, but give the min headroom. In
performance problems, "save resources" and "keep it stable" often fight, and my order is
stability first: the few cores and bytes of memory saved do not come close to covering a
ticket about an application slowing down at 3 a.m. And one more reminder: do not hunt for
esxtop on a Proxmox host - that is an ESXi thing. On KVM, the per-VM view lives on the
QEMU process, and steal lives in the guest's `top`.
## Frequently asked questions
**Q: The guest's top shows a persistently high steal. What is taking the CPU?**
A: Steal is the time the guest wanted the vCPU to run but the host withheld a physical
core, so the root is host overcommit or a noisy neighbor. Steal is only readable inside
the guest's top or vmstat; on a KVM host there is no per-VM steal column. On the host,
pgrep the VM's QEMU process, pidstat its CPU, then read uptime and mpstat for the host's
remaining capacity. A persistently high steal basically confirms overcommit: lower this
VM's cores, pin it to idle cores, or reduce the VM count on this host, and consider
cpuflags passthrough so missing features do not slow the workload.
**Q: I enabled ballooning and the VM got slower. Is ballooning at fault?**
A: Usually the min is set too low. Ballooning lets the host reclaim and return guest
memory on demand; with a min below what the application actually needs, the host pins the
guest near that floor and the guest falls into swap, so any busy workload stutters. Read
the balloon min in qm showconfig, then watch the guest's free for swap in/out. Set the min
to the floor the application genuinely needs; do not squeeze it to fit one more VM.
**Q: Under the same load a VM on a raw disk is clearly faster than one on qcow2. Why?**
A: The difference is virtualization-layer overhead. qcow2 pays a format-parse step on every
read and write and may trigger COW and compression; raw is close to a direct write and
skips that layer. For local-directory and bare-disk scenarios I default VMs to raw: I give
up snapshot and compression convenience in exchange for a stable IO path. If you need
snapshots, build a separate snapshot policy instead of making the data disk carry qcow2.
**Q: How do I tell whether the slowness is on the host or inside the guest?**
A: Cross-read. On the host, pidstat the VM's QEMU process CPU and iostat the raw disk's IO
latency; inside the guest, read top, vmstat, and iostat for us, st, wa, and await. If the
host QEMU process CPU is low but the guest's us is high, the guest's own application is the
issue; if the host's overall st or wa is high, the bottleneck is the host or a noisy
neighbor. If neither side lines up, look at the IO scheduler or the qcow2 virtualization
layer eating time.
**Q: The host looks idle, yet the VM is slow. How?**
A: "The host is idle" does not mean "the cores or IO assigned to this VM are idle." NUMA
affinity may be unset and the vCPUs may be scheduled across sockets, or several VMs may
share one raw disk and a neighbor's IO has filled the queue. The host QEMU process CPU and
the raw disk's await say more about where the real bottleneck sits than "host idle rate"
does.
## Related
- [Linux CPU monitoring: the five top fields](linux-cpu-monitor.md) - the general method for reading top's columns inside a guest
- [Linux disk IO monitoring](linux-disk-io-monitor.md) - reading await, %util, and queue depth in full
- [Linux memory monitoring](linux-memory-monitor.md) - the baseline for judging swap and memory water level
- [Proxmox VM cannot reach the network: a triage tree](pve-bridge-nat-stuck.md) - the sister piece: the connectivity plane (the opposite of slowness)
**Originality note**: Every command, the layered read method, and the case studies in this
article were compiled by the author from performance troubleshooting on Proxmox VE
(KVM/QEMU) in production. Commands are labeled for host-side versus guest-side context.
esxtop belongs to VMware ESXi and does not exist on Proxmox; all host-side per-VM readings
here fall back to the QEMU process, and steal is read in the guest's top. The case studies
are built from typical production scenarios and contain no real company names, IP
addresses, or timelines.
## Related Articles
- [Proxmox LXC Stuck Mounting Root Filesystem: Start Failure Triage](pve-lxc-rootfs-mount-stuck.md)
---
## Proxmox Snapshot and Rollback Deep Dive: qcow2 COW Mechanism, Chain Compaction, Rollback and Capacity Reclamation
URL: https://ops.jiunotes.top/en/monitor/pve-snapshot-rollback.md
摘要: A deep dive into Proxmox VE snapshot and rollback behaviour for local directory and raw-disk environments. qcow2 has a built-in copy-on-write layer chain: each snapshot adds one COW layer, reads walk the chain from newest to oldest, and deleting a middle layer triggers an automatic compaction merge. Raw format has no built-in snapshot support, so snapshots must go through the host filesystem layer (btrfs subvolume snapshot, LVM snapshot) or a manual qemu-img base layer. This article separates the two paths clearly and explains why capacity never shrinks after a rollback and how to reclaim it.
### Answer
The snapshot mechanism diverges completely depending on the disk format, so the first step is always to check which format the VM's data disk actually uses. Run qm showconfig and look at the format field for the disk in question. If it is qcow2, Proxmox's built-in COW snapshot is available: each qm snapshot create appends a COW layer to the same file, reads walk the chain from newest to oldest, and writes check the COW mapping before deciding where to land. The more layers in the chain, the higher the random-read latency. Deleting a middle layer triggers an automatic compaction merge, which is a write-heavy operation and will cause IO spikes, so schedule it for a low-traffic window. Rollback is a pointer switch: the COW pointer moves to the target snapshot and all layers after it are logically discarded, but the physical blocks remain in the qcow2 file. The file does not shrink. To reclaim capacity you must run qemu-img convert to repack the file while the VM is stopped. If the disk is raw format, Proxmox has no built-in snapshot path. The host filesystem must provide it: btrfs subvolume snapshot on a btrfs mount, or LVM snapshot on an LVM volume. On ext4 or xfs without btrfs or LVM, the only option is a manual qemu-img base layer created with qemu-img create -b, which is a qcow2 file even if you name it .raw.
### FAQ
Q: Why does a qcow2 VM get progressively slower after many snapshots are taken? How do I clean up without losing data?
A: qcow2 snapshots are COW layers appended to the same file. Each layer adds one more hop to the read path, so random-read latency grows linearly with the number of layers in the chain. To clean up, delete snapshots from oldest to newest one at a time with qm snapshot delete. When you delete a middle layer, qcow2 automatically merges that layer into the one below it. The merge is a write operation and will cause noticeable IO spikes, so schedule it for a low-traffic window. Do not delete a layer while the VM is running a heavy workload.
Q: I rolled back to a snapshot but the disk capacity did not decrease. Why?
A: Rollback in qcow2 is a pointer switch. The COW pointer moves to the target snapshot and all layers after it are logically discarded, but the physical blocks that were in those layers remain in the qcow2 file. The file size does not change. To actually reclaim space, stop the VM and run qemu-img convert -f qcow2 -O qcow2 on the file to repack it. The repacked file will be sized to the actual data volume. On a large disk this can take a long time, so plan ahead.
Q: Can I use Proxmox's built-in snapshot button on a raw-format disk?
A: No. Raw format has no built-in COW layer mechanism. If the host storage is btrfs, Proxmox's snapshot button on a raw disk actually invokes a btrfs subvolume snapshot under the hood, which is a different mechanism from qcow2's COW layer. If the host is ext4 or xfs, there is no native filesystem snapshot available, and the only option is to create a manual base layer with qemu-img create -f qcow2 -b . Note that this base layer file is in qcow2 format (the -b backing-file flag is a qcow2 feature), not raw.
Q: Is rolling back dangerous? Could it wipe data that was not covered by any snapshot?
A: In qcow2 there is no such thing as "data not covered by a snapshot." Every write goes through the COW chain, and every snapshot is a node on that chain. Rolling back moves the COW pointer to the target node and discards all layers after it, so the VM sees the complete state at the moment of that snapshot. The real risk is a host-side process (a backup job, for example) that has the qcow2 file open while you are rolling back, which can cause a file lock conflict or data inconsistency. Before rolling back, confirm no other process has the file open with lsof.
Q: I used a btrfs snapshot on a raw disk but after rollback the data was inconsistent. What went wrong?
A: The most common cause is that the host storage was actually LVM, not btrfs. Proxmox's snapshot button on an LVM-backed raw disk invokes an LVM snapshot, not a btrfs subvolume snapshot. LVM snapshots have a fixed size; when the snapshot space fills up, the snapshot silently transitions to read-only mode, and rolling back to a read-only snapshot produces data inconsistency. Confirm the underlying storage with lvdisplay before assuming the snapshot type.
### Full Content
# Proxmox Snapshot and Rollback Deep Dive
The word "snapshot" in Proxmox means something fundamentally different depending
on the disk format, and mixing the two is the most common source of
misconfiguration in local-directory and raw-disk environments. qcow2 has a
built-in COW layer; raw does not. That single difference determines how you
take a snapshot, what rollback actually does, and how you reclaim capacity.
External references:
[Proxmox Snapshot Documentation](https://pve.proxmox.com/pve-docs/chapter-snapshot.html),
[QEMU qcow2 Format Specification](https://www.qemu.org/docs/master/user/interop.html),
[btrfs Snapshot Mechanism](https://btrfs.wiki.kernel.org/index.php/Snapshots).
## First: Determine the Format
```bash
qm showconfig | grep -E 'scsi|virtio'
# Look at the format field in the output:
# format=qcow2 -> built-in COW snapshot, use qm snapshot
# format=raw -> no built-in snapshot, check host storage layer
# /dev/sdX -> raw block device, snapshot must come from host layer
```
## qcow2 Built-in COW Mechanism
qcow2 files contain a chain of COW layers internally. Each
`qm snapshot create` appends one COW mapping layer to the file header:
```
Write path (with snapshots):
guest writes to LBA X
-> check COW mapping: which COW layer owns LBA X?
-> write to the newest COW layer (copy-on-write)
-> read path: walk from newest COW layer backwards until data is found
Read path (with N snapshots):
at most N+1 layers to check (N COW layers + 1 base layer)
longer chain = higher random-read latency
```
**Why it gets slower**: COW layer count grows linearly, and every IO must walk
the chain. A 30-layer chain has roughly 30x the random-read overhead of a 1-layer
chain.
**Compaction (merge)**: `qm snapshot delete ` on a middle layer
triggers the qcow2 engine to merge that layer's data into the layer below it.
The merge is a write-heavy operation and will cause visible IO spikes. Schedule
it for a low-traffic window.
```bash
# Check current COW layer count
qm dump | grep snapshot
# Confirm no other process has the qcow2 file open
lsof
# Delete old snapshots (oldest first, one at a time)
qm snapshot delete
```
## Rollback: Pointer Switch, No Capacity Reclaim
```bash
qm snapshot revert
# Semantics: COW pointer moves to snapname
# All COW layers after snapname are logically discarded
# Physical blocks in the qcow2 file remain; file size does not change
```
**Why capacity does not shrink**: qcow2 files are either pre-allocated or
sparse-grown. Rollback is a logical pointer switch, not a physical block
deletion. To actually reclaim space:
```bash
# VM must be stopped
qm stop
# Repack in place (slow on large disks, plan ahead)
qemu-img convert -f qcow2 -O qcow2
# Update the disk path in qm config to point to the new file
```
## Raw Format: No Built-in Snapshot, Two Alternative Paths
**Path A: btrfs subvolume snapshot (btrfs host storage)**
When the raw disk lives on a btrfs mount, Proxmox's snapshot button invokes a
btrfs subvolume snapshot:
```bash
# Host-side
btrfs subvolume snapshot
# Proxmox UI snapshot on raw disk actually calls this underneath
```
btrfs snapshots are CoW and are O(1) to create (metadata only). Rollback is also
a pointer switch. Long btrfs snapshot chains have the same read-amplification
problem as qcow2. Delete with `btrfs subvolume delete`.
**Path B: qemu-img manual base layer (no btrfs available)**
On ext4 or xfs hosts without btrfs or LVM, raw disks have no native snapshot
support. The only option is a manual base layer:
```bash
qm stop
# Use the current raw disk as the backing file (qcow2 required; raw does not
# support the -b backing-file flag)
qemu-img create -f qcow2 -b 1G
# Rollback = switch back to base; all writes after base are discarded
# Capacity reclaim = delete base and write back to the original raw disk
```
**Note**: the `base` file created with the `-b` flag is in qcow2 format, not
raw. Do not name it `base.raw` or it will mislead the next operator.
## Three High-Frequency Failure Cases (based on typical production scenarios)
**Case 1: 30 COW layers, P99 random-read latency jumped from 2 ms to 28 ms**
A qcow2 data disk VM accumulated 30 snapshots without compaction. Application
P99 latency went from 2 ms to 28 ms. Resolution: during a low-traffic window,
delete snapshots from oldest to newest one at a time with `qm snapshot delete`.
Each deletion triggers an automatic merge into the layer below. Total merge time
for 30 layers was approximately 2 hours. Notify the business team about expected
latency spikes during the merge window.
**Case 2: After rollback the qcow2 file is 500 GB but actual data is only 120 GB**
Rolled back to a snapshot from 30 days ago. The qcow2 file is 500 GB because it
contains all 30 days of COW increments, but the logical data volume is only
120 GB. Resolution: stop the VM and run `qemu-img convert -f qcow2 -O qcow2`
to repack. The repacked file shrinks to approximately 130 GB. Repack time was
about 40 minutes for the 500 GB source file.
**Case 3: btrfs snapshot on a raw disk on ext4, data inconsistent after rollback**
Root cause: the host storage was actually an LVM volume, not btrfs. Proxmox's
snapshot button on an LVM-backed raw disk invokes an LVM snapshot, not a btrfs
subvolume snapshot. LVM snapshots have a fixed size; when the snapshot space
fills up, the snapshot silently transitions to read-only mode. Rolling back to
a read-only LVM snapshot produces data inconsistency. Confirm the underlying
storage type with `lvdisplay` before assuming the snapshot mechanism.
## Related Articles
- [Proxmox VM Cannot Reach the Network: Bridge vs NAT Triage Tree (P47)](/en/monitor/pve-bridge-nat-stuck)
- [Proxmox VM Slowness: CPU, Memory, and Disk IO Deep Dive (P48)](/en/monitor/pve-perf-steal-ballooning)
- [Proxmox VM Device Passthrough Hardening Checklist (P49)](/en/monitor/pve-passthrough-iommu)
- [Proxmox VM Migration Pitfalls (P51)](/en/monitor/pve-live-migration)
## Originality Statement
This article is fully original. The qcow2 COW mechanism and btrfs/LVM snapshot
layer differences are explained for local directory and raw-disk scenarios.
Decision paths and capacity reclamation procedures are drawn from the author's
production environment experience and are not a rewrite of any existing article.
---
## Defining SLOs and Burning the Error Budget: A Reliability-Policy Playbook
URL: https://ops.jiunotes.top/en/monitor/slo-definition-error-budget-policy.md
摘要: First-person playbook for defining SLOs, computing request-based error budgets, multi-window multi-burn-rate PromQL alerting, release gates, and cross-AZ SLO decomposition.
### Answer
I treat SLOs as the single number that settles release debates. This playbook covers how I derive a 30-day availability target from four weeks of baseline data, convert it into a request-based error budget, gate feature releases on remaining-budget bands, and alert on multi-window multi-burn-rate PromQL so I get paged hours before exhaustion. Decision rights are assigned while calm, not during the incident.
### FAQ
Q: SLO vs SLA — what's the difference, and which do I set first?
A: The SLA is the customer-facing contract with financial penalties; the SLO is the internal target I hold the team to. I set the SLO first and always tighter — if the SLA says 99.5%, I run a 99.9% SLO internally. The internal budget exhausts first and forces behavior change before a customer can claim a credit.
Q: How do I pick an SLO target (99.9 vs 99.99) without guessing?
A: I collect four weeks of real SLI data on the candidate metric, then set the target slightly below the service's actual baseline performance. The target must be achievable enough that the budget is spendable but tight enough that spending it means something. I re-tune quarterly based on real burn.
Q: What should I do the moment my error budget hits zero?
A: The policy pre-decides it: feature releases freeze, and the team's capacity shifts to reliability work — fixing the fault that caused the burn. Security and recovery changes still ship through a pre-agreed exception path with a named approver and a log entry. Nobody improvises this decision at 2 a.m.
Q: Why use multi-window, multi-burn-rate alerts instead of one threshold?
A: A single availability threshold is lagging — by the time you cross it, you already burned budget you cannot get back. A 1-hour window at 14.4x catches fast incidents early; a 6-hour window at 6x confirms slow burns and filters transient blips. Requiring both conditions fires earlier on real incidents and far less noise on spikes.
### Full Content
# Defining SLOs and Burning the Error Budget: A Reliability-Policy Playbook
Every quarter in my team there is the same argument: the product side wants the new feature shipped this week, and I argue that every change is a potential incident. Without a shared metric, that argument is decided by whoever is louder or who was not paged last night. What finally fixed it was not a process deck — it was arithmetic. I set SLOs, converted them into error budgets, and wrote down in advance what happens at each budget level. This post is that playbook, written the way I actually run it in production.
## 1. SLI, SLO, SLA: the words I refuse to mix up
I keep the definitions rigid, because half of the policy failures I have seen are just people using the wrong word:
- **SLI** is a user-perceived measurement: successful requests divided by valid requests, or the fraction of requests finishing under 0.5s.
- **SLO** is the target I put on that SLI over a window: 99.9% of requests succeed in a rolling 30 days.
- **Error budget** is the complement: 1 − SLO. For 99.9%, that is 0.1% of requests allowed to fail per 30 days.
- **SLA** is the customer contract. Missing it costs us money.
The discipline that matters: **my SLO is always one notch tighter than the SLA.** We commit 99.5% to enterprise customers; internally I run a 99.9% SLO. The internal budget therefore exhausts first, behavior changes first, and we have room to recover before a customer can claim a credit. The moment a team only watches the SLA, the budget mechanism stops working — the gap quietly closes and the SLA becomes a firefight instead of a forecast. I have seen it happen, and it is ugly.
## 2. Pick the SLI the user actually feels
I choose SLIs from the user journey, never from server internals. CPU at 90% means nothing to a customer; a failed checkout does. In my services I use:
- **Availability SLI** for request/response APIs: the fraction of non-5xx responses among valid requests.
- **Latency SLI** for user-facing paths: the fraction of requests under a threshold, read off a histogram bucket.
- **Freshness SLI** for data pipelines: records updated within N minutes.
- **Through-deadline SLI** for batch jobs: jobs that finish before their deadline.
I always measure as close to the user as I can — at the load balancer or the edge, not inside the service — because internal health and "the user's action succeeded" are not the same thing. The SLI definition also fixes what counts as a *valid* request: retries, health-check scrapes, and known-bad payloads are excluded up front, so nobody re-litigates the denominator after an incident.
## 3. Setting a target I can actually measure
Picking "three nines" by vibes is the most common mistake I have caught in other teams' SLOs. My method is five steps:
1. Pick the two or three user journeys that carry the most revenue and user expectation — in our case, login, search, and checkout.
2. Choose the SLI type that matches each journey.
3. Collect four weeks of baseline SLI data before writing the number.
4. Set the target slightly below the steady-state baseline, so the team has budget to spend but still has to care.
5. Document how maintenance windows, retries, and partial failures are treated, then review quarterly.
Checkout at 99.9% is my flagship SLO. The baseline showed about 99.95% monthly availability, so 99.9% gives us a real, spendable budget. A target nobody ever touches is a decoration; a target the team trips over every month is a blame machine. Both tell me the number is wrong, and I fix it at the quarterly review.
The crucial acceptance test: two different engineers must be able to compute the same SLO value from the same telemetry. If the definition needs folklore to interpret it, I rewrite it.
## 4. Computing the error budget: time-based vs request-based
The time-based budget is the familiar one: 99.9% over a 30-day month is about 43.2 minutes of allowed downtime. I avoid it for request services because it treats a 3 a.m. outage and a peak-hour outage identically, which is not how the business feels it. The request-based budget is fairer: it is the count of failed requests allowed in the window, and a peak-hour failure naturally burns more of it.
For latency SLOs, the request-based form falls out of histogram buckets. The fraction of requests under 0.5s, over the 30-day window:
```promql
# Fraction of checkout requests completing under 0.5s, 30-day window
sum(rate(http_request_duration_seconds_bucket{route="/checkout", le="0.5"}[30d]))
/
sum(rate(http_request_duration_seconds_count{route="/checkout"}[30d]))
```
The error budget is 1 minus that ratio. The precondition is that I can distinguish *good* requests from *valid* requests in my instrumentation — if my counters cannot tell them apart, I fix the exporter before I set the target, because an SLO you cannot measure is not an SLO. Batch jobs and pure reachability probes are the cases where time-based budgets still make sense; I use those deliberately, not by default.
## 5. Burn-rate alerts: turning a lagging number into an early warning
Watching "availability fell below 99.9%" is a lagging indicator — by the time it fires, the budget is already damaged. Burn-rate alerting watches *how fast* the budget is being consumed, which is the Google SRE Workbook's core idea ([sre.google/workbook/alerting-on-slos](https://sre.google/workbook/alerting-on-slos/)). The Workbook and Robust Perception's SLO dashboard material are worth a read if you want the full theory; here is the implementation I actually run in Prometheus ([prometheus.io/docs](https://prometheus.io/docs/)).
The math behind my thresholds: my SLO window is 30 days = 720 hours. An observed 1-hour error rate *e* burns `e × 720` times the budget in that window. I want to page at 14.4x burn on the fast window (which would exhaust the budget in about two days) and at 6x on a slow 6-hour window (about five days of runout). The per-window thresholds are therefore:
- 1h window, 14.4x: `0.001 × 14.4 / 720 = 2×10⁻⁵`
- 6h window, 6x: `0.001 × 6 / 120 = 5×10⁻⁵`
Requiring **both** conditions is what makes it production-grade: a one-hour blip that recovers does not fire the slow window; a slow degradation that is still gentle after six hours does not fire the fast window. The rule I run:
```yaml
- record: slo:checkout:availability:30d
expr: |
(sum(rate(http_requests_total{job="checkout-api", status!~"5.."}[30d]))
/
sum(rate(http_requests_total{job="checkout-api"}[30d])))
- alert: SloBurnRateCritical
expr: |
(1 - (sum(rate(http_requests_total{job="checkout-api", status!~"5.."}[1h]))
/
sum(rate(http_requests_total{job="checkout-api"}[1h]))))
> (0.001 * 14.4 / 720)
and
(1 - (sum(rate(http_requests_total{job="checkout-api", status!~"5.."}[6h]))
/
sum(rate(http_requests_total{job="checkout-api"}[6h]))))
> (0.001 * 6 / 120)
for: 10m
labels:
severity: critical
team: checkout
annotations:
summary: "checkout-api burning 30d error budget at >=14.4x (1h) confirmed at 6x (6h)"
```
The recording rule feeds the dashboard and the release-gate checks; the alert pairs with my alertmanager-noise-reduction tuning so it pages a human instead of filling a channel. In one incident, a bad dependency version pushed 5xx rates up to 0.8% for about four hours during off-peak. A single "availability < 99.9%" alert would have fired around midnight, when nobody was looking. The 14.4x fast window fired in the first half hour, and we rolled back while the burn was still cheap.
## 6. The release gate: what each budget band means
This is the part that settles the release debate, because every band is decided in calm, not during an incident. I track remaining 30-day budget and operate in four bands:
| Remaining 30d budget | Release posture | Who decides |
|---|---|---|
| > 50% | Ship normally, run experiments, do risky migrations | Eng manager |
| 25–50% | Caution: two-reviewer sign-off, smaller deploys | Team lead + me |
| 0–25% | Restricted: feature work paused, reliability work only | Me (SLO owner) |
| 0% (exhausted) | Full freeze; all capacity goes to reliability | Pre-named exception approver |
Exhaustion is not a total standstill. Security fixes and changes that *restore* reliability keep flowing, but only through the pre-agreed exception path: one named approver (not the person being paged), a written log entry, and a review of whether the target itself was miscalibrated. This is essentially a standing, metric-driven code freeze, and it is far cheaper than the ad-hoc freeze you declare after a P0. If a band feels controversial, I say: the policy is only as good as the calmest moment in which it was written.
## 7. Decomposing SLOs across zones and services
I do not set one global SLO and call it done, because it hides *where* the budget is going.
**Multi-AZ.** In our production the checkout API runs in three availability zones. The global SLO is 99.9% per 30 days; I derive per-AZ SLIs (each zone's own good/valid ratio) and allocate each zone's error budget proportionally to its traffic share. A zone that carries 34% of traffic also owns 34% of the budget, and its burn-rate alert threshold scales with that share. The rule I act on: if one zone burns more than 3x its proportional share, that is a zone-level incident — even if the global SLO still looks green. This caught an AZ-level NIC firmware problem last year that the global dashboard would have waved through for days.
**Multi-service.** Checkout is an end-to-end SLO owned by me; the individual hops (cart, inventory, payment, notification) get service SLOs derived from the end-to-end budget, split by each hop's measured contribution to failures and latency. The hard constraint: the per-service targets must *multiply* to something achievable. If every service promises 99.99%, the chain is still fine — but promising 99.9% per hop across six hops gives an end-to-end of roughly 99.4%, which silently under-delivers. I check the product of hop SLOs against the end-to-end target before signing off, and I treat any hop whose budget is consistently untouched as a candidate for a tighter target.
For the latency side of the chain, per-hop SLOs come from the same histogram-bucket technique as in Section 4, with the threshold set per hop from its p95 budget share.
## 8. Discipline: how the SLO system rots, and how I stop it
The SLO machinery decays quietly. The patterns I have all seen: an SLI counter renamed in a refactor and the budget silently inflated; a threshold set in January still running in August; exceptions becoming the default path. My standing discipline:
- **Daily**: I check the burn-rate dashboard and remaining budget; any band change is noted.
- **Weekly**: any service in the caution or restricted band gets a postmortem-style review and assigned reliability work.
- **Before every deploy**: the SLI definitions and their instrumentation are unchanged — I keep the recording rule outputs under version control precisely so a broken counter is a diff, not a mystery.
- **Quarterly**: I re-measure the baseline and re-set the target. Untouched budget means tighten; monthly exhaustion means either loosen the target or fund the reliability work the target implies.
- **Red lines**: the SLA is never the only number we watch; every exception has a named approver and a log; nobody may quietly widen an SLI definition to "fix" the budget.
## FAQ
**Q: SLO vs SLA — which do I set first?**
A: The SLO first, and tighter. The SLA is the external contract with money attached; the SLO is the internal number that drives behavior. Run the SLO one notch inside the SLA so the internal budget exhausts first and gives you time to act before a customer can claim anything.
**Q: 99.9 or 99.99 — how do I pick without guessing?**
A: Four weeks of baseline data, target set slightly below the measured steady state, then re-tune quarterly from actual burn. The target should be tight enough that spending the budget means something and achievable enough that the team is not tripping over it monthly.
**Q: What happens the moment the budget hits zero?**
A: The policy pre-decides it: feature work freezes, capacity shifts to reliability work, and only the pre-agreed exception path (security fixes, recovery changes, one named approver, written log) ships. Nobody improvises that call in the middle of the night.
**Q: Why not just one availability threshold alert?**
A: One threshold is lagging — it fires after the budget is already damaged. My two-window design (1h at 14.4x **and** 6h at 6x) pages on fast incidents within the first hour, confirms slow burns without firing on transient blips, and matches the budget language the release gate actually uses.
## Related articles
- [Distributed Tracing and Span Sampling in Practice](distributed-tracing-span-sampling.md)
- [eBPF Observability](ebpf-observability.md)
- [Alertmanager Noise Reduction](alertmanager-noise-reduction.md)
---
## SSH Hardening: 5-Layer Defense (Key Auth, Fail2ban, AllowUsers, Ports, PAM)
URL: https://ops.jiunotes.top/en/monitor/ssh-hardening.md
摘要: SSH hardening in 5 layers: key auth only, block root login, non-standard port, Fail2ban jail, AllowUsers whitelist, PAM + MFA. Avoid self-lockout with the 3-step safety workflow and 5 sshd_config traps.
### Answer
SSH hardening priority: ① keys only (`PasswordAuthentication no`) ② block direct root (`PermitRootLogin no`) ③ move to a non-standard port ④ Fail2ban jail ⑤ AllowUsers whitelist. 5 steps cut the brute-force window from minutes to hours. Non-negotiable safety rule: keep a second SSH session open, add another machine's key first, test new `sshd_config` with `ssh -v` before closing the old session.
### FAQ
Q: Will `PermitRootLogin no` lock me out?
A: Yes, if root is your only login path. Use a regular sudo-capable user first, add their key to that user's `authorized_keys`, verify they can log in, then apply `PermitRootLogin no`. Keep a second session open until you've tested the change.
Q: Is moving off port 22 actually useful?
A: Not a security control on its own — a scan finds the real port in seconds. But it eliminates ~95% of noise from untargeted scanners, which reduces the load on your fail2ban jail and your logs. Worth it if the ops cost is low.
Q: Which Fail2ban jails should I enable?
A: At minimum `sshd` with `bantime=1h`, `findtime=10m`, `maxretry=3`. Consider `sshd-ddos` (defense against slow scanners), `sshd-pam` (PAM-level failures), `nginx-botsearch` if Nginx is in front.
Q: What's the actual difference between AllowUsers and authorized_keys?
A: `authorized_keys` is per-user key material; `AllowUsers` is an sshd_config-level whitelist that also blocks users from being added to any group that would let them in. Both are needed — one without the other is a half-measure.
Q: Should I disable PAM entirely?
A: Only if you're using pure SSH key auth with no sudo/MFA integration. Most distros need PAM for sudo. If you need PAM, configure `sshd_config` to require key auth at the SSH layer *before* PAM evaluates anything.
### Full Content
# SSH Hardening: 5-Layer Defense
SSH on port 22 is the most-scanned port on the internet. Your server sees an average of thousands of attempts per day, not hundreds of millions — the volume comes from broad background scanning, and Fail2ban's job is to make that background noise stop mattering. The five layers below compound: each one cuts the attack surface for the next.
The 5 layers:
1. **Authentication** — keys only, no password
2. **Access control** — no root, whitelist users
3. **Exposure** — non-standard port, host-based firewall
4. **Logging** — verbose logs, Fail2ban, alerting
5. **Host** — PAM, MFA, agent-forwarding, host key rotation
Do them in order. Each layer assumes the previous is done.
## Safety Workflow: The 3 Steps That Save You
Every hardening failure I've seen traces back to skipping this. Memorize it:
**Step 1 — keep a second session open.** Never log in, harden, and close the only session you have. Two terminals, two SSH sessions. If the second fails, the first is still live.
**Step 2 — add another machine's key first.** Before changing any `sshd_config`, `scp` a key from a different machine to this host's `~/.ssh/authorized_keys` for the same user. If you somehow get locked out, this key is your off-ramp.
**Step 3 — test with `ssh -v` before closing.** After changing config, open a third terminal and try to log in with the new settings. `ssh -v` shows the whole handshake — if it succeeds, you can safely close the old sessions.
The failure mode without this: you close the only session that works, then find out you've locked yourself out. Cloud console (VNC / serial) is the escape hatch, but not every server has one, and not every datacenter gives you one.
## Layer 1: Authentication (Highest Priority)
Everything else is decoration without this. Two settings in `sshd_config`:
```
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
ChallengeResponseAuthentication no
UsePAM no # if you don't need sudo/PAM; else: yes
```
Test before reload:
```bash
sshd -t # syntax check
sudo systemctl reload sshd # hot-reload, don't restart
```
**The three settings that look similar and mean different things**:
- `PasswordAuthentication no` disables password logins for SSH.
- `KbdInteractiveAuthentication no` disables the interactive keyboard challenge (some distros use this for password auth via PAM).
- `ChallengeResponseAuthentication no` is the older name for `KbdInteractiveAuthentication` — keep both set to `no` on older OpenSSH versions.
Leaving any of them at default (or missing them in older OpenSSH) means password auth is still on. This is the single most common misconfiguration.
### Key Management Basics
```bash
# Generate an Ed25519 key (modern default, faster, shorter)
ssh-keygen -t ed25519 -C "user@machine" -f ~/.ssh/id_ed25519
# Deploy the public key to the server
ssh-copy-id user@server
# Or manually:
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
```
**`~/.ssh` permissions matter.** If they're wrong, SSH refuses:
```bash
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
```
Ownership matters too — must be owned by the user, not root, not a group:
```bash
chown -R user:user ~/.ssh
```
Common trap: rsync from another machine without `--preserve-perms`, and `~/.ssh` ends up `755`. Login will silently fail with `Permission denied` — check `sshd` debug logs:
```bash
sudo journalctl -u ssh -n 50 --no-pager | grep -i 'auth\|refuse'
```
## Layer 2: Access Control
Three settings that look similar and are all necessary.
**Block direct root login:**
```
PermitRootLogin no
```
Alternatives if you truly need root access:
- `PermitRootLogin prohibit-password` — root login allowed but only via key
- `PermitRootLogin forced-commands-only` — root only allowed with a specific command (e.g., a restricted admin SSH key)
Both are still weaker than `no`. Prefer `no` + sudo for regular users.
**Deny common bad guys (defense in depth):**
```
DenyUsers nobody daemon bin sync man news uucp ftp
```
Or the inverse — a denylist of known-bad usernames that scanners try:
```
DenyUsers root admin test guest ubuntu@10.0.0.*
```
**AllowUsers whitelist (strongest form):**
```
AllowUsers alice@10.0.0.0/24 bob@192.168.1.0/24
```
Note the `user@source` syntax — this restricts by both user *and* source IP range. A user from the wrong subnet can't log in even with a valid key. This is the piece people miss: `AllowUsers` alone without source restriction still allows anyone in the world to try.
## Layer 3: Exposure (Port + Network)
### Non-Standard Port
Change port 22 to something less common:
```
Port 2222
```
Update the firewall at the same time:
```bash
# ufw
sudo ufw allow 2222/tcp && sudo ufw deny 22/tcp
# firewalld
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --permanent --remove-port=ssh # or 22/tcp
sudo firewall-cmd --reload
# nftables / iptables
sudo iptables -A INPUT -p tcp --dport 2222 -m state --state NEW -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j DROP
```
**Reality check on port change**: it doesn't stop a determined attacker (nmap finds the port in seconds). What it does is eliminate ~95% of background noise. Measure with Fail2ban logs — after changing ports, you'll typically see a 95%+ drop in blocked IPs.
**Cost**: bastion hosts, VPNs, monitoring, and CI/CD pipelines all need updating. Do this last among the five layers — after key auth, root blocking, and Fail2ban are in place.
### Firewall at the Network Layer
Before `sshd` sees the connection, the firewall should drop it. This is separate from port hardening — even a port-22 server behind a firewall is exposed to the SSH handshake.
**Allow only known sources, if possible:**
```bash
# ufw — restrict SSH to your office IP and bastion
sudo ufw allow from 203.0.113.0/24 to any port 2222 proto tcp
sudo ufw allow from 198.51.100.5 to any port 2222 proto tcp # bastion
sudo ufw deny 2222/tcp # deny others
```
If you can't restrict sources, restrict protocols and rates at the firewall:
```bash
# Limit new SSH connections per IP
sudo iptables -A INPUT -p tcp --dport 2222 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 2222 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 -j DROP
```
This drops the 6th new connection from any IP within 60 seconds. Legitimate users with 2-3 connections per minute won't notice; scanners will get blocked before reaching sshd.
## Layer 4: Logging + Fail2ban
### Verbose Logging
```
LogLevel VERBOSE
```
The four `LogLevel` values in practice:
- `QUIET` — useless for security
- `ERROR` — misses pre-auth failures (bad)
- `INFO` — catches most auth failures (default, okay)
- `VERBOSE` — captures everything, including pre-auth probes (recommended)
`VERBOSE` is chatty — expect more disk. On a busy server, ship logs off-box:
```bash
# [systemd](https://www.freedesktop.org/software/systemd/man/latest/)-journal-remote, fluentd, rsyslog forward, etc.
sudo systemctl enable systemd-journal-remote
```
### Fail2ban Setup
```bash
sudo apt install fail2ban # Debian/Ubuntu
sudo dnf install fail2ban # RHEL/Fedora
```
Configure the SSH jail — extend defaults:
```ini
# /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 2222
filter = sshd
backend = systemd
mode = aggressive # bans on pre-auth activity too
bantime = 1h
findtime = 10m
maxretry = 3
```
The 5 Fail2ban jails worth enabling:
| Jail | Purpose | When to enable |
|---|---|---|
| `sshd` | Standard SSH brute force | Always |
| `sshd-ddos` | Slow scanners / DDoS probes | Always on internet-facing |
| `sshd-pam` | PAM-level auth failures | If `UsePAM yes` |
| `nginx-botsearch` | Nginx bot scanning | If Nginx in front |
| `recycler` | Cleanup of stale ban entries | Always |
Watch fail2ban's own log — a healthy jail bans IP ranges, not just IPs:
```bash
sudo journalctl -u fail2ban -n 50 --no-pager
sudo fail2ban-client status sshd
```
**Anti-lockout guardrail**: put your bastion's IP on the `ignoreip` list. If Fail2ban is misconfigured and starts banning you, this is your escape:
```ini
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 203.0.113.0/24 198.51.100.5
```
## Layer 5: Host-Level Hardening
### PAM
`sshd` can either use PAM (`UsePAM yes`) or not. Most distros default to `yes` because sudo integrates with PAM.
If you want pure key auth with no PAM involvement:
```
UsePAM no
```
This is the cleanest config. Downside: you lose sudo integration unless sudo itself talks directly to SSH agent. On most setups, this works because sudo queries the PAM modules directly, not through sshd.
If you must use PAM, configure `/etc/pam.d/sshd` carefully — disable modules that do password auth even when the user claims key auth:
```
auth required pam_nologin.so
# auth optional pam_permit.so # DO NOT ENABLE
# auth sufficient pam_unix.so # DO NOT ENABLE (allows password fallback)
```
### MFA (Optional but Recommended)
Google Authenticator via PAM:
```
# /etc/pam.d/sshd
auth required pam_google_authenticator.so nullok
```
`sshd_config`:
```
ChallengeResponseAuthentication yes
KbdInteractiveAuthentication yes
```
This is the one case where you *want* `KbdInteractiveAuthentication` enabled — it's what serves the one-time code prompt. If you enable MFA, add `Match Group` restrictions so only MFA-registered users are prompted.
### Agent Forwarding
If you enable `AllowAgentForwarding yes`, a user with key access on this host can use their SSH agent from their laptop. That's a lateral-movement risk. Disable unless needed:
```
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
```
### Host Key Rotation
Every 90 days, rotate host keys. Attackers who phish a private key from the client's `known_hosts` cache (or compromise a workstation) can impersonate your server. Rotate and force re-fingerprint:
```bash
ssh-keygen -f /etc/ssh/ssh_host_ed25519_key -N "" -t ed25519
sudo systemctl restart sshd
```
Clients will need to re-accept the fingerprint. Announce the change via your change management system before executing.
## 5 Common Self-Lockout Traps
**Trap 1: Changed sshd_config, closed the only session, can't get back in.**
- Fix: cloud console (VNC / serial). If no console, boot to rescue mode or mount the root filesystem from another machine, edit `/etc/ssh/sshd_config`, restore.
- Prevent: always have a second session open, always have a bastion as fallback.
**Trap 2: Removed `authorized_keys`, permission now wrong.**
- Fix: `chmod 600 ~/.ssh/authorized_keys && chown user:user ~/.ssh/authorized_keys`.
- Prevent: never edit `authorized_keys` while logged in as that user. Do it from another machine.
**Trap 3: Changed port to 2222, forgot to update firewall.**
- Fix: `sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT`.
- Prevent: change `sshd_config` and firewall in the same commit; test from a second machine before closing the old session.
**Trap 4: `AllowUsers` typo blocks legit users.**
- Fix: `sudo vim /etc/ssh/sshd_config`, `sudo systemctl reload sshd`.
- Prevent: test `AllowUsers` from a different user first; use a group-based AllowList where possible.
**Trap 5: Disabled PAM but sudo still needs it.**
- Fix: flip `UsePAM yes` back on, keep `PasswordAuthentication no`.
- Prevent: understand what PAM is used for on your system before disabling it. `sudo -l` still needs PAM.
## Cheat Sheet
### 15 `sshd_config` Lines That Matter
```
Port 2222
AddressFamily inet
ListenAddress 0.0.0.0
Protocol 2
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
ChallengeResponseAuthentication no
PermitEmptyPasswords no
PermitRootLogin no
MaxAuthTries 3
LoginGraceTime 30
AllowUsers alice@10.0.0.0/24 bob@192.168.1.0/24
ClientAliveInterval 300
ClientAliveCountMax 2
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
LogLevel VERBOSE
Subsystem sftp internal-sftp
```
### 12 Diagnostic Commands
| # | Command | What it tells you |
|---|---|---|
| 1 | `sshd -t` | Config syntax check |
| 2 | `sshd -T \| grep -Ei 'port\|auth\|allow'` | Effective config (all merged) |
| 3 | `sudo systemctl status sshd` | Service state |
| 4 | `sudo journalctl -u ssh -n 50` | Recent auth attempts |
| 5 | `sudo fail2ban-client status` | Jails and ban counts |
| 6 | `sudo fail2ban-client get sshd banned` | Currently banned IPs |
| 7 | `sudo fail2ban-client unban IP` | Manual unban |
| 8 | `grep -i auth /var/log/auth.log \| tail -50` | Raw auth log (Debian) |
| 9 | `journalctl -u ssh -f` | Live auth log |
| 10 | `nmap -sV -p 2222 target` | Verify exposed services |
| 11 | `ssh -v user@host` | Verbose handshake (debug auth failures) |
| 12 | `ss -tn state established '( sport = :2222 )'` | Active SSH sessions |
### 3 Minimal Configs
**Hardening base (5-layer minimum):**
```
Port 2222
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
MaxAuthTries 3
LoginGraceTime 30
AllowUsers alice@10.0.0.0/24
LogLevel VERBOSE
```
**Fail2ban aggressive:**
```ini
[sshd]
enabled = true
port = 2222
backend = systemd
mode = aggressive
bantime = 1h
findtime = 10m
maxretry = 3
```
**PAM with MFA:**
```
auth required pam_google_authenticator.so nullok
account required pam_nologin.so
```
## Where This Doesn't Help
SSH hardening is a partial defense, not a comprehensive one. If an attacker has your private key, none of the above matters. That's why:
- **Rotate keys** on any compromise signal
- **Use short-lived credentials** where possible (e.g., short-lived `authorized_keys` from a just-in-time system)
- **Monitor key fingerprints** — a new key appearing is a red flag
- **Consider [bastion hosts](../monitor/bastion-jumpserver.md)** — the bastion becomes the only SSH-exposed endpoint, and your internal servers have `sshd` bound to `127.0.0.1` only
## Related Articles
- [Bastion Jumpserver](../monitor/bastion-jumpserver.md) — concentrate SSH on a bastion, remove it from servers
- [Prometheus Alerts](../monitor/prometheus-alerting.md) — alert on `fail2ban` bans, auth failures
- [Prometheus Deploy](../monitor/prometheus-deploy.md) — metrics back the Fail2ban dashboards
- [Nginx Reverse Proxy](../network/nginx-proxy.md) — Nginx in front can add another layer
- [DevSecOps Security Left-Shift: CI/CD Sca…](devsecops-security.md)
## Authoritative References
- [OpenSSH Security Wiki](https://www.openssh.com/security.html) — canonical OpenSSH security guidance
- [man7.org: `sshd_config(5)`](https://man7.org/linux/man-pages/man5/sshd_config.5.html) — every directive documented
- [GitHub: fail2ban/fail2ban](https://github.com/fail2ban/fail2ban) — jail filters and defaults
- [man7.org: `ssh(1)`](https://man7.org/linux/man-pages/man1/ssh.1.html) — client options (agent forwarding, MFA)
- [RFC 4251 — SSH Protocol Architecture](https://datatracker.ietf.org/doc/html/rfc4251) — wire-level spec
---
---
## Windows Server Monitoring: wmi_exporter, Prometheus Scraping, and Grafana Dashboards
URL: https://ops.jiunotes.top/en/monitor/windows-server-monitoring.md
摘要: Full end-to-end Windows monitoring runbook: MSI and zip/NSSM wmi_exporter deploy, collector inventory with cardinality pitfalls, Windows Firewall traps, Prometheus scrape config, Grafana dashboard, alert rules, and five production incidents.
### Answer
End-to-end Windows monitoring: wmi_exporter deploy, collector inventory, firewall traps, Prometheus scrape, Grafana dashboard, alerts, and five incidents.
### FAQ
Q: Why is wmi_exporter on :9182 unreachable from Prometheus but reachable locally?
A: The Windows Firewall inbound rule for port 9182 usually applies to the Domain profile only. If the Prometheus host is on a different network profile, the connection is dropped. Add a second rule scoped to the Private profile or apply it to all profiles.
Q: Why does my disk queue metric show a false alarm on the system drive?
A: Logical disk metrics carry a volume label like C: or D:. Without a drive letter filter, every mounted volume (including the hidden System Reserved one) is summed. Filter with `windows_logical_disk_idle_seconds{volume="C:"}`.
Q: Why did Prometheus memory spike after enabling the process collector?
A: The process collector emits a high-cardinality series per process per handle and thread. On a busy host that is thousands of series, and every scrape grows the in-memory index. Use the `process` collector with the `process_include` filter or disable it.
Q: Why did my rate() alert fire at 03:00 even though nothing changed?
A: Windows time sync jumped the clock forward, so the timestamp delta in the rate window became negative or collapsed to zero. Use `for: 5m` on the alert and check `windows_time_time_offset_seconds` before blaming the service.
Q: Can I run wmi_exporter without a Windows service or MSI install?
A: Yes. Unzip the binary and register it with NSSM as a service. This is the green-deploy path for fleets where you cannot run an MSI but can drop a binary and a config file.
### Full Content
# Windows Server Monitoring: wmi_exporter, Prometheus, and Grafana
For operations engineers who manage Windows Server fleets and want real, queryable metrics instead of a screenshot of Task Manager. The takeaway: wmi_exporter gets you from `netstat` and perfmon to a full [Prometheus](https://prometheus.io/docs/)/Grafana stack in about thirty minutes, but the traps are in the collector defaults and Windows Firewall, not in the installer.
---
I run a mixed fleet. [Linux](https://www.kernel.org/doc/html/latest/) gets [node_exporter](https://github.com/prometheus/node_exporter); Windows gets [wmi_exporter](https://github.com/prometheus-community/windows_exporter). They are not symmetric. On Linux, the exporter is a single static binary that reads `/proc`. On Windows, wmi_exporter shells out to WMI, and WMI has permissions, providers, and a cardinality profile that will surprise you on the first heavy box. This article is the path I wish I had on day one: install, collectors, firewall, scrape, dashboard, alerts, and five incidents that all cost me an on-call shift.
## 1. Pick a Deployment Path: MSI or Zip + NSSM
There are two ways to get the binary on the box, and the choice is a fleet policy, not a preference.
**Path A — MSI with the `ENABLED_COLLECTORS` property.** The installer creates a service, registers the WMI provider, and is the only supported way to set collectors at install time.
```powershell
# Run as Administrator
msiexec /i windows_exporter-0.27.1-amd64.msi ^
ENABLED_COLLECTORS="cpu,cs,logical_disk,net,os,service,system,process" ^
COLLECTOR_SERVICE_SERVICES_WHERECLAUSE="Name LIKE 'W3SVC'" ^
/qn
sc.exe query windows_exporter
netstat -ano | findstr :9182
```
**Path B — zip + NSSM for greenfield fleets.** This is the path I use when the box is not domain-joined yet or when an MSI would trip a change-management review. Drop the binary, point a config at it, register it.
```powershell
mkdir C:\exporter
Expand-Archive windows_exporter-0.27.1-amd64.zip -DestinationPath C:\exporter
# config.yml
cat > C:\exporter\config.yml <<'EOF'
collectors:
enabled: cpu,cs,logical_disk,net,os,service,system,process
service:
services-where: "Name LIKE 'W3SVC'"
EOF
nssm install windows_exporter C:\exporter\windows_exporter.exe
nssm set windows_exporter AppParameters "--config C:\exporter\config.yml --telemetry.addr :9182"
nssm set windows_exporter AppDirectory C:\exporter
nssm set windows_exporter Start SERVICE_AUTO_START
nssm start windows_exporter
```
The MSI defaults to `--telemetry.addr :9182` and a `logical_disk,os,service,system` collector set. If you install the MSI and never pass `ENABLED_COLLECTORS`, you get a thin, safe default. That is fine for a quick dashboard but you will miss network and CPU entirely.
One gotcha on both paths: the service account matters. `wmi_exporter` runs as `LocalSystem` by default, which can read everything. If your security baseline forces a low-privilege service account, you must grant it `Win32_PerfFormattedData` and `Win32_Service` WMI namespace read, or you will see `windows_exporter_collector_duration_seconds` errors and empty series. I hit exactly this; it is incident 5.2 below.
## 2. Collector Inventory: What Is On, What Needs Enabling, What Bites
The collector list is the single most misunderstood part of this stack. Here is the inventory I keep pinned in my runbook.
| Collector | Default (MSI) | Perf profile | Notes |
|---|---|---|---|
| `cpu` | On | Low | Load average per core. Enable always. |
| `cs` | On | Low | System info, hostname, OS version. Cheap. |
| `logical_disk` | On | Medium | The big one for disk. Needs a volume filter (see 5.4). |
| `os` | On | Low | Memory, uptime, time. Enable always. |
| `service` | On | Medium | One series per service. Use `services-where` to trim. |
| `system` | On | Low | Context switches, threads, handles, processes. |
| `net` | **Off** | Medium | NIC bytes/packets. Turn on or you cannot alert on traffic. |
| `process` | **Off** | **High** | Per-process series. Cardinality bomb; see 5.5. |
| `iis` | **Off** | Medium | W3SVC only. Requires the IIS WMI provider and `services-where`. |
| `physical_disk` | Off | Medium | Per-physical-disk counters. Useful when logical_disk is too noisy. |
| `memory` | Off | Low | Use instead of `os` when you want the memory-specific counters. |
| `tcp` | Off | Low | TCP connection states by IPv4/IPv6. Good for connection exhaustion. |
Two rules I enforce. First, `net` and `memory` are cheap and almost always worth enabling even though they are off by default — "network is not monitored" is a terrible first finding on an incident. Second, treat `process` and `iis` as opt-in after you have sized them, never as part of the default MSI install.
The cardinality math is the trap. `process` emits `windows_process_handles`, `windows_process_threads`, and a handful of process counters per process. A box running 200 processes becomes roughly 600-1000 new time series at every scrape. At a 15-second scrape interval that is tens of thousands of samples per minute per host. Multiply by 50 hosts and you have a Prometheus memory problem that has nothing to do with your application.
## 3. Windows Firewall: The Dual-Profile Trap
This is the number one reason "wmi_exporter is installed but Prometheus says target down." The MSI adds an inbound rule, but it is scoped to a specific network profile. A Windows host on a domain can simultaneously present a Domain profile to the LAN and a Private profile to a second NIC. If your Prometheus host reaches the exporter over the second NIC, the rule does not apply and the packet is dropped.
```powershell
# This rule is Domain-profile only (the MSI default behavior)
New-NetFirewallRule -DisplayName "wmi_exporter 9182 Domain" `
-Direction Inbound -Protocol TCP -LocalPort 9182 `
-Profile Domain -Action Allow
# THIS is the fix for the dual-NIC / mixed-profile trap:
New-NetFirewallRule -DisplayName "wmi_exporter 9182 all profiles" `
-Direction Inbound -Protocol TCP -LocalPort 9182 `
-Profile Any -Action Allow
```
I also always verify with the legacy command because that is what the change ticket references:
```bat
netsh advfirewall firewall add rule name="wmi_exporter 9182" ^
dir=in action=allow protocol=TCP localport=9182 profile=any
```
Then test from the Prometheus host, not from the server console:
```bash
curl -s http://10.0.1.24:9182/metrics | head -20
nc -vz 10.0.1.24 9182
```
If `nc` connects but `curl` returns empty, the exporter is up but the firewall is still eating it, or the exporter bound to `127.0.0.1`. Check the bind address. The MSI binds to `:9182` on all interfaces, but if you set `--telemetry.addr 127.0.0.1:9182` to be safe, remote scrapes will never work. I have seen both.
## 4. Prometheus Scrape Config
A single `job` with per-host labels is the right shape for a fleet. Resist the urge to make one job per host.
```yaml
# prometheus.yml fragment
scrape_configs:
- job_name: windows
scrape_interval: 15s
scrape_timeout: 10s
static_configs:
- targets:
- "10.0.1.24:9182" # DC01
- "10.0.1.25:9182" # APP01
- "10.0.1.26:9182" # SQL01
labels:
env: prod
os: windows
relabel_configs:
- source_labels: [__address__]
regex: "([^:]+):9182"
target_label: instance
replacement: "$1"
```
Two tuning notes. First, `scrape_timeout: 10s` matters. Some `logical_disk` and `process` queries on a busy box can take longer than the default 10s timeout, which makes Prometheus mark the target as down even though the exporter is healthy. If you see `target up` but `windows_exporter_collector_duration_seconds > 5`, bump the timeout before you blame the network. Second, the `instance` relabel strips the port so your dashboards read `DC01` instead of `10.0.1.24:9182`.
## 5. Five Real Incidents
### 5.1 Port 9182 Unreachable — Dual Firewall Profile
Prometheus showed `target down`, but `curl` from a second RDP session on the same server returned a full metric dump. The exporter was fine; the problem was the firewall rule. The server had two NICs: the management LAN on the Domain profile and a storage network on the Private profile. Prometheus scraped over the storage network, so the Domain-only rule never applied. Fix: added a second `profile=any` rule (section 3) and documented that every new host needs both the Domain and the Any rule.
### 5.2 Service Account Lacked WMI Permission
After a security hardening pass, the `windows_exporter` service was switched from `LocalSystem` to a managed service account. Every collector started returning empty series and `windows_exporter_collector_duration_seconds` went to zero. WMI denied the account read on `Win32_PerfFormattedData`. Fix: granted the account `Remote Access` on the `root\cimv2` namespace and added it to the `Performance Monitor Users` group. Never run the exporter as a truly unprivileged account without granting WMI read.
### 5.3 Windows Time Jump Caused a False `rate()` Alarm
At 03:00 an alert on `rate(windows_cpu_time_total[5m]) > 0.9` fired for every host at once. Nothing was actually consuming CPU. The culprit was the Windows Time service applying a large forward correction, so the timestamp delta between samples collapsed and `rate()` divided by near-zero. Fix: added `for: 5m` to the alert and a `windows_time_time_offset_seconds > 10` query to the dashboard. Rule: `rate()` on any counter is only trustworthy when the clock is stable.
### 5.4 Disk Queue False Positive From the Drive Letter Filter
`windows_logical_disk_idle_seconds` was alerting on a box with an idle disk. The problem: I had not filtered by volume. The `logical_disk` collector reports every mounted volume, including the hidden System Reserved partition and any Recovery volume. Summing across all of them made the queue appear saturated. Fix: always filter by drive letter.
```promql
# correct: only C:
1 - avg by (instance) (windows_logical_disk_idle_seconds{volume="C:"})
> 0.9
```
### 5.5 Process Collector Blew Up Prometheus Memory
A 500-process terminal server was enabled with the `process` collector as part of the default set. Within a day Prometheus head memory doubled and query latency went from 300 ms to 4 s. The process collector had created thousands of series and every 15-second scrape was adding to the index. Fix: disabled `process`, enabled `net`, and left `process_include` empty so only a whitelist of critical processes is ever emitted.
```yaml
collectors:
enabled: cpu,cs,logical_disk,net,os,service,system
process:
process-include: "^(sqlservr|w3wp|lsass|svchost)$"
```
## 6. Key Metrics and Their PromQL
These are the eight queries I put on every Windows dashboard.
| Metric | What it tells you | PromQL |
|---|---|---|
| CPU busy % | Utilization across cores | `100 - avg by (instance) (windows_cpu_time_total{mode="idle"} / 100) * 100` |
| Memory available | Headroom before paging | `windows_os_physical_memory_free_bytes` |
| Memory % used | Pressure ratio | `1 - windows_os_physical_memory_free_bytes / windows_os_physical_memory_total_bytes` |
| Disk queue length | I/O saturation | `windows_logical_disk_avg_disk_queue_length{volume="C:"}` |
| Disk busy % | Time the disk was active | `100 - windows_logical_disk_idle_seconds{volume="C:"} / 100` |
| Handle count | Leak indicator, process exhaustion | `sum(windows_system_handle_count)` |
| Process count | Zombie / runaway process check | `sum(windows_system_process_count)` |
| Network traffic | NIC throughput | `sum by (instance) (rate(windows_net_bytes_received_total[5m]))` |
For handle count, a sustained linear climb over hours is a classic handle leak. `windows_system_handle_count` is a gauge, so you can't `rate()` it — plot it raw and look for a slope, not a spike.
## 7. [Grafana](https://grafana.com/docs/) Dashboard: The Panel Layout That Works
I build the dashboard from three rows. Row 1 is "load" (CPU, memory). Row 2 is "disk and IO" (queue, busy %, free space by volume). Row 3 is "process and network" (handles, processes, NIC traffic). The key is a `instance` template variable.
```json
{
"title": "Windows Server Overview",
"templating": {
"list": [
{
"name": "instance",
"type": "query",
"query": "label_values(windows_cpu_time_total, instance)"
}
]
},
"panels": [
{
"title": "CPU busy %",
"type": "timeseries",
"targets": [{
"expr": "100 - avg by (instance) (windows_cpu_time_total{mode=\"idle\"} / 100) * 100"
}]
},
{
"title": "Disk queue C:",
"type": "timeseries",
"targets": [{
"expr": "windows_logical_disk_avg_disk_queue_length{volume=\"C:\", instance=~\"$instance\"}"
}]
}
]
}
```
The template variable makes every panel follow the host selector. Without it, you are either plotting all hosts on one chart (unreadable) or maintaining a dashboard per host (unmaintainable).
## 8. Alert Rules
```yaml
groups:
- name: windows
rules:
- alert: WindowsHighCpu
expr: (100 - avg by (instance) (windows_cpu_time_total{mode="idle"} / 100) * 100) > 85
for: 5m
labels: { severity: warning }
annotations: { summary: "CPU > 85% on {{ $labels.instance }}" }
- alert: WindowsLowMemory
expr: windows_os_physical_memory_free_bytes / windows_os_physical_memory_total_bytes < 0.1
for: 10m
labels: { severity: critical }
annotations: { summary: "Free memory under 10% on {{ $labels.instance }}" }
- alert: WindowsDiskQueueHigh
expr: windows_logical_disk_avg_disk_queue_length{volume="C:"} > 5
for: 5m
labels: { severity: warning }
annotations: { summary: "Disk queue on C: is saturated on {{ $labels.instance }}" }
- alert: WindowsTimeSkew
expr: abs(windows_time_time_offset_seconds) > 10
for: 2m
labels: { severity: warning }
annotations: { summary: "Clock skew > 10s on {{ $labels.instance }}" }
- alert: WindowsHandleLeak
expr: windows_system_handle_count > 50000
for: 30m
labels: { severity: critical }
annotations: { summary: "Handle count high on {{ $labels.instance }}" }
```
`WindowsTimeSkew` is the alert I recommend adding to every fleet. It catches the root cause of the 5.3 incident before it masquerades as a CPU or latency problem.
## FAQ
**Q: Why is wmi_exporter on :9182 unreachable from Prometheus but reachable locally?**
A: The Windows Firewall inbound rule for port 9182 usually applies to the Domain profile only. If the Prometheus host is on a different network profile, the connection is dropped. Add a second rule scoped to the Private profile or apply it to all profiles.
**Q: Why does my disk queue metric show a false alarm on the system drive?**
A: Logical disk metrics carry a volume label like `C:` or `D:`. Without a drive letter filter, every mounted volume (including the hidden System Reserved one) is summed. Filter with `windows_logical_disk_idle_seconds{volume="C:"}`.
**Q: Why did Prometheus memory spike after enabling the process collector?**
A: The process collector emits a high-cardinality series per process per handle and thread. On a busy host that is thousands of series, and every scrape grows the in-memory index. Use the `process` collector with the `process_include` filter or disable it.
**Q: Why did my rate() alert fire at 03:00 even though nothing changed?**
A: Windows time sync jumped the clock forward, so the timestamp delta in the rate window became negative or collapsed to zero. Use `for: 5m` on the alert and check `windows_time_time_offset_seconds` before blaming the service.
**Q: Can I run wmi_exporter without a Windows service or MSI install?**
A: Yes. Unzip the binary and register it with NSSM as a service. This is the green-deploy path for fleets where you cannot run an MSI but can drop a binary and a config file.
## Related Articles
- [Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO](grafana-dashboard.md)
- [Prometheus + Grafana Deploy — Docker + systemd Side-by-Side](prometheus-deploy.md)
- [Thanos in Production: Long-Term Prometheus Storage and Multi-Cluster Querying](prometheus-thanos-storage.md)
---
## Zabbix + Prometheus Hybrid Monitoring: The Two-Tier Stack for Physical and Cloud-Native
URL: https://ops.jiunotes.top/en/monitor/zabbix-prometheus-hybrid.md
摘要: A production hybrid monitoring design: Zabbix owns physical hosts, switches, routers and SNMP; Prometheus owns Kubernetes, containers and microservices; Grafana unifies the view. Covers the architecture split, data interchange between the two, alert convergence with inhibit rules, and a phased migration path, with real incidents I hit along the way.
### Answer
Hybrid monitoring is a division of labor. Zabbix scrapes what speaks SNMP or runs a passive agent: physical hosts, switches, routers, UPS, printers. Prometheus scrapes HTTP metrics endpoints: Kubernetes pods, containers, Go and Rust services. Grafana reads both datasources. Alertmanager and the Zabbix action forward to one webhook, and inhibit rules stop the same failure firing twice. Migrate in four phases: parallel run, unified dashboards, converged alerts, incremental workloads.
### FAQ
Q: Why keep Zabbix at all if I already run Prometheus?
A: Because Prometheus is pull-based and needs an HTTP metrics endpoint. A dumb switch, a printer, a UPS, or a legacy router speaks SNMP or nothing at all. Zabbix covers those devices natively. Layering beats overloading a single tool.
Q: Can I query Zabbix and Prometheus in the same Grafana dashboard?
A: Yes, add both as datasources and mix panels. One caveat: the Zabbix datasource is a pull/cached snapshot, so it does not support live PromQL-style aggregation. Use Prometheus for real-time forensics and Zabbix for historical trends and capacity planning.
Q: The same outage fires in both systems - how do I stop the duplicate?
A: Use an Alertmanager inhibit rule keyed on the instance. When Zabbix raises a critical for host X, it silences the Prometheus alert for the same instance. Also align group_by dimensions, or one host down becomes two pages.
Q: What is the safest migration from a Zabbix-only stack?
A: Never a big-bang switch. Phase one: run both in parallel, Prometheus only scrapes new Kubernetes services. Phase two: Grafana reads both. Phase three: converge alerts to one webhook. Phase four: move workloads over gradually and keep Zabbix as the fallback.
Q: What bit me when I imported Prometheus data into Zabbix?
A: High-cardinality labels. Zabbix is relational; Prometheus is label-based. Importing raw time series wrote tens of thousands of rows per second and the queries timed out. Import only pre-aggregated values, never raw cardinality.
Q: Why did my Grafana Zabbix panel lag five minutes behind?
A: The Zabbix API caches results for a few minutes and the datasource polls on an interval. For latency-critical debugging use Prometheus. Reserve Zabbix panels for trend lines and long-range capacity work.
### Full Content
# Zabbix + Prometheus Hybrid Monitoring: The Two-Tier Stack for Physical and Cloud-Native
The question I hear most is not "which monitoring tool is better" - it is "do I really need two?" After running a Zabbix-only stack for four years and then grafting [Prometheus](https://prometheus.io/docs/) onto it, my answer is a firm yes, but only if you split the work along the seam where each tool is genuinely strong. This article documents the hybrid design I now run in production, the data-interchange pitfalls between the two, and the alert convergence that stopped me from getting paged twice for the same dead server.
## Why One Tool Stops Fitting
The failure of a single-stack setup is not that the tool is bad - it is that the workload is heterogeneous. I have a table I keep in my head, and it drives every monitoring decision:
| Workload | Zabbix strength | Prometheus strength |
|---|---|---|
| Dynamic [Kubernetes](https://kubernetes.io/docs/) clusters | Weak (static config, poor discovery) | Strong (native Service Discovery) |
| Switches, routers, printers | Strong (SNMP, passive agent) | Weak (needs an exporter, thin coverage) |
| High-cardinality metrics | Relational DB bloats fast | Label model handles it, but can exhaust memory |
| Long-term storage | Strong (SQL-backed) | Needs Thanos / Cortex / Mimir |
| Alert rules | Trigger syntax, old but solid | PromQL, flexible, steep learning curve |
The conclusion is boring and correct: **traditional infrastructure goes to Zabbix, cloud-native goes to Prometheus, and nobody tries to make one tool eat everything.** In my environment the split is roughly 60/40, Zabbix winning on raw device count.
## The Two-Tier Architecture
Here is the layout I settled on after two redesigns. The key is that the two collectors never talk to each other directly - they meet only at the display layer and the alert router.
```
┌────────────────────────────────────────┐
│ [Grafana](https://grafana.com/docs/) (single pane) │
│ infra board │ cloud board │ alert board│
└───────┬──────────┬──────────┬──────────┘
│ │ │
┌───────▼──┐ ┌─────▼─────┐ ┌─▼──────────┐
│ Zabbix │ │ Prometheus │ │ Alertman. │
│ Server │ │ + TSDB │ │ + webhook │
└───────┬──┘ └─────┬─────┘ └─┬──────────┘
│ │ │
┌───────▼──┐ ┌─────▼─────┐ ┌─▼──────────┐
│ Agent/ │ │ K8s SD + │ │ WeCom/ │
│ SNMP dev │ │ exporters │ │ Slack │
└──────────┘ └───────────┘ └────────────┘
```
Three rules I now treat as non-negotiable:
1. **Datasource isolation** - Zabbix only ever sees SNMP, passive agents, and active checks. Prometheus only ever sees HTTP exporters and Service Discovery. If a metric can be scraped, it belongs to Prometheus.
2. **Unified display** - Grafana connects to both datasources so nobody has to open two UIs during an incident.
3. **Converged alerts** - both the Alertmanager and the Zabbix action post to the same webhook endpoint, which deduplicates and routes by severity.
## Zabbix Side: What Stays, and How
I did not strip Zabbix down - I pruned it. Anything I could scrape over HTTP moved to Prometheus. Zabbix kept the long tail that has no `/metrics` endpoint:
- Physical servers (CPU, memory, disk, RAID controller state)
- Network devices (switch and router SNMP counters)
- Legacy databases (MySQL / [PostgreSQL](https://www.postgresql.org/docs/) slow-query state)
- Printers, UPS units, and HVAC controllers that only speak SNMP or Modbus
The agent config is deliberately minimal:
```ini
# /etc/zabbix/zabbix_agent2.conf
Server=10.0.0.5
ServerActive=10.0.0.5
Hostname=physical-server-01
LogFile=/var/log/zabbix/zabbix_agent2.log
# SNMP module for the network gear
LoadModule=snmp.so
```
## Prometheus Side: Service Discovery and the Node Gap
The Prometheus scrape config leans on Kubernetes Service Discovery and never uses static targets for the dynamic part of the fleet:
```yaml
# /etc/prometheus/prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
# Physical hosts that DO expose a node_exporter still go here,
# not to Zabbix. This is the bridge between the two worlds.
- job_name: 'node-exporter'
static_configs:
- targets: ['node-exporter:9100']
```
There is one deliberate overlap: a physical host that runs `node_exporter` is scraped by Prometheus, while its SNMP-managed switch is polled by Zabbix. That overlap is not a bug - it is how I get fine-grained host metrics and coarse device metrics from the same rack.
## Data Interchange: What to Bridge and What to Never Touch
The most dangerous idea in hybrid monitoring is "let's sync everything into one store." I tried it and I will not do it again. Here is the rule that saved me:
- **Bridge aggregated values only.** A daily rollup of average CPU, memory headroom, and interface utilization can live in Zabbix for capacity planning.
- **Never bridge raw high-cardinality time series.** Importing Prometheus's label-rich data into Zabbix's relational store wrote tens of thousands of rows per second and made every query time out. That was my worst week.
If you must expose Zabbix data to Prometheus consumers, use the Zabbix exporter (the `prometheus.so` module) to publish selected items as a scrape target. Do the inverse - Zabbix importing Prometheus - only for a handful of hand-picked aggregates.
## Alert Convergence: Stopping the Double Page
The symptom that forced this design: a server died, and within ninety seconds I got a Zabbix SNMP-unreachable alert and a Prometheus node-exporter-down alert. Two pages, one root cause, and two on-call engineers annoyed at me.
The fix is an inhibit rule plus aligned grouping:
```yaml
# /etc/alertmanager/alertmanager.yml
route:
receiver: 'unified-webhook'
group_by: ['alertname', 'cluster', 'service']
group_wait: 10s
group_interval: 5m
repeat_interval: 4h
routes:
- matchers:
- severity = critical
receiver: 'p0-oncall'
repeat_interval: 30m
inhibit_rules:
# When Zabbix raises a critical for a host, silence the Prometheus
# alert for the same instance.
- source_matchers:
- severity = critical
- source = zabbix
target_matchers:
- source = prometheus
equal: ['instance']
receivers:
- name: 'unified-webhook'
webhook_configs:
- url: 'http://alert-router:8080/alertmanager'
- name: 'p0-oncall'
webhook_configs:
- url: 'http://alert-router:8080/p0'
```
The Zabbix action mirrors this by posting a JSON payload to the same router with a `source: zabbix` marker, so the router can correlate the two sides. The single most important lesson: **align `group_by` and the `equal` key across both systems, or the same failure fires twice.**
## Grafana: One Pane of Glass
Two datasources, one dashboard set:
```yaml
# Grafana datasource - Prometheus
url: http://prometheus:9090
access: proxy
# Grafana datasource - Zabbix
url: http://zabbix:80
access: proxy
```
A mixed panel uses a Prometheus query for the cloud-native half:
```promql
up{job="kubernetes-pods"} == 0
```
...and a Zabbix query for the traditional half:
```text
last(/Zabbix server/uptime)
```
The dedicated alert-convergence board is the one I open first during an incident. It shows `ALERTS{alertstate="firing"}` from Prometheus and the active triggers from Zabbix side by side, so I can see whether a single root cause is firing once or twice.
## The Four-Phase Migration Roadmap
I did not do this in a weekend, and you should not either. My timeline:
**Phase 1 - parallel run (weeks 1-2).** Zabbix keeps polling everything. Prometheus only scrapes newly-created Kubernetes services. No alerting is wired to the team yet; the only goal is to prove the scrapes are clean.
**Phase 2 - unified display (weeks 3-4).** Grafana connects to both datasources. The team starts reading the new boards. The old Zabbix UI slowly falls out of habit.
**Phase 3 - alert convergence (weeks 5-6).** Wire the Alertmanager inhibit rules, the Zabbix webhook action, and the single router. Verify with a deliberate kill of a test host that exactly one alert fires.
**Phase 4 - incremental migration (weeks 7-8).** New services go to Prometheus by default. Physical hosts move case by case. Network devices stay on Zabbix because SNMP is the only sane option. Zabbix stays up as the safety net - do not rush to delete it.
## Real Incidents From the Field
**Incident 1: the high-cardinality import.** I imported Prometheus's raw metrics into Zabbix to "unify the data." Within an hour the database was writing 100,000 rows a second and the dashboard timed out. I rolled back the import and redefined the bridge to carry aggregates only.
**Incident 2: the five-minute Zabbix lag.** During an incident the Grafana Zabbix panel showed data from five minutes ago. The Zabbix API caches responses and the datasource polls on an interval, so the panel is inherently behind. I stopped using it for forensics and moved real-time work to Prometheus.
**Incident 3: the 30-second clock skew.** The Grafana timeline showed the Prometheus and Zabbix traces not aligning. Two monitoring servers had drifted thirty seconds on NTP. Skew over one second breaks correlation, so I pinned every collector to the same NTP source and alert on drift now.
## The Decision Tree I Actually Use
```
What are you monitoring?
├─ Kubernetes cluster / microservice / container
│ └─ Prometheus + Alertmanager
├─ Physical server / VM
│ ├─ exposes /metrics → Prometheus node_exporter
│ └─ SNMP only → Zabbix agent
├─ Switch / router
│ └─ Zabbix (SNMP is the only real option)
├─ Legacy database
│ ├─ has an exporter → Prometheus
│ └─ old version → Zabbix DB template
└─ IoT / printer / UPS
└─ Zabbix (SNMP / Modbus)
```
## FAQ and Originality Statement
The whole hybrid exercise has taught me one line that I repeat constantly: **monitoring is not a contest between tools, it is a division of labor.** Zabbix and Prometheus are complements, not rivals. The end goal is never "how many tools did we install" - it is "when something breaks, how fast can we find it." A layered architecture serves that goal better than any single tool ever did.
I wrote this article from my own production experience with the stack described here. The configurations are from a live hybrid deployment; the incidents are ones I personally hit. No portion of this text was translated from another article, and the cases, framing, and wording are original to this piece.
## Related Articles
- [Zabbix 7 Setup: Docker Deploy, Templates, and When It Wins Over Prometheus](zabbix-setup.md)
- [Prometheus Alerting: Route Trees, Silences, and Webhook Delivery](prometheus-alerting.md)
- [Grafana Dashboard Design: Datasources, Variables, and Panel Linking](grafana-dashboard.md)
---
## Zabbix 7 Setup: Docker Deploy, Templates, Triggers, and When It Wins Over Prometheus
URL: https://ops.jiunotes.top/en/monitor/zabbix-setup.md
摘要: Zabbix 7 four-part Docker Compose deploy (MySQL + Server + Web + Agent2), template and trigger walkthrough, three alert severity levels, and a decision tree for choosing Zabbix over Prometheus. Five real incidents included - MySQL never ready, agent can't connect, timezone drift.
### Answer
Zabbix 7 in one Compose file: MySQL + Server + Web + Agent2. Add MySQL healthcheck so server waits for it. Selection rule: Windows, physical servers, network devices, or 1000+ hosts -> Zabbix. Cloud-native Linux plus PromQL-savvy team -> Prometheus. Both coexist: Zabbix covers the traditional infrastructure, Prometheus covers k8s. Templates give every host a battery of items, triggers turn those into alerts.
### FAQ
Q: What changed in Zabbix 7 compared to Zabbix 6?
A: 7.0 is the LTS branch (2024). Big changes: Agent2 built in, custom item keys, a rewritten alert rule engine, and a modern Web UI. Skip 6.x and jump straight to 7.0.
Q: Can Zabbix and Prometheus coexist?
A: Completely. Common production topology: Zabbix scrapes physical hosts, Windows servers, and network devices. Prometheus scrapes Kubernetes, containers, and Go services. A hybrid stack covers more ground than either alone.
Q: Why Agent2 instead of Agent1?
A: Agent2 is written in Go, supports custom item keys written in Go or Python, and uses less memory. Agent1 is C and more stable but less extensible. Default to Agent2 on new projects.
Q: Do I still need Zabbix if I already have Prometheus?
A: If you run Windows servers or a lot of physical infrastructure, yes - Prometheus's Windows monitoring story is weak. Pure cloud-native Linux and k8s, Prometheus is enough. Mixed environments get more out of both.
Q: `depends_on` does not wait for MySQL to be ready - what now?
A: Add a MySQL healthcheck and use `depends_on: mysql: condition: service_healthy`. I have been burned by this on first deploy - the Web UI reports `Failed to initialize database schema` because MySQL was not actually ready even though it was running.
### Full Content
# Zabbix 7 Setup: Docker Deploy, Templates, Triggers, and When It Wins Over Prometheus
Zabbix has been shipping for over 15 years and covers everything from bare-metal servers to network devices. Many teams hear "monitoring" and jump straight to [Prometheus](https://prometheus.io/docs/), ignoring that Zabbix still owns the traditional-infrastructure slice of the stack.
This post covers two things: a fast [Docker](https://docs.docker.com/) Compose deploy of Zabbix 7.0 (Server + Web + MySQL + Agent2), and the decision-making for when to pick Zabbix over Prometheus. Not "which is better" - which one fits the room you are in.
## The 60-Second Decision: Prometheus vs Zabbix
| Axis | Prometheus | Zabbix |
| --- | --- | --- |
| Data model | Pull | Push |
| Query language | PromQL (powerful, steep) | Expressions (simple, weak) |
| Best for | Cloud native, k8s, Go/Rust services | Windows, physical hosts, network devices |
| Scale | ~5M time series per node | 100k+ hosts per node |
| Agent | Exporters (multi-language) | Agent2 (Go, cross-platform) |
| Alert rules | PromQL expressions | Triggers (more intuitive) |
| Built-in UI | None (needs [Grafana](https://grafana.com/docs/)) | Web UI included |
| Cloud native | Excellent | Moderate (via Agent2) |
| Traditional infra | Weak (no native Windows Agent) | Strong (Windows Agent supported) |
## Decision Tree: Five Questions
**Q1: Do you have Windows servers or physical machines?**
- Yes -> Zabbix as the base, Prometheus optional.
- Pure [Linux](https://www.kernel.org/doc/html/latest/) plus cloud native -> Q2.
**Q2: Does your team speak PromQL?**
- Yes -> Prometheus as the base.
- No or reluctant -> Zabbix, the Web UI is more forgiving.
**Q3: How big is your k8s cluster?**
- More than 50 nodes -> Prometheus is essential (pull model fits dynamic targets).
- Under 20 nodes -> see Q1 and Q2.
**Q4: Are alert rules complex?**
- Multi-condition, time-windowed, dependency-based -> Prometheus plus Alertmanager.
- Simple thresholds -> Zabbix's built-in UI is enough.
**Q5: Budget?**
- Cheapest -> both are open source, either way is free.
- Least ops -> Prometheus (single binary) plus Grafana plus Alertmanager, three components vs Zabbix's five (including MySQL).
The rule I use:
- Mixed environment (Windows + Linux + k8s) -> both, Zabbix for infrastructure, Prometheus for k8s.
- Pure cloud native -> Prometheus.
- Traditional datacenter -> Zabbix.
## Zabbix 7 Docker Deploy: Four Containers
### Write the Compose File
```yaml
# zabbix-compose.yml
services:
mysql:
image: mysql:8.0
container_name: zbx-mysql
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD:
MYSQL_DATABASE: zabbix
MYSQL_USER: zabbix
MYSQL_PASSWORD:
TZ: Asia/Shanghai
volumes:
- zbx-mysql:/var/lib/mysql
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_bin
- --innodb-buffer-pool-size=512M
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-p"]
interval: 5s
timeout: 5s
retries: 30
ports:
- "3306:3306"
server:
image: zabbix/zabbix-server-mysql:7.0-latest
container_name: zbx-server
restart: unless-stopped
depends_on:
mysql:
condition: service_healthy
environment:
MYSQL_HOST: mysql
MYSQL_DATABASE: zabbix
MYSQL_USER: zabbix
MYSQL_PASSWORD:
MYSQL_PORT: 3306
ZBX_SERVER_NAME: "Zabbix-7"
ZBX_SERVER_PORT: 10051
ZBX_SERVER_LOG_LEVEL: 3
TZ: Asia/Shanghai
ports:
- "10051:10051" # Agent communication
- "10052:10052" # IPMI (optional)
volumes:
- zbx-server:/var/lib/zabbix
web:
image: zabbix/zabbix-web-nginx-mysql:7.0-latest
container_name: zbx-web
restart: unless-stopped
depends_on:
- server
- mysql
environment:
MYSQL_HOST: mysql
MYSQL_DATABASE: zabbix
MYSQL_USER: zabbix
MYSQL_PASSWORD:
MYSQL_PORT: 3306
PHP_DATE_DEFAULT_timezone: Asia/Shanghai
ports:
- "8080:80"
agent2:
image: zabbix/zabbix-agent2:7.0-latest
container_name: zbx-agent2
restart: unless-stopped
depends_on:
- server
environment:
ZBX_HOSTNAME: zbx-server-local
volumes:
- /proc:/host/proc:ro
- /sys:/host/sys:ro
- /:/host/root:ro
volumes:
zbx-mysql:
zbx-server:
```
Key points:
- MySQL 8.0 is what Zabbix 7 officially recommends.
- `ZBX_SERVER_LOG_LEVEL=3` is debug; use 4 (info) in production.
- Agent2 mounts `/proc` and `/sys` to read host metrics.
- For production put TLS in front of 8080 - swap to 443 with a real certificate.
### Bring It Up
```bash
docker compose -f zabbix-compose.yml up -d
docker compose ps
# Watch MySQL initialize
docker logs zbx-mysql | tail -20
# Watch Zabbix Server come up
docker logs zbx-server | grep -iE 'ready|starting|error' | tail -20
```
Expected state: `docker compose ps` shows all four containers `running`. Zabbix Server logs include `Server started` and no `Cannot create database` error. Opening `http://:8080/zabbix` shows the install wizard.
### Web UI First-Time Wizard
Visit `http://:8080/zabbix` and step through the wizard:
1. **Info page** - Next.
2. **Pre-checks** - If anything is red, jump to the incidents section.
3. **Database setup** - Zabbix auto-fills the values. Confirm `host=mysql`, `database=zabbix`, `user=zabbix`, password matches your Compose file.
4. **Install settings** - Zabbix server address is `server` (service name, not an IP).
5. **Confirm install** - Done.
Login credentials: `admin / zabbix`.
### Install Agent2 on Clients
Every host you want to monitor runs Agent2:
```bash
# Debian/Ubuntu
sudo curl -s https://repo.zabbix.com/zabbix/7.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_7.0-1%2Bubuntu22.04_all.deb -o zabbix-release.deb
sudo dpkg -i zabbix-release.deb
sudo apt update
sudo apt install zabbix-agent2
# Point the agent at the server
sudo sed -i 's/^Server=.*/Server=192.168.1.100/' /etc/zabbix/zabbix_agent2.conf
sudo sed -i 's/^ServerActive=.*/ServerActive=192.168.1.100/' /etc/zabbix/zabbix_agent2.conf
sudo sed -i 's/^Hostname=.*/Hostname=my-web-01/' /etc/zabbix/zabbix_agent2.conf
sudo systemctl enable --now zabbix-agent2
# Verify it responds
zabbix_agent2 -I test
```
Expected output: `test` on stdout.
## Templates: Give Every Host a Battery of Items
A Zabbix template is a named set of items, triggers, graphs, and dashboards. Every host you add should inherit from at least one template.
For a generic Linux host:
- **Linux by Zabbix agent 2** - covers CPU, memory, disk, network, and processes.
For a MySQL server add:
- **MySQL by Zabbix agent 2** - covers connections, queries, slow queries, replication.
Add a template in the UI:
- Hosts -> (host) -> Templates -> Add.
Templates give you the 80% win. Without them you would have to add every item by hand.
## Triggers: Turn Items into Alerts
A trigger is a boolean expression over one or more items, with an evaluation type and a priority. The four most useful priority levels:
- **Disaster** (5) - service is down.
- **High** (4) - serious degradation, page on-call.
- **Average** (3) - degraded, ticket to the team.
- **Warning** (2) - informational, no page.
Example trigger:
```text
Trigger name: Host unreachable
Expression: last(/Zabbix/server/agent.ping)=0
Priority: Disaster
```
Example trigger for a MySQL server:
```text
Trigger name: MySQL connections near limit
Expression: last(/Zabbix/server/db.mysql.connections)>900
Priority: High
```
## Alert Severity in Actions
Once triggers fire, actions route them:
- **Disaster** -> SMS and phone call to on-call.
- **High** -> Slack DM to the team channel plus email.
- **Average** -> email to the on-call rotation, no page.
- **Warning** -> logged only, no notification.
The rule: page only for **Disaster** and **High**. Anything lower is a ticket.
## Five Real Incidents and Fixes
### Incident 1: Web UI Says "Failed to Initialize Database Schema"
**Symptom**: The Web wizard's third step shows `Cannot connect to database. Please check the DBMS configuration parameters.`
**Root cause**: `depends_on` guarantees startup order but not readiness. MySQL was up but not ready, and Zabbix Server tried to connect before the schema existed.
**Diagnostic**:
```bash
docker exec -it zbx-mysql mysqladmin status -uzabbix -p
# Should output "Uptime: xxx seconds"
```
**Fix**: Add the MySQL healthcheck (already in the Compose above) and change `depends_on` to `depends_on: mysql: condition: service_healthy`. As an escape hatch, `docker compose restart server web`.
### Incident 2: Agent2 Cannot Connect to Server
**Symptom**: After adding a host, no data appears. Agent2 log shows `Unable to connect to Zabbix server at "192.168.1.100": Connection refused`.
**Root cause**: Either `10051` is firewalled, or `Server=` is set to the wrong address.
**Diagnostic**:
```bash
# From the client
nc -zv 10051
# Check the server-side firewall
sudo iptables -L INPUT -n | grep 10051
# Agent2 log
sudo tail -50 /var/log/zabbix/zabbix_agent2.log
```
**Fix**: Open `10051` in the firewall. In cloud environments the security group default is all-blocked - go to the console and open it. On physical machines firewalld sometimes overrides iptables rules.
### Incident 3: Timezone Wrong, Alert Timestamps All Off
**Symptom**: Alert rules say "send email at 9 AM every day", but emails arrive at 5 PM.
**Root cause**: Containers default to UTC. `TZ=Asia/Shanghai` in the Compose was missing on one of the services.
**Fix**: Add `TZ: Asia/Shanghai` to every service. After install, go to Administration -> Timezone -> Asia/Shanghai in the Web UI. MySQL timezone also needs an override:
```sql
SET GLOBAL time_zone = '+08:00';
```
### Incident 4: Disk Filled with History
**Symptom**: After three weeks, MySQL uses 100 GB and dashboards start to lag.
**Root cause**: History retention was set to 2 years for every item.
**Fix**: Tune retention per item type. For most hosts 90 days is enough for hourly aggregates, 7 days for 5-second raw. Set under Administration -> General -> History / Trends.
### Incident 5: High Polling Load
**Symptom**: Zabbix Server CPU pinned at 80% during business hours.
**Root cause**: 1000+ items polled every 30 seconds. `StartPollers` was at the default of 5.
**Fix**:
```ini
# /etc/zabbix/zabbix_server.conf
StartPollers=50
StartIPMIPollers=5
StartPollersUnreachable=10
StartTrappers=30
```
Restart the server after the change.
## PromQL to Zabbix: Migration Cheat Sheet
For teams with an existing Prometheus setup who want to add Zabbix:
| Prometheus concept | Zabbix equivalent |
| --- | --- |
| target | Host |
| metric | Item |
| `rate()` | Item type `Zabbix agent (active)` or `Zabbix agent` |
| alerting rule | Trigger |
| Alertmanager | Notification (Media type + Action) |
| Dashboard | Dashboard (built into Web UI) |
| Grafana | No direct equivalent (use Grafana + Zabbix data source) |
Migration is not a one-to-one rewrite. PromQL expressions need to be translated by hand into Zabbix trigger expressions. Exporters map to Agent2 item keys in some cases but the coverage is not complete. Alert routing is label-based in Prometheus and host-or-group-based in Zabbix, which changes how you think about grouping.
## Bottom Line
Zabbix 7 is a four-container Docker deploy and a five-step Web wizard. The choice between Zabbix and Prometheus is not "which is better". Pure cloud native, Prometheus. Pure traditional infrastructure, Zabbix. Mixed environment, both. For a team that already has Prometheus, adding Zabbix is usually about plugging the Windows and physical-host gap. For a team starting from scratch, Zabbix has a lower learning curve and you can set up the first alert in five minutes without learning PromQL.
---
*This article is originally written by ops.jiunotes.top. All Docker Compose configurations, deployment steps, and selection decisions in this post are from direct production practice; no content is copied from Zabbix official documentation or third-party English tutorials. Configuration references are available at [Zabbix 7.0 documentation](https://www.zabbix.com/documentation/7.0) and the [Docker Hub zabbix images](https://hub.docker.com/_/zabbix-server). CC BY-NC-SA 4.0.*
## Related Articles
- [PromQL Field Guide: Function Families, Five Gold Metrics, and 20 Copy-Paste Queries](prometheus-query.md)
- [Blackbox Exporter: Protocol Modules, SLO Metrics, and K8s ServiceMonitor Setup](blackbox-exporter.md)
- [Grafana Dashboards: Variables, JSON, Panels, Alerts, SLO](grafana-dashboard.md)
---
## Alertmanager 告警降噪实战:抑制器 + 路由树 + 静默配置四步降噪法
URL: https://ops.jiunotes.top/monitor/alertmanager-noise-reduction.md
摘要: 生产环境 Alertmanager 告警从每天几百条降到个位数:Inhibit 抑制器配置、P0/P1/P2 三级路由、维护静默、group_by 分组策略,附四个翻车案例(告警风暴、重复轰炸、漏报、路由不生效)。
### Answer
告警降噪四步:① group_by 按业务维度分组(instance 太粗) ② Inhibit 抑制依赖告警(磁盘满时抑制 inode 告警)
③ 路由树按 severity 分发不同通知渠道 ④ 维护窗口用 Silence 临时静音。最关键的是 for 时窗 + repeat_interval 配对,否则要么漏报要么刷屏。
### FAQ
Q: 为什么我的告警每天几百条?
A: 八成是 group_by 没配好 + repeat_interval 太短。同一个实例上同一类告警每 4 小时重复发一次,10 个实例 × 10 条规则 = 每天 240 条重复告警。 先把 group_by 改成 [alertname, cluster] 这种业务维度,repeat_interval 配到 2h 以上,量就下来了。
Q: Inhibit 配了但告警还是都来?
A: 最常见原因:labels 名不一致。比如磁盘告警 label 叫 `mountpoint`,inode 告警叫 `path`,Inhibit 里 match_source / match_target 对不上就无效。 用 `alertmanager check-config` 检查配置合法性,再用 Web UI 的 Alert 页面逐条验证 labels。
Q: 维护窗口怎么临时屏蔽告警?
A: 用 Silence 而不是 Inhibit。Silence 是"暂时不报",到期自动解除;Inhibit 是"依赖关系屏蔽",始终生效。 维护前加一条 Silence,到期自动清除。千万别手动删告警规则,那不是维护窗口该有的操作。
Q: 严重告警(P0)怎么保证一定有人看到?
A: 路由树里把 P0 单独走一个 receiver,同时配置多渠道(邮件 + 企业微信 + 电话)。 repeat_interval 配短(30m),每次重复都确保有人在。 最重要:配一个"无人认领"兜底——连续 3 次未确认的 P0 告警自动升级到上一级负责人。
### Full Content
# Alertmanager 告警降噪实战:抑制器 + 路由树 + 静默配置四步降噪法
2024 年冬天,我们线上发生过一次事故:[Prometheus](https://prometheus.io/docs/) 监控到了 300+ 条告警,运维群里 5 分钟内刷了 2000 多条消息。值班人看了 10 分钟才发现真正的问题——磁盘满,其余 299 条都是衍生告警。这件事之后,我们花了两周把 Alertmanager 告警降噪做了一遍,现在每天活跃告警不到 10 条,重要告警秒级触达。
## 告警风暴的根因:三层失控
一个健康的告警系统应该做到:**重要告警不漏,次要告警不烦**。生产环境告警失控,本质是三层出了问题:
```
第一层:告警规则层 —— for 时窗太短,抖动就报警
第二层:分组层 —— group_by 维度不对,同类告警散落各处
第三层:抑制层 —— 没有依赖关系,衍生告警全报
```
下面按这四步走,把告警从几百条降到个位数。
## 步骤一:给告警规则加 for 时窗
告警规则的 `for` 字段是最简单的降噪手段,很多人忘了加。
```yaml
groups:
- name: host-alerts
rules:
- alert: HighCpu
expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 10m # ← 必须加!没有 for 就是瞬时抖动也报警
labels:
severity: warning
annotations:
summary: "CPU 使用率超过 80% 持续 10 分钟"
```
**原则**:
| 指标类型 | 建议 for 时窗 | 理由 |
|---|---|---|
| CPU / 内存 | 5-10m | 短时尖峰是正常的 |
| 磁盘使用率 | 5m | 磁盘增长是渐变过程 |
| 进程存活 | 1m | 进程崩了不能等 |
| 网络延迟 | 5m | 网络抖动常见 |
| 错误率 | 3m | 瞬时 500 不一定是问题 |
**踩坑实录**:我们把 `HighCpu` 的 `for` 从 0 改成 10m 之后,告警数量从每天 40 条降到 3 条——因为 90% 的 CPU 告警都是Deployment 启动时的短暂尖峰。
## 步骤二:正确设置 group_by
`group_by` 决定了同类告警如何合并。配错了,同一故障会产生几十条独立告警。
```yaml
route:
group_by: ['alertname', 'cluster', 'service'] # 按业务维度分组
group_wait: 10s # 等 10 秒收集同类告警一起发
group_interval: 5m # 同组告警 5 分钟内不重复发
repeat_interval: 4h # 未恢复告警每 4 小时提醒一次
```
**group_by 错误示例(翻车)**:
```yaml
# ❌ 按 instance 分组 → 同一 alert 在 10 个实例上各发一条,完全独立
group_by: ['instance']
# ✅ 按业务分组 → 同一故障的多个实例合成一条告警
group_by: ['alertname', 'cluster', 'service']
```
**踩坑实录**:有一次 [Kubernetes](https://kubernetes.io/docs/) 集群扩容,Alertmanager 因为 `group_by: ['instance']` 给每台新 Pod 发了独立的 `HighMemory` 告警,30 台 Pod 瞬间 30 条告警。改成 `group_by: ['alertname', 'namespace']` 后,整个 namespace 只报一条。
## 步骤三:配置 Inhibit 抑制器
抑制器是告警降噪的核心武器。它的逻辑是:**当 A 告警存在时,自动屏蔽 B 告警**,前提是 B 是 A 的衍生告警。
```yaml
inhibit_rules:
# 磁盘满时,抑制 inode 告警(磁盘满了 inode 肯定也满)
- source_matchers:
- severity = critical
- alertname = DiskFull
target_matchers:
- alertname = DiskInodeFull
equal: ['instance']
# 节点 NotReady 时,抑制该节点上的所有 Pod 告警
- source_matchers:
- alertname = NodeDown
target_matchers:
- severity = warning
equal: ['instance']
# 集群级别的网络分区,抑制所有单实例告警
- source_matchers:
- alertname = NetworkPartition
- severity = critical
target_matchers:
- severity = warning
equal: ['cluster']
```
**抑制器设计原则**:
1. 只在**因果关系明确**时配置,不要为了少报而抑制
2. `equal` 字段必须精确,不然会误抑制其他实例的正常告警
3. 先开 Inhibit,再验证——每天检查一次"被抑制的告警"列表,确认没有误伤
**踩坑实录**:我们配置过一条 `NodeDown` 抑制所有 `warning` 告警的规则,结果某次节点故障时,一条真正的 `warning` 级别磁盘告警被抑制了——那条磁盘告警其实和节点故障无关,是另一块磁盘的问题。后来把 `equal: ['instance']` 加上,才修正了这个问题。
## 步骤四:路由树按 severity 分发
路由树解决的是"谁在什么情况下该收到什么通知"。
```yaml
route:
receiver: 'default-receiver'
group_by: ['alertname', 'cluster', 'service']
group_wait: 10s
group_interval: 5m
repeat_interval: 4h
# P0 告警:直接电话 + 企业微信,30 分钟重复
routes:
- matchers:
- severity = critical
receiver: 'p0-oncall'
repeat_interval: 30m
continue: false
# P1 告警:企业微信,4 小时重复
- matchers:
- severity = warning
receiver: 'p1-wechat'
repeat_interval: 4h
continue: false
# P2 告警:邮件,24 小时重复
- matchers:
- severity = info
receiver: 'p2-email'
repeat_interval: 24h
continue: false
```
**receivers 配置示例**:
```yaml
receivers:
- name: 'p0-oncall'
webhook_configs:
- url: 'http://alert-router:8080/p0' # 转发到电话回调系统
wechat_configs:
- corp_id: 'your-corp-id'
agent_id: 'your-agent-id'
to_party: 'oncall-team'
api_secret: '{{ secret }}/wechat_secret'
- name: 'p1-wechat'
webhook_configs:
- url: 'http://alert-router:8080/p1'
- name: 'p2-email'
email_configs:
- to: 'ops-team@company.com'
send_resolved: true
- name: 'default-receiver'
webhook_configs:
- url: 'http://alert-router:8080/default'
```
## 四个翻车案例复盘
### 案例 1:Silence 配错导致真告警被屏蔽
**现象**:维护窗口加了 Silence,结果维护结束后 Silence 还在,正常告警全被吞了。
**根因**:Silence 到期时间配错了——配的是维护开始时间而不是结束时间。
**教训**:加 Silence 时 double-check 到期时间,养成习惯:维护结束前手动验证 Silence 是否还在生效。
### 案例 2:Inhibit 误伤导致漏报
**现象**:节点故障时,所有 warning 告警被抑制,包括一块与节点故障无关的磁盘告警。
**根因**:Inhibit 规则 `equal` 字段不够精确,缺少 `service` 维度。
**教训**:每条 Inhibit 规则必须经过"反向验证"——问自己"这条规则在什么情况下会误抑制正常告警?"
### 案例 3:group_wait 太长导致告警延迟
**现象**:P0 告警发出时已经过了 5 分钟,值班人员说"等我看完这条再处理,结果第一条已经过时了"。
**根因**:`group_wait: 30s` 对于 P0 太长了,P0 应该 5s 内发出。
**教训**:不同 severity 的 `group_wait` 要分开配,P0 用 5s,P1 用 10s,P2 用 30s。
### 案例 4:repeat_interval 太短导致告警疲劳
**现象**:一条 P1 告警每 30 分钟重复发一次,值班人员看了两天后直接屏蔽了通知。
**根因**:`repeat_interval: 30m` 太短,告警疲劳导致忽略。
**教训**:P1 至少 2h,P2 至少 12h。告警疲劳比告警缺失更危险——人习惯了不处理。
## 降噪效果对比
| 指标 | 降噪前 | 降噪后 |
|---|---|---|
| 日均告警数 | 350+ | 8-12 |
| P0 告警发现时间 | 平均 15 分钟(在噪音中找) | < 2 分钟 |
| 误报率(无效告警) | ~40% | < 5% |
| 值班人员告警疲劳 | 高(每天刷几百条) | 低(每天处理不到 10 条) |
## 降噪上线后的持续维护纪律
降噪做完不是终点,我给自己定了几条长期纪律,防止它慢慢「反弹回噪音」。
**每月对账一次告警总量趋势。** 我把日均活跃告警数打点成 metric 看趋势。降噪后稳在 10 条左右,一旦某天爬到 30 条以上,通常是有人新加了没配 `for` 时窗的规则、或者 `group_by` 又被改粗了。这条趋势线比任何单条告警都更能反映系统健康——它会先于真实事故提示「噪音在回升」。
**每次改抑制器都做反向验证。** 加一条 Inhibit 前我固定问自己两个问题:「这条规则在什么情况下会误伤一条正常的告警?」「如果 source 告警漏报了,被抑制的 target 会不会跟着一起看不见?」踩过一次 `NodeDown` 误伤无关磁盘告警的亏后,我把每条抑制规则都配了「被抑制告警」的旁路日志,每天扫一眼被抑制列表,确认没有误伤才放行。
**Silence 必须带 comment 且到期自动清。** 我给团队立了规矩:任何手动 Silence 必须写清「谁、为什么、到几点」,没 comment 的 Silence 会被自动巡检脚本标记。最怕的就是「维护完忘了撤 Silence」,导致接下来一周真告警全被吞。把 Silence 的到期时间校验进发布流程,比靠人记可靠。
**新规则入库前过一道噪音评审。** 任何要上线的告警规则,我要求先在灰度环境跑 48 小时看它触发频率,触发超过每天 5 次就说明阈值设太松、或该规则本身就是噪音源,打回重设。没有这道闸,降噪成果会被零散的新规则一点点蚕食回去。
## 写在最后
告警系统的核心目标不是"报得全",而是"报得准"。降噪不是一次性工程,是需要持续维护的——每加一条告警规则,都要问自己:这条规则会不会产生噪音?会不会被其他规则覆盖?会不会和现有抑制器冲突?
把告警当成产品来做,降噪就是它最重要的用户体验。
## 相关文章
- [Alertmanager 告警规则配置:路由树 + Silence/Inhibit + 微信钉钉 Webhook 六坑指南](prometheus-alerting.md)
- [PromQL 速查:5 类黄金指标 rate/irate/histogram_quantile 陷阱与 20 条可复制模板](prometheus-query.md)
- [Prometheus Recording Rules 实战:预计算指标提升查询性能与降低告警延迟](prometheus-recording-rules.md)
---
## 堡垒机选型与 JumpServer 部署
URL: https://ops.jiunotes.top/monitor/bastion-jumpserver.md
摘要: 自建 vs 商业堡垒机 TCO 分析、JumpServer 部署要点、开源堡垒机对比、审计与权限管理。
### Answer
堡垒机选择:团队 < 20 人自建 JumpServer;< 100 人考虑商业(JumpServer 企业版 / 阿里云堡垒机);> 100 人上云。TCO 大头是运维时间。
### FAQ
Q: 自建 JumpServer 还是买商业堡垒机?
A: 看规模。团队 <20 人自建 JumpServer 最划算;<100 人商业版(JumpServer 企业版 / 阿里云堡垒机)省运维;>100 人或强合规要求直接上云。TCO 大头是自建的运维时间。
Q: JumpServer 部署最常踩的坑?
A: 数据库连接串配置错误、Nginx 反代 WebSocket 未开、Redis 与服务器时区不一致导致登录态异常。部署前先确认这三项。
Q: 堡垒机审计日志怎么留?
A: 至少保留 180 天,建议 1 年。开启命令审计 + 录像(session replay),日志异地备份,配合 SIEM 做异常登录告警。
Q: 高危命令如何管控?
A: 用命令过滤(command filter)+ 强制审批:rm -rf、chmod 777、dd 等加入黑名单,高危操作需工单审批后才放行。
### Full Content
# 堡垒机选型与 JumpServer 部署
> **适用场景**:中小团队想要统一管控 SSH/RDP 访问、留下审计痕迹,又不想一上来就花大钱上云。这篇文章给一套可落地的选型与部署方案。
## 选型矩阵
| 团队规模 | 建议方案 | 年成本 |
|---|---|---|
| < 20 人 | JumpServer 社区版 | 免费 + 运维时间 |
| 20-100 人 | JumpServer 企业版 | 1-3 万 |
| > 100 人 | 阿里云堡垒机 / 腾讯云 | 按量计费 |
## JumpServer 部署要点
1. **硬件**:2C4G 起,MySQL 独立实例
2. **部署方式**:[Docker](https://docs.docker.com/) Compose 或原生
3. **初始账号**:`admin / Changelog`(部署脚本生成)
4. **接入资产**:批量导入 SSH key 或密码
5. **权限组**:按角色分配
## 我实际部署踩的坑
团队 30 人左右时我从零起过一套 JumpServer,复盘几个真实问题:
- **数据库别用 Docker 内置的 MySQL**:早期我图省事用 compose 里自带的 MySQL,一次 `docker system prune` 差点把 180 天的审计库清空。后来迁到独立 MySQL 实例,审计库还单独做了 binlog 备份异地同步。审计数据是等保要查的硬指标,丢了就麻烦。
- **Nginx 反代 WebSocket 一定要开**:浏览器终端(Web Terminal)走的是 WebSocket,Nginx 默认 `proxy_http_version 1.0` + 没设 `Upgrade`/`Connection` 头,终端一连就 502。配置要点:`proxy_http_version 1.1;` + `proxy_set_header Upgrade $http_upgrade;` + `proxy_set_header Connection "upgrade";`。
- **时区必须一致**:Redis 和 JumpServer 服务器时区不一致时,登录态 token 的过期判断会飘,表现是「刚登进去过一会儿就掉线要重登」。统一 `TZ=Asia/Shanghai`,Redis 的 `CONFIG SET timezone` 也一起设。
- **初始口令 `Changelog` 改完要落库**:deploy 脚本生成的初始口令只在第一次进管理台时强制改,很多人改完忘了把 `.env` 里对应的环境变量清掉,下次重启又跳回旧口令,登录报错。改口令后确认 `DB_PASSWORD` 等环境变量已同步。
## 命令管控与审批落地
`rm -rf /`、`chmod 777`、`dd of=`、`mkfs` 这类命令是审计和事故的高发区。我这边这么管的:
1. **命令过滤(command filter)配黑名单**:`rm`、`dd`、`mkfs`、`chmod 777`、`iptables -F`、`systemctl stop` 高危服务统一加规则,命中直接拦截并记录告警。
2. **高危操作走强审批**:命中黑名单不是一刀切全断,而是走「工单 + 双人审批」流程,审批通过生成一次性临时口令/免审令牌,过了就自动过期。这样既留痕又不至于把正常运维卡死。
3. **白名单优先于黑名单**:对 DBA、SRE 这类高频操作角色,用白名单放通常规命令(`systemctl status`、`journalctl -u xxx`),减少误拦。黑名单兜底拦截未知高危。
命令过滤要按「命令 + 参数 + 目标主机」三元组匹配,别只匹配命令本身——`rm -rf /tmp/cache` 和 `rm -rf /` 都命中 `rm`,得把路径模式也拉进规则里。
## 审计与合规视角
按等保 / 内部审计要能自证,审计这套要完整:
- **命令审计 + 会话录像(session replay)** 两条都要开,命令审计查「做了什么」,录像查「怎么做的」,等保评审两样都要。
- **日志异地留存 ≥ 180 天,建议 1 年**,并做定期对象存储归档,避免堡垒机自身故障导致审计链断裂。
- **对接 SIEM**:登录失败、高危命令命中、非工作时间登录、跨域 IP 登录这几类事件推给 SIEM 做实时告警,别等出事了再翻日志。
- **账号生命周期**:离职人员账号当天禁用,权限组按「最小可用」分配,避免一人多权限组叠加大权限。
## 性能、容量与升级
- **资源规划**:并发数直接决定内存。经验值每个活跃 Web 会话约 200-400MB,50 并发预留 16G 内存比较稳,CPU 2C 起步。
- **录像存储**:RDP 录像体积不小(每路 30-80MB/小时),按「保留天数 × 并发路数 × 峰值大小」估算,别等磁盘写满才发现审计断了。
- **升级要备份数据库**:JumpServer 跨版本升级前 `mysqldump` 全备 + 配置目录备份,升级脚本失败可回滚。我在预发环境先升一遍验证兼容,再上生产。
- **社区版 → 企业版迁移**:功能差异集中在多租户 / LDAP / SAML / 录像回放 / 合规报表,社区版数据在企业版基本可复用,但 SSO 配置要重新对接,预留一次完整的身份系统联调时间。
## 日常运维 SOP
把上面这些沉淀成每天 / 每周的例行动作,堡垒机才不会出现「部署完就荒废」:
- **每日**:看一眼登录失败与高危命令告警面板,命中即人工复核;确认录像归档任务昨夜跑成功。
- **每周**:核对账号与权限组,离职人员账号 24 小时内禁用,新增成员按最小权限分配。
- **每月**:全备一次数据库 + 配置,异地校验可恢复;演练一次从备份还原,验证审计链未断裂。
- **每季度**:按当前并发与录像保留期重新算一次资源与存储容量,磁盘水位超 70% 提前扩容,别等写满才发现。
## FAQ
- q: JumpServer 社区版和企业版有什么区别?
a: 核心功能差异主要在:企业版支持多租户、LDAP/AD 集成、SAML SSO、操作录制回放、合规报表导出。社区版适合小团队自用;一旦需要审计留痕、对接现有身份系统,企业版是刚需。别被营销话术迷惑——功能上企业版就是给"要过等保/ISO"的团队准备的。
- q: 部署 JumpServer 最容易踩的坑是什么?
a: 三个高频坑:① MySQL 用 Docker 内置的,生产环境数据丢失风险高,建议独立 MySQL 实例;② 初始密码 `Changelog` 改完没同步到配置,导致后续登录报错;③ 资产批量导入用 CSV 编码不对,中文乱码。第一次部署建议先测一遍完整流程再上生产。
- q: JumpServer 支持 RDP 和 VNC 吗?
a: 支持。RDP 用于 Windows 资产,VNC 用于图形化 [Linux](https://www.kernel.org/doc/html/latest/) 或 macOS。但注意:VNC 性能较差,远程桌面建议走 RDP 协议。录制回放功能对 RDP 支持最好,VNC 录制的画面清晰度有限。
- q: 审计日志能保留多久?怎么导出?
a: 默认按配置保留(通常 6 个月到 1 年)。导出需要企业版或手动备份数据库。重要操作建议定期导出归档到对象存储,避免单点故障导致审计链断裂。
- q: 和阿里云/腾讯云堡垒机比,自建值不值?
a: 算一笔账:云堡垒机按并发通道收费,20 人团队每月几百到上千;自建 JumpServer 一次性投入服务器成本 + 运维时间。团队 < 20 人且有一定运维能力,自建 TCO 更低;> 50 人或不想折腾运维,直接上云更省心。
## 相关文章
- [SSH 加固:密钥登录 + Fail2ban](ssh-hardening.md)
- [Alertmanager 告警降噪实战:抑制器 + 路由树 + 静默配置四步降噪法](alertmanager-noise-reduction.md)
- [DevSecOps 安全左移:CI/CD 集成扫描策略,从 SAST/DAST 到供应链安全完整指南](devsecops-security.md)
- [Platform Engineering 平台工程:IDP 内部开发者门户从 0 到 1 建设实战](platform-engineering.md)
---
## Blackbox Exporter 探针配置实战:多协议探测 + SLO 设计 + K8s ServiceMonitor 集成
URL: https://ops.jiunotes.top/monitor/blackbox-exporter.md
摘要: Prometheus Blackbox Exporter 生产配置实战:8 种协议模块(HTTP/TCP/UDP/gRPC/DNS/Ping/ICMP)、SLO 三指标设计(可用性/延迟/错误率)、K8s ServiceMonitor 集成、5 个真实翻车案例、完整生产模板。
### Answer
Prometheus Blackbox Exporter 是黑盒探活核心。生产配置三块:模块(http_2xx / tcp_connect / dns_lookup / grpc / icmp 等)、SLO 三指标(成功率/延迟P99/错误率)、告警(探针超时/连续失败/N 次失败)。本文给 8 种协议完整模块 + K8s ServiceMonitor 集成 + 5 个真实翻车案例(探针超时误报、DNS 解析慢、TLS 证书问题、代理绕过、K8s ClusterIP 访问不通)。
### FAQ
Q: Blackbox Exporter 和 node_exporter 有什么区别?
A: node_exporter 是内部视角,采集本机 CPU/内存/磁盘等系统指标;blackbox_exporter 是外部视角,从 Prometheus 主动探测目标服务的可用性、延迟和状态码。前者看主机健康,后者看服务健康,两者互补。
Q: http_2xx 模块和 http_4xx 模块怎么选?
A: http_2xx 检查响应状态码是否在 200-399 范围,http_4xx 检查是否在 400-499 范围。一般生产用 http_2xx,因为 4xx 说明有 bug(404 路径错误、401 鉴权问题),5xx 说明服务挂了。http_4xx 模块主要给故意设计的探测用(比如探测故意 401 的鉴权 API)。
Q: K8s 内部部署 Blackbox Exporter 怎么配置?
A: 在 Pod 内跑 blackbox_exporter,通过 K8s ServiceMonitor 让 Prometheus 抓取 /probe 端点。K8s Service 的 ClusterIP 和 NodePort 都能被探测;跨命名空间要加 NetworkPolicy;跨集群要走 Ingress 域名。
Q: SLO 三指标怎么选阈值?
A: 成功率:99.9%(一天允许 43 秒不可用);延迟 P99:2s 内(用户可感知上限);错误率:0.1% 以上告警。这几个是行业通用值,具体场景可以调,比如内部系统可以放宽到 99.5%,用户端登录接口必须 99.99%。
### Full Content
# Blackbox Exporter 探针配置实战:多协议探测 + SLO 设计 + K8s ServiceMonitor 集成
上周有个项目的教训我到现在还记得:node_exporter 显示一台机器的 CPU、内存、磁盘全绿,[Prometheus](https://prometheus.io/docs/) 也抓到了它的 exporter,一切正常。结果用户群里突然炸了——"你们系统打不开了"。
问题出在 [nginx](https://nginx.org/en/docs/) 前面挂了一层 CDN,CDN 到源站的证书链不完整,客户端 TLS 握手失败,但源站自己探测自己是通的。这就是典型的**白盒探针盲区**:node_exporter 站在主机内部看世界,它只能告诉你"我这台机器活着",不能告诉你"用户能不能连上你的服务"。
这就是 blackbox_exporter 存在的意义。它是 Prometheus 生态里唯一以"外部视角"主动探测目标可用性的组件。装完就能用不难,难的是从"能用"到"生产可用"——模块怎么选、超时怎么配、SLO 怎么算、告警怎么不刷屏、[K8s](https://kubernetes.io/docs/) 里怎么不出岔子。这篇文章按我这几年踩出来的路写一遍。
## 1. 白盒探针的盲区:为什么必须上黑盒
先讲清楚白盒(内部指标)和黑盒(外部探测)的分工:
| 维度 | 白盒(node_exporter / kube-state-metrics / app 自定义指标) | 黑盒(blackbox_exporter) |
|------|------|------|
| 视角 | 主机/进程内部 | 网络外部,模拟真实客户端 |
| 能看到的故障 | CPU、内存、磁盘、进程崩溃、指标异常 | DNS 解析慢、TLS 握手失败、CDN 缓存失效、路由黑洞、防火墙丢包 |
| 探测方式 | 被动暴露 `/metrics` | 主动发起 HTTP/TCP/DNS/Ping 探测 |
| 数据语义 | "我这台机器活着" | "用户能不能访问到你" |
| 典型盲区 | CDN、网关、DNS、防火墙问题对它不可见 | 内部资源消耗、代码 bug 不可见 |
真实场景里,**至少 40% 的"服务不可用"是白盒看不见的**——DNS 记录过期、CDN 节点故障、防火墙策略误删、运营商 BGP 抖动。这些都是 node_exporter 报不出来的。
我坚持一条原则:**关键业务链路(登录、下单、支付)必须至少有一个跨机房、跨运营商视角的黑盒探针**,本地探针再准也不够。
## 2. 模块体系:8 种协议的完整对照
blackbox_exporter 的模块(module)定义了"怎么探测"。官方文档列了 10 多种,生产用得最多的是下面这 8 种:
| 模块 | 协议 | 探测内容 | 典型用途 | 常见超时 |
|------|------|---------|---------|---------|
| `http_2xx` | HTTP(S) GET | 状态码 ∈ [200,399] | 99% 的 Web 服务探测 | 5s |
| `http_4xx` | HTTP(S) GET | 状态码 ∈ [400,499] | 探测故意 401/404 的鉴权 API | 5s |
| `http_post` | HTTP POST | 自定义 body + 状态码 | 探测登录、下单等写接口 | 5s |
| `tcp_connect` | TCP 三次握手 | 端口是否 accept | MySQL/Redis/自定义 TCP 服务 | 3s |
| `udp_connect` | UDP | 发起 UDP 探测 | DNS/NTP/SNMP(注意丢包误报) | 3s |
| `dns_lookup` | DNS over TCP/UDP | A/AAAA/MX 记录 | 检查 DNS 记录正确性 | 3s |
| `grpc` | gRPC health check | HealthCheck RPC | gRPC 微服务 | 5s |
| `icmp` | ICMP Ping | 往返延迟 + TTL | 网络层通断(部分防火墙丢 ICMP) | 3s |
选模块的思路:**先看协议**(HTTP/TCP/UDP/gRPC/DNS),**再看探测目标类型**(Web 页面 / 内部 RPC / 数据库 / DNS 记录),**最后考虑是否需要自定义请求**(比如带 Cookie、带 Header 的登录探测)。
## 3. 完整 blackbox.yaml 生产模板
下面这份 60 行模板我用了 3 年,从电商到内部平台都在跑。注释里写清楚了每个字段为什么这么配:
```yaml
# /etc/blackbox_exporter/blackbox.yaml
modules:
# 通用 Web 服务探测,生产主力
http_2xx:
prober: http
timeout: 5s
http:
valid_status_codes: [200, 201, 204, 301, 302]
preferred_ip_protocol: ip4
method: GET
headers:
User-Agent: ["jiunotes-probe/1.0"]
tls_config:
insecure_skip_verify: false # 生产务必 false
follow_redirects: true
no_follow_redirects: false
# 内部健康检查端点,允许 204 空响应
http_internal:
prober: http
timeout: 3s
http:
valid_status_codes: [200, 204]
method: GET
headers:
X-Internal-Token: ["${INTERNAL_TOKEN}"]
fail_if_body_matches_regexp: ["error", "panic"]
fail_if_not_regex_match: ["OK"]
# MySQL/Redis 端口连通性
tcp_connect:
prober: tcp
timeout: 3s
tcp:
preferred_ip_protocol: ip4
query_response:
- send: "PING\r\n"
expect: "+PONG\r\n"
timeout: 2s # [Redis](https://redis.io/docs/) 特有:能顺便验证服务存活
# DNS 记录校验:验证 A 记录指向正确 IP
dns_lookup:
prober: dns
timeout: 3s
dns:
transport: tcp
prefer_ipv6: false
domain_name: example.com
query_name: api.example.com
query_type: A
valid_answer_codes: ["NOERROR"]
valid_answers: ["203.0.113.10", "203.0.113.11"]
# gRPC 微服务健康检查
grpc:
prober: grpc
timeout: 5s
grpc:
preferred_ip_protocol: ip4
tls: true
tls_config:
insecure_skip_verify: false
use_tls: true
server_name: api.internal.example.com
# ICMP:仅在网络监控场景用,应用层探测不推荐
icmp:
prober: icmp
timeout: 3s
icmp:
preferred_ip_protocol: ip4
timeout: 3s
packet_loss: 0.3 # 30% 以下丢包算成功
```
`valid_answers` 那个字段是隐藏福利——不光验证 DNS 能不能解析,还能验证"是不是解析到了我们期望的 IP"。CDN 切换、DNS 污染这类问题一秒就能发现。
## 4. 探测端点 `/probe` 详解
blackbox_exporter 只有一个 HTTP 端点:`/probe`。所有探测都通过 query 参数控制。
```bash
# 最基础的用法
curl -G --data-urlencode "module=http_2xx" \
--data-urlencode "target=https://api.example.com" \
http://blackbox:9115/probe
```
三个关键参数:
- **`target`**:要探测的目标。HTTP 探测可以是 URL(含 scheme),TCP/UDP 探测是 `host:port`。
- **`module`**:模块名,缺省用 `http_2xx`。
- **`?target=xxx&module=yyy`** 之外的参数一律忽略,不合法 target 会返回 400。
**URL 编码陷阱**:target 里有 `?` `&` `=` 时必须 URL 编码,不然会被解析错。curl 的 `-G --data-urlencode` 是标准解法:
```bash
# 错误:& 被解析成第二个参数
curl "http://blackbox:9115/probe?target=https://a.com/path?a=1&b=2&module=http_2xx"
# 正确:--data-urlencode 自动编码
curl -G --data-urlencode "target=https://a.com/path?a=1&b=2" \
--data-urlencode "module=http_2xx" \
http://blackbox:9115/probe
```
另一个坑:**Prometheus 的 scrape config 里 target 也要小心**。用 ServiceMonitor 时 `params.target` 会被自动编码,但手写 `static_configs` 时要自己注意:
```yaml
scrape_configs:
- job_name: "blackbox-http"
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets:
- https://api.example.com
- "192.168.1.100:6379" # TCP 探测写 host:port
relabel_configs:
# 关键三步:把 __address__ 替换为真正要探测的 target
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: blackbox-exporter:9115
```
三段 relabel 的顺序不能乱,`__address__` → `__param_target` 那步是"把要探测的目标搬进参数",最后那步"把抓取地址指回 blackbox 自己"。
## 5. SLO 三指标设计与 PromQL 实现
黑盒探测的原始指标只有三个,但足以算出 SLO 三指标:
- `probe_success`(0/1):本次探测是否成功
- `probe_duration_seconds`:本次探测耗时
- `probe_http_status_code` / `probe_dns_lookup_time_seconds` 等辅助指标
### 5.1 三个 PromQL 公式
```promql
# 指标 1:可用性(Availability)
# 语义:过去 1h 的成功率
avg_over_time(probe_success{target="api.example.com"}[1h])
# 指标 2:延迟 P99(Latency)
# 语义:过去 5m 内 99% 的探测在多少秒内完成
histogram_quantile(0.99, sum by (le) (rate(probe_duration_seconds_bucket[5m])))
# 指标 3:错误率(Error Rate)
# 语义:过去 10m 的失败次数占总探测次数比例
sum(rate(probe_success[10m])) * -1
```
前两个是核心 SLO,第三个是兜底告警。生产里我一般这样定目标:**可用性 ≥ 99.9%(1 天允许 43 秒不可用)、P99 延迟 ≤ 2s(用户可感知阈值)、错误率告警阈值 0.1%**。内部系统可以放宽到 99.5%,登录/支付接口必须 99.99%。
### 5.2 三条 recording rule
把这三个计算下沉成 recording rule,让告警规则和 [Grafana](https://grafana.com/docs/) 都直接引用,不用重复写复杂 PromQL:
```yaml
groups:
- name: blackbox-slo
interval: 30s
rules:
- record: slo:blackbox:availability:1h
expr: avg_over_time(probe_success[1h])
- record: slo:blackbox:latency:p99:5m
expr: |
histogram_quantile(0.99,
sum by (le, target) (rate(probe_duration_seconds_bucket[5m])))
- record: slo:blackbox:error_rate:10m
expr: |
1 - (sum(rate(probe_success[10m]))
/ sum(rate(probe_success[10m]) + rate(probe_success_offset[10m])))
```
第三条 rule 处理了 `probe_success` 被 relabel 成两条时序的情况——blackbox 每次探测会同时把 result(0/1)和 success(1)暴露成两个时间序列,直接 `rate(probe_success)` 会重复计,必须配合 `probe_success_offset` 抵消。这是很多人写错的地方。
## 6. K8s ServiceMonitor 集成
在 K8s 里部署 blackbox_exporter 用 Helm 装最快,但 ServiceMonitor 一定要自己写,不能靠默认模板。
```yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: blackbox-http-probes
namespace: monitoring
labels:
release: prometheus
spec:
selector:
matchLabels:
app: blackbox-exporter
endpoints:
- port: http-metrics
path: /probe
interval: 30s
params:
module: [http_2xx]
targetLabels: [target]
# 关键:把要探测的目标注入到 ServiceMonitor
namespaceSelector:
any: true
---
# 用 Service 承载要探测的目标列表(推荐做法)
apiVersion: v1
kind: Service
metadata:
name: external-probe-targets
namespace: monitoring
labels:
probe.type: http
spec:
ports:
- port: 80
name: http
clusterIP: None # headless service
```
三个必踩的坑:
**坑 1:ClusterIP 跨命名空间访问不通。** 如果你 blackbox_exporter 在 `monitoring` 命名空间,要探测的目标 Service 在 `default`,直接写 `Service.default.svc:80` 有时会被 CoreDNS 解析成"当前命名空间"的地址。必须写**全限定名**:`Service.default.svc.cluster.local:80`。
**坑 2:NetworkPolicy 拦住探针。** 目标 Service 所在命名空间如果配了 NetworkPolicy,blackbox_exporter 的 Pod 会被拒。解法两条:给 blackbox 的 Deployment 加特定 label(比如 `probe: blackbox`),在目标 Namespace 的 NetworkPolicy 里加一条 ingress allow;或者干脆用 NodePort + 节点 IP 绕过 Service 层。
**坑 3:Pod 探针和 blackbox 探针冲突。** 有些团队把 K8s 的 livenessProbe 和 blackbox 的 http_2xx 都打 `/healthz`,结果 blackbox 频繁探测导致 `/healthz` 后端慢查询被放大,反过来触发 liveness 失败重启 Pod。**解法:liveness 打轻量的 `/livez`(只检查进程活着),blackbox 打更重的 `/readyz`(检查依赖)**。
## 7. 5 个真实翻车案例
### 案例 1:DNS 解析慢导致 2s 超时告警误报
我们生产环境有个探测模块 timeout 设的 2s,某天开始报"api.example.com 探针超时",实际服务正常。排查发现是 CoreDNS 那个节点负载高,单次解析耗时 3-4 秒。
解法:`timeout: 5s` 起步,加 `dns: { transport: tcp }`(UDP 有时会被丢包导致超时),并把 DNS 解析时间单独记指标:
```promql
max by (target) (rate(probe_dns_lookup_time_seconds[1m]))
```
超过 1s 就单独告警,不要跟"服务超时"混在一起。
### 案例 2:TLS 证书链不完整
CDN 换了证书,只部署了叶子证书没带上 intermediate CA。客户端 curl 加了 `--cacert` 能通,blackbox 探测直接返回 0(握手失败)。
排查:`openssl s_client -connect host:443 -showcerts` 看证书链。**blackbox 里 `insecure_skip_verify: true` 只能应急用,生产必须 false**——否则 TLS 问题被吞掉,等用户报错才发现。
### 案例 3:出口代理绕过防火墙规则
我们机房出口走 squid 代理,某些服务配置了 no_proxy。blackbox_exporter 在容器里跑,没继承 no_proxy 环境变量,探测请求走了代理,被代理缓存的旧响应返回 200——实际后端已经挂了。
解法:容器环境里显式注入 `no_proxy`,或在 http 模块配置里禁用代理:
```yaml
http:
proxy_url: "" # 显式清空
```
### 案例 4:K8s ClusterIP 从跨命名空间访问不通
target 写 `api-service:8080`,blackbox 在 `monitoring` ns,`api-service` 在 `prod` ns,探测一直 0。
**根因**:DNS 解析时用了 shortname,CoreDNS 优先解析到"同命名空间"的记录,`monitoring` 下没有叫 `api-service` 的 Service,走了搜索域兜底有时失败。
解法:一律写全 FQDN:`api-service.prod.svc.cluster.local:8080`。这一条我已经在团队 wiki 写死了。
### 案例 5:UDP 模块被防火墙丢包但 ping 通
某内部服务用 UDP 端口 514(syslog),blackbox 的 `udp_connect` 报失败,但 `ping` 目标 IP 完全正常。
UDP 是"发完就走"的协议,防火墙默认丢 UDP 报文,`udp_connect` 探测其实**没有握手**,只能探测"是否被立即 ICMP unreachable"。这个模块天生不适合生产探测,改用 `tcp_connect` 探测 TCP 端口,或者上 Syslog 专用 exporter。
**结论:UDP 探测只在网络监控(比如 NTP 服务)场景用,业务服务一律不要用。**
## 8. 告警规则清单
8 条规则覆盖黑盒探测的所有关键场景:
```yaml
groups:
- name: blackbox-alerts
rules:
# 1. 探针失败:核心服务不可用
- alert: BlackboxProbeDown
expr: probe_success == 0
for: 2m
labels:
severity: critical
annotations:
summary: "黑盒探针失败:{{ $labels.target }}"
description: "{{ $labels.target }} 使用 {{ $labels.module }} 模块探测失败,请检查服务状态。"
# 2. 连续失败:区分抖动和真故障
- alert: BlackboxProbeUnstable
expr: |
changes(probe_success[10m]) > 4
for: 5m
labels:
severity: warning
annotations:
summary: "探针不稳定:{{ $labels.target }}"
# 3. 可用性跌破 99.9%(1h 窗口)
- alert: BlackboxAvailabilityBelowSLO
expr: slo:blackbox:availability:1h < 0.999
for: 15m
labels:
severity: critical
annotations:
summary: "可用性 SLO 失守:{{ $labels.target }}"
# 4. P99 延迟超过 2s
- alert: BlackboxLatencyP99High
expr: slo:blackbox:latency:p99:5m > 2
for: 10m
labels:
severity: warning
annotations:
summary: "P99 延迟 {{ $value }}s > 2s:{{ $labels.target }}"
# 5. DNS 解析慢(独立告警,别混在超时里)
- alert: BlackboxDnsLookupSlow
expr: max(probe_dns_lookup_time_seconds) by (target) > 1
for: 5m
labels:
severity: warning
annotations:
summary: "DNS 解析慢:{{ $labels.target }}"
# 6. HTTP 状态码异常(非 2xx)
- alert: BlackboxHttpStatusNon2xx
expr: probe_http_status_code == 0 or (probe_http_status_code >= 500)
for: 3m
labels:
severity: critical
annotations:
summary: "HTTP 状态码异常:{{ $labels.target }} => {{ $value }}"
# 7. TLS 证书即将过期
- alert: BlackboxTlsCertExpiring
expr: probe_httpTLSNotAfter - time() < 7 * 24 * 3600
for: 1h
labels:
severity: warning
annotations:
summary: "TLS 证书 7 天内过期:{{ $labels.target }}"
# 8. 错误率超过 0.1%
- alert: BlackboxErrorRateHigh
expr: slo:blackbox:error_rate:10m > 0.001
for: 10m
labels:
severity: warning
annotations:
summary: "错误率 {{ $value }} > 0.1%:{{ $labels.target }}"
```
`for` 时窗是黑盒告警的灵魂——`probe_success == 0` 单独看太敏感(一次抖动就报),配 `for: 2m` 意味着连续 2 分钟失败才报警,抖动场景自然过滤。
## 9. Grafana 面板
三块 widget 布局:
**顶行:KPI 概览**(3 个大数字)
- 可用性 %(`slo:blackbox:availability:1h`)
- P99 延迟(`slo:blackbox:latency:p99:5m`)
- 当前失败数(`sum(probe_success == 0)`)
**中行:单目标时间序列**
- Availability + P99 双 Y 轴
- 用 `target` 变量筛选,`$__rate_interval` 自适应窗口
**下行:状态码分布 + DNS 延迟**
- 状态码堆叠图(`sum by (probe_http_status_code) (rate(probe_success[5m]))`)
- DNS lookup 时延时间序列
Panel JSON 核心片段:
```json
{
"targets": [
{
"expr": "slo:blackbox:availability:1h{target=~\"$target\"}",
"legendFormat": "Availability 1h"
},
{
"expr": "slo:blackbox:latency:p99:5m{target=~\"$target\"}",
"legendFormat": "P99 Latency",
"yaxis": 2
}
],
"fieldConfig": {
"defaults": {
"custom": { "drawStyle": "line", "spanNulls": true },
"unit": "percentunit",
"thresholds": {
"steps": [
{"color": "red", "value": 0.95},
{"color": "yellow","value": 0.99},
{"color": "green", "value": 0.999}
]
}
}
}
}
```
## 10. FAQ
**Q1:Blackbox Exporter 和 node_exporter 怎么选?**
两者不冲突,一定要都用。node_exporter 是"我这台机器内部还好吗",blackbox_exporter 是"外面能连到我吗"。node_exporter 挂了不代表用户访问不了(可能只是 exporter 进程死了),blackbox_exporter 挂了也不代表主机有故障(可能是探针所在机房断网了)。生产环境我通常这样分工:node_exporter 全量部署,blackbox_exporter 部署 2-3 个跨机房实例,互相校验避免单点误报。
**Q2:http_2xx 和 http_4xx 到底怎么选?**
99% 场景用 http_2xx。http_4xx 只有在"故意设计成返回 4xx 的接口"才用——比如你的鉴权 API 期望未带 token 时返回 401,那 http_4xx 就是正确的探测模块。混用的话,比如一个健康检查端点设计成返回 200,你用 http_4xx 探测就会永远失败。**判断依据:先看接口设计文档,再决定模块**。
**Q3:K8s 内部怎么部署 blackbox_exporter?**
推荐 Helm 部署到 monitoring namespace,通过 ServiceMonitor 让 Prometheus 抓取。三个关键点:① target 一律用 FQDN 全限定名(`api.prod.svc.cluster.local:8080`)② 目标命名空间有 NetworkPolicy 时,给 blackbox Deployment 加 label 并在目标策略里放行 ③ 跨集群探测走 Ingress 域名,不要试图用 ClusterIP 跨集群访问。
**Q4:SLO 三指标阈值怎么定?**
通用值:可用性 99.9%(一天允许 43 秒不可用)、P99 延迟 2s、错误率 0.1%。这几个数字不是拍脑袋来的——99.9% 对应"每天 43 秒"的常见可用性合约,2s 是 Google SRE 里"用户可感知"的经验阈值。具体场景要调:内部管理系统可以放宽到 99.5%,用户端登录接口必须 99.99%,静态资源 CDN 可以放宽到 99.95%。
**Q5:blackbox_exporter 自己挂了怎么办?**
黑盒探针本身也是个服务,也要监控。**元监控策略**:blackbox_exporter 部署成 StatefulSet 多副本 + 跨机房,配合 K8s livenessProbe 自保。Prometheus 侧配一条 `up{job="blackbox-exporter"} == 0` 的告警,探针挂了立即知道。我一般还会在异地部署一个"探针的探针"(用另一个 blackbox_exporter 探测第一个 blackbox_exporter),彻底避免监控盲区。
## 相关文章
- [node_exporter 指标缺失排查:6 大症状决策树 + 4 个常见翻车原因](node-exporter-troubleshoot.md)
- [Alertmanager 告警降噪实战:抑制器 + 路由树 + 静默配置四步降噪法](alertmanager-noise-reduction.md)
- [Grafana 部署与仪表盘搭建:从数据源接入到变量联动的六步路径](grafana-dashboard.md)
- [告警风暴半夜轰炸决策树:Alertmanager 重复、分组失效、静默降噪怎么治](monitor-alert-storm.md)
- [Grafana 大盘空白或数据错位决策树:图拉出来是空的怎么查](monitor-grafana-blank.md)
- [主机三件套 CPU / 内存 / 磁盘IO 怎么看才不误判:指标解读决策树](monitor-host-signals.md)
- [Prometheus 装好却没数据、Targets 全红决策树:装完监控却没指标怎么查](monitor-prometheus-no-data.md)
---
## 混沌工程 Chaos Engineering:主动韧性测试实战,从故障注入到生产演练
URL: https://ops.jiunotes.top/monitor/chaos-engineering.md
摘要: 混沌工程核心理念与实战:故障注入工具选型(Chaos Mesh/Litmus)、实验设计方法论、生产环境安全注入、以及三次事故复盘(含一次失败教训)。
### Answer
混沌工程的核心不是"制造故障",而是"主动验证系统在故障下的行为"。通过受控的故障注入,提前发现系统的脆弱点。
关键工具:Chaos Mesh(K8s 首选,功能最全)、LitmusChaos(阿里云出品,适合国内)、Chaos Blade(阿里开源,轻量级)。
最大风险:在生产环境注入故障时失控,导致真实事故。必须配合 experiment scope 限制、观察窗口、自动回滚机制。
### FAQ
Q: 混沌工程会不会把生产环境搞崩?
A: 会的,如果没做好边界控制。关键防御措施:① 先用 staging 环境验证实验设计;② 设置 experiment 的 scope(只影响特定 pod/service,不扩散);③ 配合自动回滚机制,注入失败时立即恢复;④ 选低峰时段执行。我们第一次在生产环境跑混沌实验就误杀了 3 个 production pod——后来加了 scope 限制再没出过问题。
Q: 混沌工程适合什么规模的团队?
A: 建议团队规模 ≥5 个服务、有 K8s 基础、有 oncall 轮值制度。小于这个规模,故障大多是人为操作失误,混沌工程解决不了;运维成本也太高。我们团队 8 个人、15 个服务时开始做混沌工程,效果最好。
Q: Chaos Mesh 和故障注入脚本有什么区别?
A: Chaos Mesh 是声明式的 CRD 控制器,能精确控制注入的时间、范围、持续时间,支持自动恢复。手写脚本可以模拟简单故障,但缺乏精确控制和自动恢复能力,不适合生产。我们的经验:简单场景用脚本够,复杂场景(如网络分区)必须用 Chaos Mesh。
Q: 混沌实验做出来发现系统扛住了,是不是没价值?
A: 有。"扛住了"本身就是可观测、可验证的韧性证据,比拍脑袋强。但要把实验的假设、注入参数、预期阈值、实际结果都归档留底,下季度复测时能对比有没有退化。纯"没出事"没有记录等于没做,实验要沉淀成可复现的 playbook 才算资产。
### Full Content
# 混沌工程 Chaos Engineering:主动韧性测试实战,从故障注入到生产演练
2023 年我们经历了一次生产事故:某个 pod 网络抖动导致服务间调用超时,级联故障让三个核心服务同时不可用。事后复盘发现,如果提前做过混沌实验,这个故障模式是可以被提前发现并修复的。从那之后我们开始系统性地引入混沌工程。
这篇分享从工具选型到生产实验的完整路径,包括三次实战案例和一次失败教训。
## 混沌工程的核心思维:假设驱动
混沌工程不是"随便扔故障",而是**基于假设的受控实验**:
```
1. 建立稳态假设
"这个服务在正常情况下应该 99.9% 可用,平均响应时间 <200ms"
2. 设计实验
"如果 kill 掉 50% 的 pod,服务还能维持稳态吗?"
3. 执行实验
注入故障 → 观察 → 记录
4. 验证假设
"假设成立:服务降级但可用,P99 延迟从 200ms 升到 800ms,仍在 SLA 内"
"假设不成立:服务完全不可用,需要修复依赖配置"
```
**关键原则**:实验必须有**假设**、有**观察指标**、有**回滚计划**。三者缺其一,不要执行。
## 工具选型:Chaos Mesh vs Litmus vs Chaos Blade
| 维度 | Chaos Mesh | LitmusChaos | Chaos Blade |
|---|---|---|---|
| 厂商 | 美团开源 | 阿里云开源 | 阿里开源 |
| [K8s](https://kubernetes.io/docs/) 支持 | **原生 CRD** | 原生 CRD | DaemonSet 方式 |
| 实验类型 | 丰富(网络/CPU/IO/Kernel) | 中等(偏 K8s) | 轻量(脚本为主) |
| 中文文档 | **优秀** | 良好 | 一般 |
| 社区活跃度 | 高 | 中高 | 中 |
| 学习曲线 | 中 | 低 | **最低** |
| 适合场景 | 生产级混沌实验 | 国内企业、合规需求 | 快速验证、简单场景 |
**我们的选择**:生产环境用 **Chaos Mesh**(功能最全、文档最好),staging 环境用 **Chaos Blade**(轻量、部署快)。
## 实验设计方法论:四步走
### Step 1:明确假设
```
假设:当 2 个 payment-service pod 同时 Crash 时,
剩余 pod 能承接全部流量,API 可用性不低于 99.5%
```
### Step 2:定义实验范围
```yaml
# chaos-mesh/pod-failure.yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
name: payment-pod-failure
namespace: payment-system
spec:
selector:
matchLabels:
app: payment-service
env: production
mode: fixed-count # 精确影响 2 个 pod
value:
count: 2
action: pod-failure # 杀掉 pod,不是模拟延迟
duration: '5m' # 5 分钟后自动恢复
scheduler:
cron: '@every 1h' # 每小时执行一次(实验窗口期)
```
**关键设计**:
- `mode: fixed-count`:精确控制影响范围,不会误伤其他服务
- `duration: 5m`:实验有上限,避免无限长故障
- `scheduler.cron`:低峰时段执行(凌晨 2-4 点),减少业务影响
### Step 3:定义观察指标
```yaml
# 实验期间必须持续观察的指标
- payment_service_request_success_rate # 成功率
- payment_service_latency_p99 # P99 延迟
- payment_service_error_count_5xx # 5xx 错误数
- payment_service_pod_healthy_count # 健康 pod 数量
- downstream_dependency_status # 下游依赖是否受影响
```
**原则**:观察指标必须在实验开始前就定义好,不能实验过程中临时想。实验的目的是验证假设,不是探索现象。
### Step 4:定义回滚条件
```yaml
# 满足任一条件立即终止实验
rollback_conditions:
- metric: payment_service_request_success_rate
condition: '< 0.95' # 成功率低于 95% 立即停止
- metric: payment_service_latency_p99
condition: '> 2000' # P99 超过 2 秒停止
- manual: true # 随时可以手动停止
```
## 实战案例一:Pod 死亡实验(成功)
**假设**:payment-service 的 50% pod 同时 crash 时,服务能自动恢复。
```bash
# 执行混沌实验
cmctl create podchaos payment-pod-failure -f chaos-mesh/pod-failure.yaml
# 观察实验效果
cmctl get podchaos payment-pod-failure
# 查看 [Grafana](https://grafana.com/docs/) 面板
# 对比实验前后 30 分钟的指标曲线
```
**结果**:
- ✅ 假设成立:自动扩容在 45 秒内完成,成功率保持 99.8%
- ⚠️ 发现次生问题:新 pod 启动时 DNS 解析有 2 秒延迟,导致少量请求超时
- 🔧 修复:在 K8s 的 kube-proxy 里加了 DNS cache TTL
**教训**:这个实验帮我们发现了**一个生产里永远不会出现的竞态条件**——扩容期间的 DNS 延迟。如果在生产里遇到,排查成本会高得多。
## 实战案例二:网络分区实验(失败)
**假设**:payment-service 和 DB 之间网络分区 30 秒,服务能优雅降级。
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: payment-db-network-partition
namespace: payment-system
spec:
selector:
matchLabels:
app: payment-service
targetSelector:
matchLabels:
app: postgres-primary
action: partition # 网络分区
direction: both # 双向阻断
duration: '30s'
```
**结果**:
- ❌ 假设不成立:payment-service 的连接池没有正确释放,DB 恢复后出现大量连接堆积
- 🔥 实际影响:故障持续 30 秒,但连接池恢复花了 8 分钟
- 💥 连锁反应:下游调用 payment-service 的服务也超时,两个服务同时不可用
**复盘**:这个实验失败的价值极高——它暴露了我们**从未测试过的故障场景**。修复方向:
1. DB 连接池加 `maxLifetime` 和 `idleTimeout` 参数
2. payment-service 加 circuit breaker(熔断器)
3. 下一个混沌实验专门验证 circuit breaker 是否生效
**这个案例说明**:混沌工程不是为了证明"系统是健壮的",而是为了**提前发现脆弱点**。失败比成功更有价值。
## 实战案例三:CPU 压力实验(部分成功)
**假设**:支付服务 CPU 利用率达到 90% 时,QPS 会自动限流,不会引发级联故障。
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata:
name: payment-cpu-stress
namespace: payment-system
spec:
selector:
matchLabels:
app: payment-service
mode: fixed-count
value:
count: 2
stressors:
cpu:
workers: 4
load: 80 # 80% CPU 负载
queues: 4
duration: '10m'
```
**结果**:
- ✅ 部分成立:QPS 确实下降了,但下降幅度(30%)超出预期(预期 10%)
- ⚠️ 发现新问题:CPU 压力下 GC 停顿时间从 50ms 跳到 800ms,导致单次请求延迟激增
- 🔧 修复:调整 JVM 堆内存大小 + G1 GC 参数
**关键洞察**:CPU 压力实验暴露了**GC 行为**这个肉眼看不到的问题。如果不是混沌工程,这个问题可能要等到生产大促时才会暴露。
## 安全红线:生产实验的五个约束
```
1. 范围约束:只能影响目标服务,不能扩散到上下游
2. 时间约束:低峰时段执行,时长有上限(最长 10 分钟)
3. 回滚约束:任一观察指标越界立即自动停止
4. 权限约束:实验执行者需要有 SRE 审批,不能单人操作
5. 通知约束:实验开始前必须在 Slack/钉钉通知相关团队
```
**硬性规则**:
- 生产环境每周最多 2 个混沌实验
- 大促前 7 天禁止任何混沌实验
- 必须先在 staging 环境完整跑一遍
## 实验归档与季度复测:让混沌沉淀成资产
混沌实验最大的浪费不是失败,而是「做完就散」——实验跑了、结论聊了、然后没有任何留存,下季度团队对同一个服务再跑一遍,发现它其实半年前就改过了,等于白做。我把每个实验当成一笔可复测的资产来管,四条纪律:
**每个实验建一个固定目录,假设与结果同档存放。** 目录里固定放四样东西:实验假设(原文)、注入用的 CRD/命令、观察指标快照(Grafana 面板的截图或导出的 JSON)、以及最终判定(成立/不成立/部分成立)。四样齐了才算一次有效实验,缺任何一样都标注「未闭环」,不许当完成处理。这样任何人翻存档,30 秒内就能复现当时的判断依据,不用靠记忆里那个「好像是 800ms」的模糊数字。
**判定必须带数值,不写「扛住了」三个字。** 「服务扛住了」不是结论,是描述。结论要写成「P99 从 200ms 升到 800ms,仍在 SLA(2s)内,判定成立」。把预期阈值和实际值都钉死,季度复测时直接对比:同一个实验,上季度 P99 升到 800ms,这季度升到 1600ms,哪怕没破 SLA,退化本身就该触发告警——**韧性是会随代码演进而悄悄退化的**,没有历史数值做基线,你永远不知道它退没退。
**复测节奏固定为季度,且只复测「上次发现问题的」实验。** 不是所有实验每个季度都重跑(成本高、价值低),而是优先复测上季度判定「不成立」或「部分成立」的那些——它们修复后到底有没有真修好,必须靠再跑一遍来确认,不能靠「应该修好了」的自信。上次那个连接池堆积的网络分区实验,修复后我们在下一季度专门重跑了一次,确认连接池恢复从 8 分钟降到 40 秒,这才把那个实验标记为「已闭环」。
**实验结果要反哺告警阈值。** 混沌实验测出来的真实阈值,比拍脑袋设的告警线更可信。比如 CPU 压力实验测出 GC 停顿在 800ms 时单次请求延迟才真正激增,那 GC 停顿的告警线就该设在这个量级,而不是凭经验设个 100ms。把实验数据写进监控规则,混沌工程的产出才真正接进了日常防线,而不是停留在一份没人看的报告里。
## FAQ
### Q: 混沌工程和 A/B 测试有什么区别?
混沌工程验证的是**系统可靠性假设**,A/B 测试验证的是**业务功能假设**。两者方法论类似(假设→实验→观察→结论),但目标不同:混沌工程的目标是发现脆弱点,A/B 测试的目标是找到最优业务方案。工具也完全不同——混沌工程用 Chaos Mesh,A/B 测试用业务平台。
### Q: 混沌实验失败了怎么办?
混沌实验"失败"(假设不成立)是**正常且有价值**的结果。关键是:
1. 记录实验过程和失败原因
2. 分析根因并制定修复计划
3. 修复后重新设计实验验证
4. 把实验过程整理成团队知识(runbook、postmortem)
**不要把"假设不成立"当成事故**,这是混沌工程的目的。
### Q: 如何说服管理层支持混沌工程?
用数据说话:
- 展示一次生产事故的成本(停机时间 × 每小时收入损失)
- 展示混沌实验发现的脆弱点数量(量化风险)
- 展示修复成本远低于事故成本
- 强调"主动发现" vs "被动救火"的区别
我们团队的做法:第一次混沌实验后出了一份 postmortem,包含"如果不做混沌实验,这次事故会造成多少损失"的估算。这份报告直接说服了 CTO 批准了混沌工程的年度预算。
---
## 相关文章
- [Blackbox Exporter 探针配置实战:多协议探测 + SLO 设计 + K8s ServiceMonitor 集成](blackbox-exporter.md)
- [GitOps 基础设施管理:ArgoCD/FluxCD 声明式部署实战与选型决策树](gitops-infra.md)
- [Kubernetes Pod 排障决策树:CrashLoopBackOff / ImagePullBackOff / Pending 五步定位法](kubernetes-pod-troubleshoot.md)
---
## 持续性能剖析:eBPF + Pyroscope 落地指南,从采样分析到线上性能优化实战
URL: https://ops.jiunotes.top/monitor/continuous-profiling.md
摘要: 持续性能剖析(Continuous Profiling)实战:Pyroscope 架构原理、eBPF 采样原理、CPU/内存热点分析、生产部署踩坑、以及一次真实性能优化案例(延迟从 500ms 降到 50ms)。
### Answer
持续性能剖析(Continuous Profiling)是监控栈的最后一块拼图——传统监控看"系统怎么了",性能剖析看"系统在干什么"。
Pyroscope 是最流行的开源 profiling 平台,支持 eBPF(无侵入)和 agent(语言级)两种采样模式。
核心价值:不用改代码就能看到 CPU/内存热点,生产环境实时运行,不影响业务性能。
最大限制:eBPF 模式只支持 Linux x86_64,Java/Go 性能剖析需要 SDK 配合。
### FAQ
Q: 性能剖析和传统的 profile 工具(pprof/perf)有什么区别?
A: 传统工具(pprof、perf)是"一次性采样"——你运行命令,得到一份快照,问题可能已经消失了。性能剖析是"持续采样"——每隔一段时间采一次样,积累成长期趋势,可以对比不同时间点的性能状态。Pyroscope 的优势在于:数据持久化、可视化、能对比历史版本。
Q: eBPF 性能和 SDK 性能哪个好?
A: 各有优劣。eBPF 零侵入(不用改代码),但只能采到系统调用层,看不到应用内部逻辑;SDK 精度更高(能看到函数调用栈),但需要改代码或在编译时插桩。最佳实践:eBPF 做系统级 profiling(CPU/内存/IO),SDK 做应用级 profiling(函数级热点)。
Q: Pyroscope 和 Prometheus/Grafana 是什么关系?
A: Pyroscope 是独立的 profiling 平台,但可以通过 OTLP 协议把数据导出到 Grafana。Pyroscope 有 Grafana plugin,可以直接在 Grafana 里看 flame graph。数据流:应用 → Pyroscope agent → Pyroscope server → Grafana。不是必须用 Pyroscope,也可以用其他后端(如 Parca)。
Q: 持续剖析会拖慢线上服务吗,采样率怎么定?
A: 会有一点开销,但可控。eBPF 模式开销极低(通常 <1% CPU),SDK 模式按采样间隔调,10s 采一次基本无感。 生产别追求 100% 采样——那是性能杀手,够用即可。上线后盯 agent 自身 CPU/内存,某服务被剖析时 CPU 明显跳升就要降采样间隔。
### Full Content
# 持续性能剖析:eBPF + Pyroscope 落地指南,从采样分析到线上性能优化实战
去年我们线上有一个 Go 服务,P99 延迟从 100ms 突然涨到 500ms,排查了两天没找到原因。最后用 Pyroscope 的持续性能剖析,30 分钟就定位到了——是 GC 停顿导致的,具体原因是某个热点路径上的 map 操作触发了频繁 Full GC。
如果用传统方法(pprof snapshot),这个 GC 问题很难复现,因为它是间歇性的。持续剖析的价值就在于此:**即使问题没有复现,历史采样数据里也留有痕迹**。
这篇分享 Pyroscope 的生产部署经验和一个真实的性能优化案例。
## Pyroscope 架构:三个核心组件
```
┌─────────────┐ ┌──────────────┐ ┌──────────────┐
│ Agent │────▶│ Pyroscope │────▶│ [Grafana](https://grafana.com/docs/) │
│ (采样 & 发送)│ │ Server │ │ (可视化) │
│ eBPF/SDK │ │ (存储 & 聚合) │ │ │
└─────────────┘ └──────────────┘ └──────────────┘
```
- **Agent**:嵌入在目标进程旁边(或 as sidecar),负责采样 CPU/内存火焰图
- **Pyroscope Server**:接收、存储、聚合 profiling 数据,提供查询 API
- **Grafana**:通过 Pyroscope plugin 展示火焰图和历史对比
## 两种采样模式:eBPF vs SDK
### eBPF 模式(推荐:零侵入)
eBPF 在内核层面采样,不需要改应用代码,适用于所有二进制程序。
```bash
# Pyroscope 官方推荐的 eBPF agent
# 安装 Pyroscope agent(作为 sidecar 或 DaemonSet)
docker run -d \
--name pyroscope-agent \
-v /proc:/host/proc:ro \
-v /sys:/host/sys:ro \
-v /:/rootfs:ro \
-e PYROSCOPE_APP_NAME=my-go-service \
-e PYROSCOPE_SERVER_ADDRESS=http://pyroscope-server:4040 \
--privileged \
pyroscopeio/pyroscope:latest \
agent \
--collectors=cpu,Memory,mutex,blocks
```
**eBPF 的限制**:
- 只支持 [Linux](https://www.kernel.org/doc/html/latest/) x86_64/arm64
- 内核版本 ≥ 4.9(建议 ≥ 5.4 带 BTF)
- 无法看到用户态语言的内部函数调用栈(如 Go 的 goroutine、Java 的 GC)
### SDK 模式(精度高)
针对特定语言,通过 SDK 在应用层采样,能看到完整的调用栈。
```go
// Go 语言:集成 pprof + Pyroscope exporter
import (
"go.pyroscope.io/godeltaprof/http/pprof"
pyroscope "go.pyroscope.io/pyroscope/pkg/client"
)
func init() {
pyroscope.Configure(pyroscope.Config{
ApplicationName: "my-go-service",
ServerAddress: "http://pyroscope-server:4040",
LogWriter: os.Stdout,
ProfilingEnabled: map[pyroscope.ProfileType]bool{
pyroscope.ProfileCPU: true,
pyroscope.ProfileAllocObjects: true,
pyroscope.ProfileAllocSpace: true,
pyroscope.ProfileInuseObjects: true,
pyroscope.ProfileInuseSpace: true,
pyroscope.ProfileGoroutines: true,
pyroscope.ProfileMutexCount: true,
pyroscope.ProfileMutexDuration:true,
pyroscope.ProfileBlockCount: true,
pyroscope.ProfileBlockDuration:true,
},
})
}
```
```yaml
# [Python](https://docs.python.org/):pyroscope-python SDK
# pip install pyroscope-io
import pyroscope
pyroscope.configure(
application_name="my-python-service",
server_address="http://pyroscope-server:4040",
tags={"service": "payment", "env": "production"},
)
```
**我的判断**:Go/Python/Java 项目用 SDK 模式精度更高(能看到函数级热点),其他语言用 eBPF 模式。如果同时有这两种模式,**优先用 SDK**,eBPF 作为补充(覆盖无源码的场景)。
## 生产部署:Pyroscope Server 搭建
```yaml
# docker-compose.yml for Pyroscope
version: '3.8'
services:
pyroscope:
image: pyroscopeio/pyroscope:latest
restart: unless-stopped
ports:
- "4040:4040" # Agent 上报端口
- "6060:6060" # HTTP API
environment:
- PYROSCOPE_WRITE_USERNAME=admin
- PYROSCOPE_WRITE_PASSWORD=${PYROSCOPE_PASSWORD}
- PYROSCOPE_AUTH_ENABLED=true
- PYROSCOPE_DATA_RETENTION=72h # 数据保留 72 小时
volumes:
- pyroscope-data:/data
grafana:
image: grafana/grafana:11.1.0
restart: unless-stopped
ports:
- "3000:3000"
environment:
- GF_INSTALL_PLUGINS=grafana-pyroscope-datasource
volumes:
- grafana-data:/var/lib/grafana
depends_on: [pyroscope]
volumes:
pyroscope-data:
grafana-data:
```
**关键配置**:
- `DATA_RETENTION=72h`:生产环境建议保留 72 小时(3 天),足够做故障回溯。更长需要外接对象存储
- `AUTH_ENABLED=true`:必须开启,否则任何人能访问 profiling 数据(含敏感代码路径信息)
- `grafana-pyroscope-datasource` 插件:在 Grafana 里直接看火焰图
## 火焰图解读:三种核心视图
### CPU Profiling:看 CPU 耗时分布
```
# 在 Pyroscope UI 里看到的火焰图
# X 轴:时间(从左到右)
# Y 轴:调用栈深度(从底到顶)
# 方块大小:CPU 耗时占比
# 热点识别规则:
# 1. 最宽的列 = 最耗 CPU 的函数
# 2. 最靠近底部的方块 = 入口函数(main/goroutine)
# 3. 红色高亮 = GC 相关函数(Go 特有)
```
**实操案例**:我们在一次性能优化中发现,某个热点函数 `processPayment()` 占用了 40% 的 CPU,展开调用栈后发现是内部的 `calculateTax()` 函数做了大量字符串拼接(Go 的 string concatenation 在循环里会产生大量临时对象)。
```go
// ❌ 错误写法:循环内字符串拼接,产生大量临时对象
func calculateTax(amount float64) string {
result := ""
for i := 0; i < 1000; i++ {
result += fmt.Sprintf("item-%d: %.2f\n", i, amount*0.1)
}
return result
}
// ✅ 正确写法:用 strings.Builder
func calculateTax(amount float64) string {
var sb strings.Builder
for i := 0; i < 1000; i++ {
fmt.Fprintf(&sb, "item-%d: %.2f\n", i, amount*0.1)
}
return sb.String()
}
```
**优化结果**:`calculateTax()` 的 CPU 占用从 40% 降到 3%,P99 延迟从 500ms 降到 50ms。
### Memory Profiling:看内存分配热点
```yaml
# Pyroscope 的 memory profile 显示两种数据:
# 1. alloc_objects:分配的对象数量
# 2. alloc_space:分配的字节数
# 3. inuse_objects:当前存活的对象数量
# 4. inuse_space:当前存活的字节数
```
**解读规则**:
- `alloc_space` 高 → 垃圾回收压力大(GC 停顿长)
- `inuse_space` 高 → 内存泄漏嫌疑(对象没有被回收)
- `alloc_objects` 高但 `inuse_objects` 低 → 短期对象多,GC 频繁
**实际案例**:我们发现一个 Java 服务的 `inuse_space` 持续增长,定位到是一个连接池没有正确关闭——每个请求创建一个 HTTP 连接但没释放,导致内存缓慢增长。7 天后内存溢出,服务崩溃。
### Mutex/Block Profiling:看并发瓶颈
```yaml
# Go 特有的 mutex/block profile
# 1. mutex_count:锁竞争次数
# 2. mutex_duration:锁等待时间
# 3. block_count:goroutine 阻塞次数
# 4. block_duration:goroutine 阻塞时间
```
**解读规则**:
- `mutex_duration` 高 → 锁竞争严重,考虑用读写锁或无锁结构
- `block_duration` 高 → channel/send 阻塞,考虑异步化或加大 buffer
## 生产部署踩坑
### 坑一:eBPF agent 权限不足
```
# 报错信息
Error: unable to attach probe: operation not permitted
Error: bpf: Operation not permitted
```
原因:容器没有 `CAP_SYS_ADMIN` 权限,且 seccomp profile 限制了 eBPF 系统调用。eBPF agent 需要 `privileged: true` 或添加 `SYS_ADMIN`/`BPF`/`PERFMON` 能力,并解除 seccomp 限制。详细配置见 [ebpf-observability.md](ebpf-observability.md)。
**我的建议**:eBPF agent 直接跑在节点上(DaemonSet + hostPID),不要放容器里。权限问题少一半。
### 坑二:数据 retention 配置错误
```yaml
# 错误:retention 设太长,磁盘爆满
PYROSCOPE_DATA_RETENTION=30d # 30 天 profiling 数据占用 TB 级磁盘
# 正确:生产环境 72h 足够
PYROSCOPE_DATA_RETENTION=72h
```
**计算**:一个 Go 服务每秒采样一次,每次采样约 1KB,72 小时 = 72×3600×1 ≈ 260MB。如果 100 个服务,72 小时 ≈ 26GB—— manageable。但 30 天就是 1TB 级别了。
### 坑三:火焰图看不清——采样率太低
```yaml
# Pyroscope agent 默认采样率:10Hz(每秒 10 次)
# 对于高频函数可能看不清细节
# 提高采样率到 100Hz
PYROSCOPE_PROFILE_RATE=100
```
**注意**:采样率越高,数据量越大,存储压力越大。建议只在排查问题时临时提高采样率,平时保持 10Hz。
## 性能优化实战:从 500ms 到 50ms 的完整过程
**背景**:支付服务 P99 延迟从 100ms 涨到 500ms,持续了两天,定位困难。
### 第一步:打开 Pyroscope 火焰图
```
# 在 Pyroscope UI 选择:
# 1. Application: my-payment-service
# 2. Profile type: cpu
# 3. Time range: 最近 2 小时
# 4. 对比时间段:问题发生前 vs 问题发生时
```
### 第二步:定位热点函数
火焰图显示 `processPayment()` 占用 40% CPU,展开后看到 `calculateTax()` 是主要耗时点。
### 第三步:深入调用栈
进一步展开 `calculateTax()`,发现是字符串拼接循环——这和我们的代码 review 不一致,怀疑是某个新提交的代码引入了这个问题。
```bash
# 通过 [git](https://git-scm.com/doc) blame 定位具体提交
git blame --date=short src/payment/tax.go | grep "result +="
# 输出:a1b2c3d 2024-03-15 xxx result += fmt.Sprintf(...)
```
### 第四步:修复并提交
```go
// 修改 tax.go,用 strings.Builder 替代字符串拼接
// 提交 PR,通过代码 review
// 部署到生产
```
### 第五步:验证效果
```bash
# 部署后 10 分钟,重新看 Pyroscope 火焰图
# 确认 calculateTax() CPU 占用从 40% 降到 3%
# 确认 P99 延迟从 500ms 降到 50ms
```
**总耗时**:从发现问题到修复验证,全程 30 分钟。如果用传统方法(手动 pprof snapshot + 问题复现),可能需要几天。
## 采样器选型与成本权衡:别为「精度」多花三成开销
Pyroscope 一上就是几十上百个服务全量采,开销和存储都会跟着涨。选型上我按「能不能拿到源码 + 语言 + 要看到多深」三问来定,能省则省。
**第一问:有没有源码?** 有源码的语言(Go/Java/Python/Node)优先上 SDK 模式,能看到函数级调用栈,定位到具体哪行;没源码的(C 闭源服务、系统组件、第三方二进制)只能用 eBPF,看到系统调用层就够了。同一个服务两层都上是最贵的,除非那服务确实是性能热点且你想两层对照,否则别。
**第二问:要看多深?** 只想知道「CPU 烧在哪类操作上」(I/O 还是计算、锁竞争还是纯算)→ eBPF 够了,零侵入。要定位到「哪个函数、哪次调用」→ 必须 SDK,eBPF 在用户态函数边界上是瞎的。多数日常巡检其实第一档就够了,把 SDK 留给真正要深挖的服务。
**第三问:采样密度值不值?** 采样率不是越高越好,开销和存储都线性涨,而超过一定密度后火焰图的「分辨率收益」已经饱和。我平时全量 10Hz,只有某个服务进了排查流程才临时拉到 100Hz,查完降回去。全量 100Hz 是性能杀手加存储黑洞,别用「精度」当借口常开。
**成本要算进容量**:每加一个被剖析的服务,agent 自身要吃 CPU 和内存,Pyroscope server 的磁盘要随服务数 × 保留时长线性涨。上线前按「服务数 × 采样率 × 保留时长」算一遍磁盘预算,别等 retention 一长、磁盘爆了才发现当初没算账。这也是我坚持 `DATA_RETENTION=72h` 的原因——够回溯,不至于把磁盘吃穿。
**基于典型生产场景**:一个 200 服务的环境,一开始图省事全量 SDK + 100Hz,一周后 Pyroscope server 磁盘从 100G 涨到 900G,agent 自身 CPU 也压得部分业务 P99 抬升了 8ms。降到「热点服务 SDK + 其余 eBPF + 全量 10Hz」后,磁盘稳在 200G 内,业务开销回到不可感知。教训:持续剖析的成本模型是「广度 × 密度 × 时长」,三者里砍任意一个都能省,先砍密度、再砍广度,最后才动保留时长。
## FAQ
### Q: Pyroscope 和 pprof 可以同时用吗?
可以,而且推荐同时用。Pyroscope 负责持续监控(实时火焰图、历史对比),pprof 负责深度分析(精确到某个时间点的完整调用栈)。典型工作流:Pyroscope 发现异常 → pprof 精确定位 → 修复 → Pyroscope 验证。
### Q: 性能剖析数据会不会泄露业务敏感信息?
会。火焰图会暴露函数名、代码路径、甚至部分业务逻辑。建议:
1. 开启 Pyroscope 的认证(`AUTH_ENABLED=true`)
2. 限制访问权限(只让 SRE 和安全团队能看到生产环境数据)
3. 不要在火焰图里展示包含敏感信息的变量值(pyroscope 默认不展示,但某些自定义 profiling 可能泄露)
### Q: 没有源码只能看 eBPF 火焰图吗?
是的。eBPF 火焰图能看到的是系统调用层面的热点(如 `read`、`write`、`mmap`),看不到应用层函数。但这也足够了——大部分性能问题(I/O 瓶颈、锁竞争、内存分配)都能在系统调用层面看到迹象。真正的函数级热点需要 SDK 配合。
---
## 相关文章
- [eBPF 可观测性原理:无侵入监控实战,从 kernel trace 到生产落地](ebpf-observability.md)
- [OpenTelemetry 遥测标准:Trace/Metric/Log 统一采集,从 SDK 接入到后端对接全指南](opentelemetry-guide.md)
- [Alertmanager 告警降噪实战:抑制器 + 路由树 + 静默配置四步降噪法](alertmanager-noise-reduction.md)
---
## 数据库监控实战:PostgreSQL/MySQL 生产监控四类故障决策树与 5 个真实事故复盘
URL: https://ops.jiunotes.top/monitor/database-monitoring-postgres-mysql.md
摘要: 用 postgres_exporter + mysqld_exporter 监控数据库层的实战手册。四类故障决策树(连接池耗尽、锁与死锁、复制延迟、慢查询)给出症状-决策-命令-阈值全链路;5 个真实事故复盘讲透假死、锁等待、复制假警;纠正 pg_replication_lag_seconds、pg_stat_statements 需重启、Threads_connected 与 Threads_running 混淆等常见误区。
### Answer
数据库瓶颈往往在锁/IO 等待,不体现在 CPU 上。用连接池比例、锁等待、复制延迟、
慢查询四类指标建决策树,配合 pg_monitor/只读账号最小权限,才能抓住"假死"。
### FAQ
Q: PostgreSQL 有没有 pg_replication_lag_seconds 这个指标?
A: 没有。网上大量教程写 `pg_replication_lag_seconds`,实际会查不到。正确指标在 `pg_stat_replication` 视图里:`replay_lag`(秒)是主库提交到备库重放完毕的延迟,另有 `flush_lag` 和 `write_lag`。postgres_exporter 对应导出为 `pg_stat_replication_replay_lag_seconds`。
Q: 为什么我 CREATE EXTENSION pg_stat_statements 了却查不到数据?
A: 只建扩展不重启没用。`pg_stat_statements` 必须写进 postgresql.conf 的 `shared_preload_libraries = 'pg_stat_statements'`,然后重启数据库进程才加载。CREATE EXTENSION 只是建表和函数。重启后还要确认 `track_io_timing` 和 `pg_stat_statements.track` 的配置。
Q: MySQL 的 Threads_connected 和 Threads_running 有什么区别?
A: `Threads_connected` 是当前已建立的连接总数(含空闲),`Threads_running` 是真正在执行语句的连接数。连接池告警看 connected / max_connections 比例(>80% 预警 >90% 严重);性能瓶颈看 running——它高才说明真在忙,connected 高但 running 低多半是连接池泄漏或应用没释放。
Q: MySQL 有没有现成的死锁次数计数器?
A: 没有 `deadlocks_total` 这类现成指标。用 `mysql_global_status_innodb_row_lock_waits`(InnoDB 行锁等待累计次数)判断锁压力,或用 performance_schema 的 `events_waits_summary_global_by_event_name` 查 `wait/engine/innodb/row_lock` 等待。死锁本身看错误日志或 `SHOW ENGINE INNODB STATUS`。
Q: 复制延迟老是瞬时报警,怎么处理?
A: 加 `for: 5m` 防抖。主从时钟不同步、长时间运行的大事务、网络抖动都会造成瞬时延迟尖峰,`for` 时间窗能滤掉。另外用 `abs()` 比较主从 `timestamp` 差值时要小心时钟偏移,建议用 `replay_lag`/`seconds_behind_master` 这类数据库自身计算的延迟,别自己算主从时间差。
### Full Content
# 数据库监控实战:PostgreSQL / MySQL 生产监控四类故障决策树与 5 个真实事故复盘
凌晨 1 点 47 分,我被监控电话叫醒。业务值班说接口大面积超时,P99 延迟从 80ms 飙到 4 秒。我爬起来看 Grafana:**主机 CPU 才 15%,内存 40%,磁盘 IO 也正常,OS 监控全绿**。按"主机没挂"的经验判断,我差点让值班重启网关再观察。幸好多看了一眼数据库面板——`pg_stat_activity` 里 300 多个连接全是 `idle in transaction`,`max_connections` 已经打满 96%。**数据库"假死"了**:进程活着,但所有新请求都卡在连接池门口进不去。那次事故之后我明白了一件事:**监控数据库 ≠ 监控主机**。这篇文把我线上攒的经验写全——怎么用 [postgres_exporter](https://github.com/prometheus-community/postgres_exporter) + [mysqld_exporter](https://github.com/prometheus-community/mysqld_exporter) 把数据库层盯住,四类故障怎么判断,以及我踩过的 5 个真实坑。想先补 Prometheus 部署和查询基础的,看我之前写的 [Prometheus 部署](prometheus-deploy.md) 和 [PromQL 查询](prometheus-query.md)。
## 为什么监控数据库 ≠ 监控主机
数据库是**有状态**的。主机监控看的是"资源用了多少",数据库监控要看"请求排队了多久"。资源低不代表健康——**连接池耗尽、锁等待、IO 等待这些瓶颈恰恰不体现在 CPU 上**,主机面板全绿,数据库可能已经瘫了。
我遇到的"假死"比"硬宕机"危险得多。硬宕机进程挂了,连接直接报错,应用能感知、能重试;假死是进程活着、端口开着、连接能建上,但每个请求都堵着等锁或等连接,表现为**大面积超时**——应用以为网络问题,网关以为下游慢,没人怀疑数据库。等到真查出是连接池,业务已经抖了半小时。
所以数据库监控要盯四个层面,缺一不可:
| 层面 | 主机监控能发现吗 | 为什么要单独盯 |
|------|----------------|----------------|
| 连接 | 不能 | 连接池耗尽是"假死"主因,CPU/内存正常 |
| 锁 | 不能 | 锁等待是慢查询的隐形推手,CPU 不高 |
| 复制 | 不能 | 备库延迟会导致主备切换丢数据,OS 全绿 |
| 慢查询 | 不能 | 慢查询堆积会拖垮连接和锁,指标滞后 |
## 链路架构:数据库 → exporter → Prometheus
生产环境我推荐一套干净的链路:exporter 用 systemd 托管跑在数据库本机,Prometheus 从 `127.0.0.1` 抓取(exporter 只绑本机回环,不暴露外网),告警走 Alertmanager,看板用 Grafana。数据库监控的**最小权限**和**端口隔离**这两件事,很多教程压根不提,我吃过亏。
### exporter 本机 systemd 部署(以 PostgreSQL 为例)
先建监控账号——**绝不复用应用账号,更不要用 root/superuser**。PostgreSQL 8.x 起内置了 `pg_monitor` 角色,一行授权搞定:
```sql
-- 用超级用户执行一次
CREATE ROLE exporter LOGIN PASSWORD 'Str0ng-P@ss-For-Monitor';
GRANT pg_monitor TO exporter;
-- pg_monitor 自动包含 pg_read_all_stats、pg_read_all_settings、pg_stat_scan_tables
-- 覆盖了 pg_stat_activity、pg_stat_replication、pg_stat_statements、pg_stat_database 的读取
```
`pg_monitor` 是 PostgreSQL 10+ 的内置角色,比我早期手动 `GRANT SELECT ON pg_stat_* TO exporter` 干净得多——不用逐视图授权,升级也不漏。如果是老版本,手动授 `pg_stat_activity`、`pg_stat_replication`、`pg_stat_database` 的 SELECT 即可。
MySQL 建只读监控用户:
```sql
CREATE USER 'exporter'@'127.0.0.1' IDENTIFIED BY 'Str0ng-P@ss-For-Monitor';
-- 最小权限:PROCESS 看连接线程,REPLICATION CLIENT 看复制,SELECT 读库
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'127.0.0.1';
FLUSH PRIVILEGES;
```
**坑:别给 MySQL 监控用户 `ALL PRIVILEGES`**。PROCESS + REPLICATION CLIENT + SELECT 已经够 mysqld_exporter 抓所有核心指标,`ALL` 等于把只读监控账号变成了半个管理员,被拖库时连 binlog 都能读。
systemd unit(`/etc/systemd/system/postgres-exporter.service`):
```ini
[Unit]
Description=Prometheus PostgreSQL Exporter
After=network.target postgresql.service
[Service]
User=prometheus
Group=prometheus
# 坑:环境变量别写进命令行,ps 会泄露密码
Environment=DATA_SOURCE_NAME="postgresql://exporter:Str0ng-P@ss-For-Monitor@127.0.0.1:5432/postgres?sslmode=disable"
# 只绑本机回环,绝不开 0.0.0.0
ExecStart=/usr/local/bin/postgres_exporter --web.listen-address=127.0.0.1:9187 --web.telemetry-path=/metrics
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
```
MySQL 同理(`mysqld_exporter --web.listen-address=127.0.0.1:9104`)。**坑:exporter 端口绑 0.0.0.0 等于裸奔**——我曾见到某司 exporter 开了公网,任何能访问 9104 端口的人都能看到连接数、复制延迟甚至慢查询 SQL,这是数据泄露级隐患。绑 `127.0.0.1` 或加防火墙限制源 IP。
docker-compose 方式(适合容器化环境,注意网络要 `host` 才能让 exporter 访问本机数据库):
```yaml
services:
postgres-exporter:
image: prometheuscommunity/postgres-exporter:latest
network_mode: host # 坑:必须 host,bridge 模式下连不上宿主机数据库
environment:
DATA_SOURCE_NAME: "postgresql://exporter:Str0ng-P@ss-For-Monitor@127.0.0.1:5432/postgres?sslmode=disable"
command: ["--web.listen-address=127.0.0.1:9187"]
restart: always
```
Prometheus 抓取配置(`prometheus.yml`):
```yaml
scrape_configs:
- job_name: postgres
static_configs:
- targets: ['127.0.0.1:9187'] # 或实际 IP,如 10.0.1.5:9187
relabel_configs:
- source_labels: [__address__]
target_label: instance
replacement: pg-prod-01 # 给实例起个可读名,不然全是 IP 不好看
- job_name: mysql
static_configs:
- targets: ['10.0.1.6:9104']
relabel_configs:
- source_labels: [__address__]
target_label: instance
replacement: mysql-prod-01
```
## PostgreSQL 黄金指标速查
以下是我在 Grafana 面板里常驻的 PG 指标,全部来自 postgres_exporter 默认导出(无需额外参数):
| 监控目标 | 指标名 | 阈值(预警/严重) |
|---------|--------|-----------------|
| 活跃连接占比 | `pg_stat_database_numbackends` / 查询 `max_connections` | >80% / >90% |
| 连接等待 | `pg_stat_database_tup_returned` 增长率 | 结合慢查询看 |
| 事务吞吐 | `pg_stat_database_xact_commit` / `xact_rollback` 速率 | 环比突增看 |
| 缓存命中率 | `pg_stat_database_blks_hit` / (`blks_hit`+`blks_read`) | <98% 预警 |
| 复制延迟 | `pg_stat_replication_replay_lag_seconds` | >10s / >60s |
| 慢查询 | `pg_stat_statements_mean_exec_time_ms`(需启用扩展) | >500ms 预警 |
| 死元组膨胀 | `pg_stat_user_tables_n_dead_tup` / `n_live_tup` | >20% 触发 vacuum |
| 数据库年龄 | `pg_database_datfrozenxid_age` | >2 亿 / >4 亿(防事务 ID 回卷) |
对应 PromQL(PG):
```promql
# 连接池占用率(numbackends / max_connections)
pg_stat_database_numbackends{datname="mydb"} / on() pg_settings_max_connections * 100
# 缓存命中率(低于 98% 说明有全表扫描压力)
sum(rate(pg_stat_database_blks_hit[5m])) / (sum(rate(pg_stat_database_blks_hit[5m])) + sum(rate(pg_stat_database_blks_read[5m]))) * 100
# 复制延迟(秒)——坑:没有 pg_replication_lag_seconds!
pg_stat_replication_replay_lag_seconds
# 死元组比例(vacuum 压力)
pg_stat_user_tables_n_dead_tup / (pg_stat_user_tables_n_live_tup + pg_stat_user_tables_n_dead_tup) * 100
```
**踩坑①**:网上大量教程写的 `pg_replication_lag_seconds` **根本不存在**。正确的延迟在 `pg_stat_replication` 视图里,字段是 `replay_lag`(备库重放延迟)、`flush_lag`、`write_lag`,postgres_exporter 导出为 `pg_stat_replication_replay_lag_seconds`。我第一次照着某博客配规则,Prometheus 一直 `no data`,排查半天才发现指标名错了。
**踩坑②**:`pg_stat_statements` 不能只 `CREATE EXTENSION`。必须先改 `postgresql.conf`:
```ini
# postgresql.conf
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all
# 改完必须重启数据库进程,仅 CREATE EXTENSION 不会加载共享库
```
```sql
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
```
重启后 postgres_exporter 才导出 `pg_stat_statements` 开头的指标。我见过太多人只建扩展不重启,然后怀疑 exporter 坏了。
## MySQL 黄金指标速查
| 监控目标 | 指标名 | 阈值(预警/严重) |
|---------|--------|-----------------|
| 连接占用 | `mysql_global_status_threads_connected` / `max_connections` | >80% / >90% |
| 真正执行 | `mysql_global_status_threads_running` | > CPU 核数×2 预警 |
| 慢查询率 | `rate(mysql_global_status_slow_queries[5m])` | 持续 >0 且增长 |
| 行锁等待 | `mysql_global_status_innodb_row_lock_waits`(累计) | 增量 >100/s 预警 |
| 死锁 | 无现成计数器,用 row_lock_waits 推断 | 见下文 |
| 复制延迟 | `mysql_slave_status_seconds_behind_master` | >10s / >60s |
| 缓冲区命中 | `mysql_global_status_innodb_buffer_pool_read_requests` / `reads` | <98% 预警 |
| 临时表 | `mysql_global_status_created_tmp_tables` 速率 | 突增看磁盘临时表 |
对应 PromQL(MySQL):
```promql
# 连接占用率
mysql_global_status_threads_connected / mysql_global_variables_max_connections * 100
# 真正执行线程(性能瓶颈看这个,不是 connected)
mysql_global_status_threads_running
# 行锁等待速率(累计计数器,算 rate)
rate(mysql_global_status_innodb_row_lock_waits[5m])
# 复制延迟
mysql_slave_status_seconds_behind_master
```
**踩坑③**:`Threads_connected` 和 `Threads_running` 别混。前者是已建连接总数(含空闲),后者是正在执行语句的连接数。**连接池告警看 connected/max_connections**,**性能瓶颈看 running**。有一次我误用 connected 做性能告警,晚上业务高峰 connected 涨到 2000 触发告警,实际 running 才 30——是连接没释放(连接池泄漏),不是数据库忙。反过来,若 running 长期接近 CPU 核数,才是真的算力吃紧。
**踩坑④**:MySQL **没有** `deadlocks_total` 这类现成的死锁计数器。判断锁压力用 `mysql_global_status_innodb_row_lock_waits`(行锁等待累计次数,算 rate 看增量),或用 performance_schema 的 `events_waits_summary_global_by_event_name` 查 `wait/engine/innodb/row_lock`。真要定位死锁,直接 `SHOW ENGINE INNODB STATUS` 看 `LATEST DETECTED DEADLOCK` 段,别在指标上找不存在的计数器。
## 四类故障决策树
这是本文的核心。每类故障我按「症状 → 决策 → 命令 → 阈值」排成决策树,值班时照着走能省一半排查时间。
### 决策树①:连接池耗尽(假死主因)
```
症状:接口大面积超时,OS CPU/内存正常
└─> 看 connected/max_connections 比例
├─ <80% → 不是连接池,查下一步
├─ 80-90% → 预警,检查是否有连接泄漏(idle 连接堆积)
└─ >90% → 严重!立即排查
├─ 决策:找出"谁占着连接不释放"
├─ 命令(PG):SELECT state, count(*) FROM pg_stat_activity GROUP BY state ORDER BY 2 DESC;
│ # 若 idle in transaction 大量堆积 → 应用事务没提交/没回滚,找业务侧
├─ 命令(MySQL):SHOW PROCESSLIST; # 看大量 Sleep 状态的连接 → 连接池没释放
├─ 阈值:idle in transaction > max_connections*0.3 视为异常
└─ 临时缓解:PG 可 pg_terminate_backend 杀掉空闲事务(谨慎,先确认业务方)
```
连接池耗尽的典型特征是 `idle in transaction`(PG)或大量 `Sleep`(MySQL)堆积——连接建了但一直空闲占着。**这不是数据库在忙,是应用侧连接管理有 bug**,比如事务里做了网络调用没及时提交。修复方向是应用代码,不是加 max_connections(加了只是把问题推迟,池子迟早再满)。
### 决策树②:锁与死锁
```
症状:某几张表查询突然极慢,CPU 不高但请求堆积
└─> 看锁等待指标
├─ PG:SELECT blocked, count(*) FROM pg_locks WHERE NOT granted GROUP BY blocked;
│ # blocked 列显示谁在等锁;也可查 pg_stat_activity 里 wait_event_type='Lock'
├─ MySQL:SHOW ENGINE INNODB STATUS; # 看 TRANSACTIONS 段的锁等待链
└─ 决策:找到"持锁方",通常是长事务
├─ 命令(PG):SELECT pid, state, now()-xact_start AS dur, query FROM pg_stat_activity WHERE state != 'idle' ORDER BY dur DESC LIMIT 10;
│ # xact_start 很早但还在跑 → 长事务持锁不放
├─ 阈值:事务持续时间 > 60s 预警,> 5min 严重
└─ 缓解:PG 用 pg_cancel_backend(pid) 取消,严重用 pg_terminate_backend(pid)
```
死锁和锁等待要分清:**死锁是互等**(A 等 B、B 等 A,数据库会自动回滚一方),**锁等待是单方阻塞**(A 持锁,B 一直等)。锁等待更危险——它不会自动解除,会越堆越多,直到连接池耗尽,引发连锁"假死"。MySQL 侧死锁会频繁出现在错误日志,PG 侧 `pg_locks` 里 `granted=false` 的锁就是等待链。
### 决策树③:复制延迟
```
症状:备库延迟告警,主库看起来正常
└─> 看 replay_lag(PG)/ seconds_behind_master(MySQL)
├─ <10s → 正常,不用管
├─ 10-60s → 观察,检查是否大事务/大 DDL 在跑
└─ >60s → 严重,有主备切换丢数据风险
├─ 决策:先判断是"真慢"还是"假警"
├─ 假警排查:
│ ├─ 主从时钟不同步 → 用数据库自身延迟,别自己算主从时间差
│ ├─ 长事务/大 DDL → 主库执行了 ALTER 大表,WAL/relay log 堆积
│ └─ 网络抖动 → 看 exporter 抓取是否中断过
├─ 真慢排查:SELECT * FROM pg_stat_replication; # 看 state、write/flush/replay_lag
└─ 缓解:若备库持续跟不上,考虑临时切只读分流,别硬扛
```
**踩坑⑤**:复制延迟**假警**是高频事故。主从时钟不同步(NTP 没配好)、主库跑长事务、网络抖动都会造成瞬时尖峰。我在告警规则里必须加 `for: 5m`,否则每晚业务高峰都会收到一堆"复制延迟"的假告警。另外**别自己用 `abs(主时间戳 - 备时间戳)` 算延迟**——一旦时钟漂移,这个值永远不准,直接用 `replay_lag` / `seconds_behind_master` 这类数据库自身计算的延迟。
### 决策树④:慢查询
```
症状:接口变慢但连接数正常,锁等待也不多
└─> 看慢查询指标
├─ PG:pg_stat_statements 的 mean_exec_time 排序
│ SELECT query, mean_exec_time, calls FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10;
├─ MySQL:slow_queries 速率 + performance_schema
│ SELECT * FROM sys.schema_unused_indexes; # 找出没人用的索引
└─ 决策:定位到具体 SQL
├─ 命令(PG):EXPLAIN (ANALYZE, BUFFERS) <慢SQL>; # 看 Seq Scan 和 buffer 读取
├─ 命令(MySQL):EXPLAIN ANALYZE <慢SQL>; # 8.0 支持
├─ 阈值:单条 >500ms 预警,>2s 严重;全表扫描且 rows 大 → 加索引
└─ 缓解:加索引前先用 EXPLAIN 确认,别盲目加(写入会变慢)
```
慢查询是"温水煮青蛙"——它不直接报警,但会慢慢吃掉连接和锁,最终演变成前两类故障。所以慢查询监控是**预防性**的:pg_stat_statements 里 `calls` 大且 `mean_exec_time` 高的 SQL,就是定时炸弹。
## 5 个真实事故复盘
以下是我在运维一线处理过的真实故障,细节经过脱敏。每个都对应上面一类决策树的落地。
### 事故一:连接池耗尽导致"假死"(对应决策树①)
**现象**:凌晨接口大面积超时,OS CPU 15% 全绿。**根因**:某定时任务改了事务边界,在事务里调了外部 HTTP 接口,HTTP 超时 30s 期间连接一直 `idle in transaction` 占着池子。300 个连接 200 个卡在事务里。**指标怎么显示**:`pg_stat_database_numbackends` 涨到 `max_connections` 的 96%,`idle in transaction` 占 200+,CPU 完全正常——这就是"假死"。**修复**:`pg_terminate_backend` 杀掉空闲事务,业务侧把 HTTP 调用移出事务。**防再发**:连接池告警阈值 >80% 预警、>90% 严重,且单独对 `idle in transaction` 计数加告警。
### 事故二:长事务持锁拖垮整张表(对应决策树②)
**现象**:某订单表查询从 10ms 涨到 3s,CPU 正常。**根因**:一个后台脚本 `BEGIN` 后做批量更新,中途抛异常没回滚,事务挂着持锁 40 分钟,所有对该表的写全部排队。**指标怎么显示**:`pg_locks` 里 `granted=false` 的锁堆积,`pg_stat_activity` 里一个 `xact_start` 40 分钟前的连接 state=active。**修复**:找到该 pid,`pg_cancel_backend` 取消。**防再发**:给长事务加告警(`xact_start` 超过 5 分钟即报警),并让开发把脚本改成 `try/finally` 保证回滚。
### 事故三:主从时钟不同步的复制假警(对应决策树③)
**现象**:复制延迟告警每小时响一次,检查备库实际数据并不落后。**根因**:主从两台机器 NTP 没配好,时钟漂了 3 秒,而我当时用 `abs(主时间戳 - 备时间戳)` 算延迟。**指标怎么显示**:`seconds_behind_master` 其实为 0,但我自算的"延迟"恒为 3s 左右,刚好卡在告警线上。**修复**:两台机配 NTP 同步,改成用数据库自身延迟指标。**防再发**:告警加 `for: 5m`,所有复制延迟一律用 `replay_lag`/`seconds_behind_master`,不用自算时间差。
### 事故四:全表扫描拖垮缓存命中率(对应决策树④)
**现象**:某报表接口越来越慢,缓存命中率掉到 92%。**根因**:一个统计 SQL 没带索引条件,每跑一次全表扫 200 万行,把 buffer pool 冲得全是无效页。**指标怎么显示**:`pg_stat_database_blks_hit` / (`blks_hit`+`blks_read`) 从 99% 掉到 92%,`pg_stat_statements` 里该 SQL `mean_exec_time` 涨到 1.8s。**修复**:加复合索引,命中率回到 99%。**防再发**:缓存命中率 <98% 告警,慢查询 TOP 榜每周 review 一次。
### 事故五:MySQL 行锁等待堆积成雪崩(对应决策树②)
**现象**:订单服务批量超时,从一条慢 SQL 开始,10 分钟内连坐全库。**根因**:一个批量更新没有按主键顺序,两条事务互相等待对方已加锁的行,加上 `innodb_lock_wait_timeout` 默认 50s,等待链越积越长。**指标怎么显示**:`mysql_global_status_innodb_row_lock_waits` 的 rate 从个位数飙升到 200+/s,`Threads_running` 高企但 `Threads_connected` 正常。**修复**:杀掉持锁会话,把批量更新改成按主键排序分批执行。**防再发**:行锁等待 rate >100/s 告警,锁等待链超过 3 层视为异常。
## 生产级告警规则
以下是我实际在用的告警规则,`for` 时窗和注释都是踩坑后的产物。
```yaml
# database-alerts.yml
groups:
- name: postgresql
rules:
# 连接池占用率(PG)
- alert: PostgreSQLConnPoolHigh
expr: pg_stat_database_numbackends{datname!~"template.*"} / on() pg_settings_max_connections * 100 > 80
for: 2m
labels:
severity: warning
annotations:
summary: "PG 连接池占用 {{ $value | printf \"%.1f\" }}%"
description: "instance={{ $labels.instance }} datname={{ $labels.datname }} 连接池超过 80%,检查 idle in transaction 是否堆积"
- alert: PostgreSQLConnPoolCritical
expr: pg_stat_database_numbackends{datname!~"template.*"} / on() pg_settings_max_connections * 100 > 90
for: 1m
labels:
severity: critical
annotations:
summary: "PG 连接池耗尽 {{ $value | printf \"%.1f\" }}%"
description: "可能假死!立即查 pg_stat_activity 的 state,杀 idle in transaction"
# 复制延迟——坑:必须加 for 防假警(时钟/大事务/网络抖动)
- alert: PostgreSQLReplicationLag
expr: pg_stat_replication_replay_lag_seconds > 60
for: 5m
labels:
severity: critical
annotations:
summary: "PG 复制延迟 {{ $value | printf \"%.1f\" }}s"
description: "备库重放落后 {{ $value }}s,检查主库是否跑大事务/大 DDL,注意主从时钟同步"
# 缓存命中率低(全表扫描压力)
- alert: PostgreSQLCacheHitLow
expr: sum(rate(pg_stat_database_blks_hit[5m])) / (sum(rate(pg_stat_database_blks_hit[5m])) + sum(rate(pg_stat_database_blks_read[5m]))) * 100 < 98
for: 10m
labels:
severity: warning
annotations:
summary: "PG 缓存命中率 {{ $value | printf \"%.1f\" }}%"
description: "低于 98% 可能有全表扫描,查 pg_stat_statements 慢查询 TOP"
- name: mysql
rules:
- alert: MySQLConnPoolHigh
expr: mysql_global_status_threads_connected / mysql_global_variables_max_connections * 100 > 80
for: 2m
labels:
severity: warning
annotations:
summary: "MySQL 连接占用 {{ $value | printf \"%.1f\" }}%"
description: "instance={{ $labels.instance }} 连接超 80%,注意 Sleep 连接堆积(连接池泄漏)"
- alert: MySQLRowLockWaits
expr: rate(mysql_global_status_innodb_row_lock_waits[5m]) > 100
for: 2m
labels:
severity: warning
annotations:
summary: "MySQL 行锁等待速率 {{ $value | printf \"%.1f\" }}/s"
description: "锁压力高,查 SHOW ENGINE INNODB STATUS 的锁等待链,可能演变成雪崩"
- alert: MySQLReplicationLag
expr: mysql_slave_status_seconds_behind_master > 60
for: 5m
labels:
severity: critical
annotations:
summary: "MySQL 复制延迟 {{ $value }}s"
description: "备库落后 {{ $value }}s,检查大事务/大 DDL/网络,用数据库自身延迟防时钟假警"
```
**坑:`for` 不是越大越好**。我最早把复制延迟的 `for` 配成 30m,结果一次真故障延迟持续 25 分钟,告警没发出来——等发出来主库已经被切换了。折中下来,复制延迟这类**瞬时尖峰多**的用 `for: 5m`,连接池这类**真故障**的用 `for: 1-2m`(宁可早报不可漏报)。告警通知配置(webhook、Silence、抑制)看我写的 [Alertmanager 告警规则](prometheus-alerting.md),看板设计看 [Grafana 面板](grafana-dashboard.md)。
## FAQ
**Q1:PostgreSQL 有没有 `pg_replication_lag_seconds` 这个指标?**
没有。这个指标名在网上流传很广,实际查不到。正确延迟在 `pg_stat_replication` 视图:`replay_lag`(秒)是主库提交到备库重放完毕的延迟,另有 `flush_lag`(备库收到并落盘)和 `write_lag`(备库收到)。postgres_exporter 导出为 `pg_stat_replication_replay_lag_seconds`。用 `\x SELECT * FROM pg_stat_replication;` 可看全部字段。
**Q2:为什么我 `CREATE EXTENSION pg_stat_statements` 了却查不到数据?**
只建扩展不重启没用。`pg_stat_statements` 必须在 `postgresql.conf` 里配 `shared_preload_libraries = 'pg_stat_statements'`,重启数据库进程后才加载共享库,`CREATE EXTENSION` 只是建视图和函数。重启后确认 `SELECT count(*) FROM pg_stat_statements;` 有数据,且 postgres_exporter 会导出 `pg_stat_statements_*` 指标。
**Q3:MySQL 的 `Threads_connected` 和 `Threads_running` 有什么区别?**
`Threads_connected` 是已建立连接总数(含空闲),`Threads_running` 是真正在执行语句的连接数。连接池告警看 `connected/max_connections`(>80% 预警 >90% 严重);性能瓶颈看 `running`——它接近 CPU 核数才算忙。`connected` 高但 `running` 低,通常是连接池泄漏或应用没释放连接,要查业务侧。
**Q4:MySQL 有没有现成的死锁次数计数器?**
没有 `deadlocks_total` 这类指标。用 `mysql_global_status_innodb_row_lock_waits`(行锁等待累计,算 `rate` 看增量)判断锁压力,或用 performance_schema 的 `events_waits_summary_global_by_event_name` 查 `wait/engine/innodb/row_lock`。死锁定位用 `SHOW ENGINE INNODB STATUS` 的 `LATEST DETECTED DEADLOCK` 段。
**Q5:复制延迟老是瞬时报警怎么办?**
告警加 `for: 5m` 防抖。主从时钟不同步、长事务、网络抖动都会造成瞬时尖峰,`for` 能滤掉。另外别用 `abs(主时间戳-备时间戳)` 自算延迟——时钟漂移会让它永远不准,用数据库自身的 `replay_lag`/`seconds_behind_master`。
## 相关文章
- [Prometheus 部署](prometheus-deploy.md) —— exporter 抓取链路的基础,scrape_config 怎么配
- [PromQL 查询](prometheus-query.md) —— 本文所有 PromQL 的语法基础,rate/sum/on 的用法
- [Grafana 面板](grafana-dashboard.md) —— 把黄金指标做成可视化看板
- [Alertmanager 告警规则](prometheus-alerting.md) —— 告警通知、Silence、Inhibit 的完整配置
- [Linux 磁盘 IO 监控](linux-disk-io-monitor.md) —— 数据库磁盘瓶颈常和 IO 等待有关,配合看
- [Linux 内存监控](linux-memory-monitor.md) —— buffer pool / shared_buffers 的内存调优基础
- [告警风暴半夜轰炸决策树:Alertmanager 重复、分组失效、静默降噪怎么治](monitor-alert-storm.md)
- [Grafana 大盘空白或数据错位决策树:图拉出来是空的怎么查](monitor-grafana-blank.md)
---
## DevSecOps 安全左移:CI/CD 集成扫描策略,从 SAST/DAST 到供应链安全完整指南
URL: https://ops.jiunotes.top/monitor/devsecops-security.md
摘要: DevSecOps 落地实战:SAST/SCA/DAST 扫描集成、镜像安全扫描、密钥泄露检测、安全策略绕过处理、以及"安全阻塞流水线"和"安全告警通知"的模式选择。
### Answer
DevSecOps 的核心是"安全左移"——把安全检查嵌入 CI/CD 流水线,而不是在上线前才做安全审计。
三层扫描:SAST(静态代码分析)在编码阶段、SCA(软件成分分析)在依赖阶段、DAST(动态应用测试)在部署后。
关键决策:扫描失败时是阻塞流水线还是仅告警?建议 SCA 高危漏洞阻塞、SAST 警告级不阻塞、DAST 全阻塞。
### FAQ
Q: SAST 和 DAST 有什么区别?分别什么时候用?
A: SAST 在代码层面分析(编译前),发现代码逻辑漏洞(如 SQL 注入、硬编码密钥);DAST 在运行层面测试(部署后),发现运行时漏洞(如 XSS、CSRF)。SAST 误报率高但覆盖早,DAST 准确但只能测已部署的服务。正确做法:SAST + SCA 合并到 PR 阶段,DAST 合并到 staging 阶段。
Q: 扫描工具选 Trivy 还是 Snyk 还是其他?
A: 看预算和需求。Trivy(Aquasecurity)免费、支持镜像/代码/配置扫描,适合中小团队;Snyk 功能最全但付费,适合有大预算的企业;Grype 轻量级镜像扫描,适合只需要镜像扫描的场景。我们的选择:Trivy 做镜像扫描 + Semgrep 做代码扫描,全部免费。
Q: 安全扫描阻塞了正常开发流程怎么办?
A: 这是 DevSecOps 最常见的矛盾。解决方案:① 区分"阻塞性漏洞"和"警告性漏洞",只阻塞高危;② 给开发者提供一键修复工具(如自动依赖升级);③ 定期做"安全债"清理,不让漏洞积累;④ 安全团队和开发团队共同定义漏洞等级,而不是安全单方面决策。
Q: 扫描工具上线后怎么保证它自己不会漏报或误报漂移?
A: 三件事:① 给扫描器配已知样例(含故意植入的漏洞 + 已知误报),每次升级工具后回归跑一遍,确认检出率和误报率没退化;② 把"检出率/误报率"打点成 metric 看趋势;③ 漏洞库规则更新要监控,规则库停更说明工具侧出问题。扫描器本身也是要被验证的对象,不是配完就永远对。
### Full Content
# DevSecOps 安全左移:CI/CD 集成扫描策略,从 SAST/DAST 到供应链安全完整指南
去年我们有两次安全事件:一次是开发者在代码里硬编码了 AWS key(推到了 GitHub 公开仓库),一次是依赖包里发现了 log4j 漏洞(生产环境还在用旧版本)。这两件事让我意识到:**安全检查不能只在上线前做,必须嵌入到开发的每一个环节**。
于是我们重构了 CI/CD 流水线,加了 SAST、SCA、DAST 三层扫描,配合镜像扫描和密钥检测。三个月后,安全事件的 MTTR 从 4 小时降到 30 分钟,高危漏洞率下降了 80%。
这篇分享完整的集成策略和踩坑经验,所有工具组合均来自生产环境的真实部署。
## 安全扫描三层模型
```
开发阶段 构建阶段 部署阶段
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────────┐ ┌────────────┐
│ SAST │ │ SCA │ │ DAST │
│(静态代码)│ │(依赖分析) │ │(运行时测试) │
└────────┘ └────────────┘ └────────────┘
│ │ │
▼ ▼ ▼
PR 阶段 构建阶段 Staging 阶段
(阻断高危) (阻断高危) (阻断高危)
```
### SAST:静态应用安全测试
在代码提交前分析代码逻辑漏洞。
```yaml
# .github/workflows/sast.yml
name: SAST Scan
on: [pull_request]
jobs:
semgrep:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: returntocorp/semgrep-action@v1
with:
config: 'p/default' # 默认规则集
severity: 'error' # 只报告 error 级别
fail_on_exit: true # 高危漏洞阻塞流水线
args: '--json --output=semgrep.json'
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: semgrep.json
```
**Semgrep vs Bandit vs GoSec**:
- **Semgrep**:多语言支持、规则可自定义、误报率低——**首选**
- **Bandit**:[Python](https://docs.python.org/) 专用,简单直接
- **GoSec**:Go 专用,Golang 项目必装
**踩坑**:Semgrep 的规则集太多,选 `p/default` 可能漏掉一些高危规则。建议基于团队的技术栈自定义规则:
```yaml
# semgrep.yaml
rules:
- id: hard-coded-secret
patterns:
- pattern: $PASSWORD = "$$";
- pattern: api_key: "$$"
message: "硬编码密钥不允许出现在代码中"
severity: ERROR
languages: [python, go, java]
```
### SCA:软件成分分析
扫描依赖包的安全漏洞。
```yaml
# Trivy 镜像扫描(最常用)
- name: Trivy Image Scan
uses: aquasecurity/trivy-action@master
with:
image-ref: 'myregistry/my-app:latest'
format: 'sarif'
output: 'trivy-results.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1' # 高危漏洞阻塞流水线
# Trivy 依赖扫描(Go module)
- name: Trivy Dependency Scan
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
scan-ref: '.'
format: 'sarif'
output: 'trivy-deps.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1'
```
**Trivy vs Snyk vs Grype**:
- **Trivy**:免费、全面(镜像+代码+配置)、OCI 兼容——**生产首选**
- **Snyk**:功能最全但付费贵、IDE 插件体验好
- **Grype**:仅镜像扫描,轻量快速
**实际操作经验**:Trivy 扫描速度很快(Go 镜像约 30 秒),但规则库更新有延迟——log4j 漏洞爆发时 Trivy 用了 6 小时才更新规则。解决方案:同时跑 Snyk(规则更新快但付费)做补充。
### DAST:动态应用安全测试
部署后对运行中的服务进行安全测试。
```yaml
# OWASP ZAP 基础扫描
- name: OWASP ZAP Scan
uses: zaproxy/action-baseline@v0.10.0
with:
target: 'http://staging.example.com'
rules_file_name: '.zap/rules.tsv'
cmd_options: '-a' # 允许扫描所有风险等级
fail_action: true
allow_issue_writing: false
```
**ZAP vs Burp Suite vs Nessus**:
- **ZAP**:免费、开源、CI 集成好——**自动化扫描首选**
- **Burp Suite**:功能最强但付费、适合人工渗透测试
- **Nessus**:漏洞扫描器,偏基础设施而非应用层
**DAST 的限制**:只能测试已部署的服务,且无法发现代码逻辑漏洞(如 SQL 注入需要输入向量才能触发)。DAST 的价值在于发现**配置错误**和**运行时漏洞**。
## 密钥检测:第一道防线
```yaml
# GitLeaks 密钥泄露检测
- name: GitLeaks Scan
uses: gitleaks/gitleaks-action@v2
env:
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
# 或者用 trivy 的 secret scan
- name: Trivy Secret Scan
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
scan-ref: '.'
severity: 'CRITICAL,HIGH'
format: 'sarif'
output: 'trivy-secret.sarif'
```
**GitLeaks 规则库**:默认规则覆盖 200+ 种密钥格式(AWS、GCP、Azure、GitHub token、JWT、SSH key 等),基本够用。如果有内部密钥格式,可以自定义规则:
```toml
# .gitleaks.toml
[[rules]]
id = "internal-api-key"
description = "Internal API Key"
regex = '^IAK_[a-zA-Z0-9]{20,}$'
severity = "CRITICAL"
```
## 安全策略:阻塞 vs 通知
这是 DevSecOps 最核心的决策——**扫描发现问题后,要不要阻塞流水线?**
| 扫描类型 | 建议策略 | 理由 |
|---|---|---|
| SAST 高危(SQL 注入、RCE) | **阻塞** | 漏洞直接可被利用 |
| SAST 中危(信息泄露) | **通知** | 需要人工评估 |
| SCA 高危(已知 CVE) | **阻塞** | 有明确 exploit |
| SCA 低危(信息泄露) | **通知** | 取决于依赖链 |
| 密钥泄露 | **阻塞** | 零容忍 |
| DAST 高危 | **阻塞** | 运行时漏洞 |
| 镜像基础镜像漏洞 | **通知+升级建议** | 不是开发可控的 |
**我们的实践**:
- PR 阶段:SAST + SCA + 密钥检测 → **高危阻塞**
- 构建阶段:镜像扫描 → **高危阻塞**
- Staging 阶段:DAST → **全阻塞**
- 每周安全报告:所有漏洞汇总 → **通知安全团队**
```yaml
# 分级阻塞策略
- name: Check Security Results
if: always()
run: |
critical=$(jq '[.results[] | select(.Severity=="CRITICAL")] | length' trivy-results.sarif)
high=$(jq '[.results[] | select(.Severity=="HIGH")] | length' trivy-results.sarif)
if [ "$critical" -gt 0 ]; then
echo "::error::Critical vulnerabilities found: $critical"
exit 1
fi
if [ "$high" -gt 0 ]; then
echo "::warning::High vulnerabilities found: $high (will notify security team)"
fi
```
## 供应链安全:不被注意的盲区
**Supply Chain 攻击是近两年安全事件的主旋律**——npm 包被投毒、CI/CD token 被盗、构建环境被入侵。
### 防护策略
```yaml
# 1. 锁定依赖版本(不使用 latest)
# package.json
"dependencies": {
"express": "4.18.2", # 精确版本,不用 ^4.18.2
"lodash": "4.17.21"
}
# 2. 校验依赖完整性
- name: Verify Dependencies
run: |
npm audit --production --audit-level=high
go list -m all | xargs go vet
# 3. 镜像签名验证(cosign)
- name: Verify Image Signature
run: |
cosign verify --key https://example.com/key.pub \
myregistry/my-app:latest
# 4. SBOM 生成(SPDX 格式)
- name: Generate SBOM
uses: anchore/sbom-action@v0
with:
path: .
format: spdx-json
output-file: sbom.spdx.json
```
**SBOM(Software Bill of Materials)** 是供应链安全的基础设施——它记录了你的软件用了哪些依赖、什么版本。一旦发生供应链攻击(如 log4j),可以快速定位受影响的服务。
```yaml
# GitHub Actions 自动生成 SBOM
- uses: anchore/sbom-action@v0
with:
path: .
format: spdx-json
```
## 安全债务管理:不让漏洞积累
**关键策略**:不是不让漏洞出现,而是建立漏洞追踪和清理机制。
```yaml
# 每周安全报告(自动发送给安全团队和开发负责人)
name: Weekly Security Report
on:
schedule:
- cron: '0 9 * * 1' # 每周一早上 9 点
jobs:
security-report:
runs-on: ubuntu-latest
steps:
- name: Collect Vulnerabilities
run: |
# 从所有仓库收集高危漏洞
gh api repos/${{ github.repository }}/security-advisories \
--jq '.[] | select(.severity=="high")'
- name: Send Report
run: |
curl -X POST ${{ secrets.SLACK_WEBHOOK }} \
-d '{"text":"Weekly Security Report: ${{ steps.collect.outputs.vulns }} critical vulnerabilities"}'
```
**安全债务看板**:用 GitHub Issues 或 Jira 跟踪每个漏洞的修复进度,设置 SLA:
- Critical:24 小时内修复
- High:72 小时内修复
- Medium:7 天内修复
- Low:下一个迭代处理
## 扫描体系上线后的巡检与防退化纪律
安全扫描器本身也是要被持续验证的对象,我给自己定了几条纪律,防止它「配完就永远对」。
**每次升级扫描器都跑回归样例集。** 我维护了一组固定样例:故意植入已知漏洞的 bad 用例 + 一批已确认的误报 good 用例。扫描器升级或规则库更新后,先跑一遍这套回归,比对检出率和误报率有没有漂移。某次 Trivy 规则库大更新后误报率从 5% 跳到 20%,靠回归在上线前就拦住了,没有直接污染开发体验。没有这道回归,规则库一变,你的整个门禁标准就悄悄变了。
**漏洞库停更要报警。** 我给 Trivy/Semgrep 的漏洞库拉取做了监控,连续 48 小时没拉到新规则就告警。规则库静默停更意味着新出的高危 CVE 你的门禁根本防不住,而这往往是最危险的时刻(log4j 那种爆发式场景)。监控规则库活性比监控扫描器本身更能抓住「防线哑了」的盲区。
**安全债按 SLA 强制收敛,不是只记录。** 我固定每周拉一次全仓库高危漏洞清单,按 Critical 24h / High 72h 的 SLA 算逾期项。逾期超阈值的自动 @ 到对应负责人并在周报里点名。安全债最坏的状态不是有漏洞,而是「记了但没人认领、慢慢烂掉」。让看板带收敛趋势(本周新增 vs 本周关闭),数字在涨就是失血。
## FAQ
### Q: 安全扫描太慢拖慢 CI/CD 怎么办?
分层处理:
1. **快速扫描放 PR 阶段**(密钥检测、简单 SAST,<30 秒)
2. **完整扫描放 nightly build**(全量 SAST、DAST,10-30 分钟)
3. **增量扫描放构建阶段**(只扫描变更的文件)
我们的经验:把完整扫描放到 nightly build,PR 阶段只做快速扫描,整体 CI 时间从 15 分钟增加到 18 分钟(可接受)。
### Q: 开发者抱怨安全扫描阻断正常开发怎么办?
1. **明确告知阻断原因**:不要只说"Build Failed",要给出具体的漏洞信息和修复建议
2. **提供一键修复**:自动依赖升级、自动密钥替换
3. **建立安全沙箱**:允许开发者在本地跑扫描工具,提前发现问题
4. **定期培训**:让开发者理解"为什么这个漏洞危险",而不是"为什么我的 PR 被拒"
### Q: 安全扫描结果误报率高怎么处理?
```yaml
# 建立误报豁免机制
- name: Suppress False Positives
run: |
# 把已确认的误报加入 ignore 列表
echo '{"ignore":[{"id":"semgrep-123","reason":"已确认误报:这是测试代码"}]}' \
> .semgrepignore
```
关键原则:**不是消除误报,而是管理误报**。建立一个共享的误报知识库,让全团队都能看到哪些扫描结果是误报,避免重复判断。
---
## 相关文章
- [堡垒机选型与 JumpServer 部署](bastion-jumpserver.md)
- [GitOps 基础设施管理:ArgoCD/FluxCD 声明式部署实战与选型决策树](gitops-infra.md)
- [SSH 加固:密钥登录 + Fail2ban](ssh-hardening.md)
---
## 分布式追踪采样实战:从头采样到尾采样,把成本压下来又不丢异常
URL: https://ops.jiunotes.top/monitor/distributed-tracing-span-sampling.md
摘要: 分布式追踪采样怎么做才不丢关键信息又控住成本?本文讲清头采样与尾采样的取舍、概率采样/限流采样/自适应采样/父级采样策略,附 OpenTelemetry Collector tail_sampling 配置与常见坑。
### Answer
追踪采样分头采样(采集时定)和尾采样(看完全程再定)。高流量用尾采样保住异常与慢
链路、用概率+限流控总量;OTel Collector 的 tail_sampling 处理器按延迟/错误/频次决策,
配内存与等待窗口防丢。
### FAQ
Q: 头采样和尾采样到底差在哪,为什么大家都推尾采样?
A: 头采样在 span 一产生就决定是否保留,简单、零延迟、不占内存,但它"没看到结局就做了决定"——一条最终报错的链路可能在采样点被丢掉了。尾采样把 span 攒到请求结束(或更久),根据这条链路最终是否出错、是否够慢、是否罕见来做决定,能保住真正有价值的异常链路。代价是要缓冲一批 span、占用内存、引入决策延迟。所以高价值但高流量的系统多用尾采样,低流量或边缘采集点用头采样更划算。
Q: 尾采样要等多久才拍板?等太短会不会漏掉慢请求?
A: 关键参数是"等待窗口"(OTel 里是 `wait_for`)。它决定 Collector 收到第一个 span 后最多等多久才对整条链路做决策。窗口太短,跨服务的长链路还没到齐就被迫决策,慢请求会被误判为"普通"而丢掉;窗口太长,内存里堆的 span 越多、延迟越大。经验值从 2 秒起步,跨多服务或长事务的系统调到 5-10 秒,同时配合 `num_traces` 上限防止内存爆。这是个"内存 vs 保真度"的权衡,按你的链路长度实测调。
Q: 概率采样设多少合适?会不会把偶发的错误采样没了?
A: 纯概率采样(如 1%)对平稳流量很省,但偶发的错误链路有概率被整个丢掉,而这恰恰是最该看的。正确做法是在尾采样里叠规则:对"错误链路"和"超过阈值的高延迟链路"强制 100% 保留,对普通成功链路才走概率。这样整体采样率可能只有几个点,但异常链路几乎不丢。也可以按服务重要度分桶:核心支付链路高采样、健康检查类低采样。
Q: 父级采样(parent-based)是什么意思,什么时候用?
A: 父级采样是一种"跟随上游决定"的策略:如果上游已经决定采这条链路,下游服务就跟着采,保证一条链路要么整条都在、要么整条都不在,避免出现"父 span 不在、子 span 孤零零"的残缺链路。它常和头采样搭配:服务收到一个已被上游标记为采样的请求时,自己不再独立抛硬币。在微服务里基本是必开的,否则追踪图谱会碎片化。
Q: 采样之后,我怎么确认没把关键错误采丢了?
A: 三个办法:第一,在尾采样规则里把"错误/高延迟"设为强制保留并单独计数,监控这两条规则的命中率;第二,对极少数核心业务(如支付、登录)做 100% 采样或独立高采样通道,不依赖通用采样;第三,周期性抽几条已知故障做"能否在追踪系统里查到"的探针验证。别只信采样率数字,要看"关键链路的可查到率"。
### Full Content
# 分布式追踪采样实战:从头采样到尾采样,把成本压下来又不丢异常
分布式追踪一旦铺开,第一个让你肉疼的不是接入难度,而是成本。每来一个请求就生成几十条甚至上百条 span,全量上报到后端,存储和流量费用按月跳着涨。更要命的是,绝大多数 span 是健康请求的正常路径,你其实并不需要它们全部。采样就是回答一个问题:**在海量 span 里,留下哪些才既看得清系统、又不被账单压垮**。
但采样最怕两件事:一是把偶发的报错链路采没了,出事时追踪里查无此链;二是采得支离破碎,父 span 在、子 span 不在,图谱拼不起来。这篇文章把头采样、尾采样和各种采样策略讲透,并给你一套能直接落地的取舍原则。
## 1. 为什么必须采样,不能全量
先算笔账。一个中等流量服务,QPS 2000,每请求平均 30 条 span,一天就是约 52 亿条 span。全量存下来,光存储就要按 TB 计,查询也慢。而其中 95% 以上是正常的、重复的、没分析价值的路径。追踪的本质目的是"在异常时定位问题",不是"给每根健康请求建档"。
所以行业共识是:**对高流量系统,采样不是可选项,是必选项**。难点在于怎么采得"聪明"——把采样率压到个位数百分比,同时让错误、慢、异常的链路几乎不丢。
## 2. 头采样:在起点就决定
头采样(head-based sampling)在 span 被创建的那一刻就决定这条链路采不采,通常是抛个硬币(概率采样)或看固定规则。它的好处很直接:
- 零缓冲、零额外内存,决定立刻生效。
- 不引入决策延迟,对延迟敏感的服务友好。
- 实现简单,SDK 里一个 `sampler` 配置就完事。
坏处也明显:它"没看到结局"。一条最终 500 错误的链路,在采样点可能恰好被概率丢掉;一条跨十个服务的慢链路,头采样无法预知它后面会变慢。所以头采样适合流量低、或者只关心"有没有"而非"具体哪条错了"的场景。
## 3. 尾采样:看完全程再拍板
尾采样(tail-based sampling)反过来:先把一条链路相关的 span 收齐,等请求跑完(甚至等多久看配置),再根据"最终表现"决定保留与否。它可以基于这些信号决策:
- 这条链路最终报错了吗(HTTP 5xx、gRPC error、异常)?
- 耗时是否超过某阈值(P99 之外)?
- 这是不是罕见路径(低频接口、特定用户)?
- 是否触发了自定义业务规则(如金额大于某值)?
于是你能做到"错误和慢链路全留、正常链路按比例抽",在极低总采样率下保住最大价值。代价是要有一层组件把 span 缓冲起来、占用内存、引入一点点决策延迟。OpenTelemetry Collector 的 `tail_sampling` 处理器就是干这个的。
## 4. 常见采样策略拆解
单一策略不够用,实战里是组合拳:
- **概率采样**:每条链路按固定比例(如 1%)保留。简单、流量平稳时够用,但会随机丢掉偶发错误。
- **限流采样(rate-limited)**:每秒最多保留 N 条,超出丢弃。控制总量上限很有效,适合防突发。
- **自适应采样**:根据当前流量和错误率动态调采样率,错误率高时自动调高。需要额外实现或平台支持。
- **父级采样**:下游跟随上游的采样决定,保证链路完整性(见 FAQ)。
- **基于属性的采样**:按服务名、接口、用户标签等做不同采样率,核心业务高、旁路低。
生产环境通常是"尾采样 + 错误/慢强制保留 + 普通链路概率/限流"的组合。
## 5. OpenTelemetry Collector 尾采样配置
下面是 `tail_sampling` 处理器的骨架,逻辑是:先看是否错误、是否够慢,命中就 100% 保留;否则走概率采样把总量压住:
```
processors:
tail_sampling:
decision_wait: 10s # 等整条链路到齐的窗口
num_traces: 50000 # 内存里最多攒多少条链路
policies:
- name: errors
type: status_code
status_code:
status_codes: [ERROR]
- name: slow
type: latency
latency:
threshold_ms: 500
- name: probabilistic
type: probabilistic
probabilistic:
sampling_percentage: 5
```
注意顺序:前面的 policy 命中即保留,未命中的才落到概率策略。再配一个 `batch` 处理器和导出器即可。这套配置下,错误和慢链路几乎不丢,整体采样率只有约 5%,成本直接砍掉九成多。
## 6. 内存与等待窗口的权衡
尾采样的命门是内存。它在决策前要把 span 缓存在 Collector 里,所以两个参数要盯紧:
- `decision_wait`:等太久,内存堆得多、延迟大;等太短,长链路没到齐就被迫决策,慢请求被误丢。从 2 秒起,跨多服务调到 5-10 秒。
- `num_traces`:并发缓存的链路数上限,防内存爆。超了会触发淘汰,可能丢还在等待的链路。
经验法则:链路平均跨度越长、服务越多,`decision_wait` 越大;Collector 内存越小,`num_traces` 越要收。上线后监控 Collector 的内存和"被淘汰未决策链路数",这是尾采样最该看的指标。
## 7. 父级采样保证链路完整
微服务里如果每个服务独立抛硬币采样,会出现"父 span 没采、子 span 采了"的残缺链路,追踪图谱全是断点。父级采样让下游跟随上游决定:上游说采,下游就采;上游说不采,下游也不采。在 OTel 里默认开启,和头采样组合使用时尤其重要。别为了"更细粒度"把它关掉,否则你会得到一堆拼不起来的碎片。
## 8. 怎么验证采样没丢关键链路
采样率数字好看不等于没丢东西。建议三条验证线:
- 监控尾采样各 policy 的命中率,特别是 `errors` / `slow` 的命中,确认异常链路确实进了保留池。
- 对核心业务(支付、登录)走独立 100% 采样通道,不依赖通用采样,确保这部分永远可查。
- 周期性用已知故障做探针:故意触发一次错误,确认能在追踪后端查到完整链路。
把"关键链路可查到率"当成 SLO 来盯,比盯"总采样率"更有意义。
## 9. 上线后的巡检与防退化纪律
采样配置也会悄悄退化:一次 Collector 配置回滚可能让尾采样变头采样、一次内存超限可能让 `num_traces` 被调小丢链路。建立纪律:
- **每周**:看尾采样各 policy 命中率趋势,错误链路保留率应稳定接近 100%;若骤降,查是不是规则被改。
- **每周**:核对 Collector 内存与"淘汰未决策链路数",内存持续高位说明 `decision_wait`/`num_traces` 该调或该扩容。
- **每次变更前**:在测试环境用已知错误链路验证"采到率",再上生产;变更后立刻复核。
- **红线**:禁止"为省成本把错误链路也纳入概率采样"。错误和慢链路必须强制保留,这是采样配置不可动的底线。
- **每次扩服务**:新接入的服务默认继承统一采样策略,别让某个服务"裸奔"全量上报拉高成本。
## FAQ
头采样和尾采样到底差在哪,为什么大家都推尾采样?
头采样在 span 一产生就决定是否保留,简单、零延迟、不占内存,但它"没看到结局就做了决定"——一条最终报错的链路可能在采样点被丢掉了。尾采样把 span 攒到请求结束(或更久),根据这条链路最终是否出错、是否够慢、是否罕见来做决定,能保住真正有价值的异常链路。代价是要缓冲一批 span、占用内存、引入决策延迟。所以高价值但高流量的系统多用尾采样,低流量或边缘采集点用头采样更划算。
尾采样要等多久才拍板?等太短会不会漏掉慢请求?
关键参数是"等待窗口"(OTel 里是 `wait_for`)。它决定 Collector 收到第一个 span 后最多等多久才对整条链路做决策。窗口太短,跨服务的长链路还没到齐就被迫决策,慢请求会被误判为"普通"而丢掉;窗口太长,内存里堆的 span 越多、延迟越大。经验值从 2 秒起步,跨多服务或长事务的系统调到 5-10 秒,同时配合 `num_traces` 上限防止内存爆。这是个"内存 vs 保真度"的权衡,按你的链路长度实测调。
概率采样设多少合适?会不会把偶发的错误采样没了?
纯概率采样(如 1%)对平稳流量很省,但偶发的错误链路有概率被整个丢掉,而这恰恰是最该看的。正确做法是在尾采样里叠规则:对"错误链路"和"超过阈值的高延迟链路"强制 100% 保留,对普通成功链路才走概率。这样整体采样率可能只有几个点,但异常链路几乎不丢。也可以按服务重要度分桶:核心支付链路高采样、健康检查类低采样。
父级采样(parent-based)是什么意思,什么时候用?
父级采样是一种"跟随上游决定"的策略:如果上游已经决定采这条链路,下游服务就跟着采,保证一条链路要么整条都在、要么整条都不在,避免出现"父 span 不在、子 span 孤零零"的残缺链路。它常和头采样搭配:服务收到一个已被上游标记为采样的请求时,自己不再独立抛硬币。在微服务里基本是必开的,否则追踪图谱会碎片化。
采样之后,我怎么确认没把关键错误采丢了?
三个办法:第一,在尾采样规则里把"错误/高延迟"设为强制保留并单独计数,监控这两条规则的命中率;第二,对极少数核心业务(如支付、登录)做 100% 采样或独立高采样通道,不依赖通用采样;第三,周期性抽几条已知故障做"能否在追踪系统里查到"的探针验证。别只信采样率数字,要看"关键链路的可查到率"。
## 相关文章
- [OpenTelemetry 实战指南:从 SDK 到 Collector](opentelemetry-guide.md)
- [持续性能剖析:把火焰图接进可观测体系](continuous-profiling.md)
- [eBPF 可观测性:内核级采集不改造应用](ebpf-observability.md)
- [SLO 与错误预算实战:把可靠性目标变成可执行的发布闸门](slo-definition-error-budget-policy.md)
---
## eBPF 可观测性原理:无侵入监控实战,从 kernel trace 到生产落地
URL: https://ops.jiunotes.top/monitor/ebpf-observability.md
摘要: eBPF 原理与实战:kprobe/uprobe/ftrace 三种 attach 方式、常见性能影响、生产部署踩坑(内核版本限制、权限、BTF 缺失)、以及三个真实案例复盘。
### Answer
eBPF 是在 Linux 内核里跑用户态程序的技术,通过 kprobe/uprobe/ftrace 三种 attach 方式采集指标,零侵入、低开销。
核心工具链:BCC(Python 脚本)、bpftrace(一命令一行)、Cilium/Telegraf(生产级)。
关键限制:内核 4.9+(现代发行版都满足)、需要 BTF 元数据(5.4+)、CAP_SYS_ADMIN 权限(容器里用 hostPID+privileged 或 seccomp unconfined)。
最大坑:误以为 eBPF 零开销——高频 tracepoint 会烧 CPU,要配合 sampling 使用。
### FAQ
Q: eBPF 和传统的 strace/ltrace 有什么区别?
A: strace 是系统调用级别的 trace,性能开销极大,不适合生产。eBPF 在内核里直接运行用户态编写的小程序,开销比 strace 低 1-2 个数量级,而且可以持久运行、实时上报指标,不是事后回放。
Q: eBPF 需要什么权限?容器里能用吗?
A: 需要 CAP_SYS_ADMIN 加载 eBPF 程序。普通容器默认没有这个权限。解决方案:① 用 privileged 容器(安全风险高);② 配置 seccomp unconfined + SYS_ADMIN 能力;③ 用 Cilium 等工具做白名单加载。生产建议直接跑在节点上,不走容器。
Q: eBPF 程序写起来很复杂吗?有没有现成工具?
A: 写 C 再编译最灵活但门槛高。日常用 BCC 的 Python 脚本(如 tcplife、execsnoop)或 bpftrace 一行命令就够了。生产场景推荐 Telegraf with eBPF plugin 或 Cilium Hubble,开箱即用。
Q: kprobe 和 tracepoint 选哪个?哪个更稳定?
A: 我第一次用 kprobe 挂到 `do_mkdir` 上,结果内核升级到 5.15 后函数名改成 `vfs_mkdir`,脚本直接报错。 tracepoint 是内核预先定义好的钩子,接口不会因为内部实现改动而变,稳定性好得多。 原则:能用 tracepoint 就优先用,只有 tracepoint 覆盖不到的场景(比如跟踪特定内核函数的参数)才用 kprobe。 查可用 tracepoint 用 `sudo bpftrace -l 'tracepoint:*'`,按类别过滤用 `tracepoint:syscalls:*`。
Q: 生产环境 eBPF 监控要不要做采样?怎么控制开销?
A: 要。我第一次在压测环境跑 `bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%s\n", args->filename); }'`, CPU 直接飙到 40%,因为每个 open 系统调用都打了日志。 正确姿势是聚合而不是打印:`@[comm] = count();` 用 map 累加,定时 `print(@)` 输出。 或者用 LRU map 限制条目数,避免 map 溢出导致 verifier 拒绝加载。 生产部署建议:只采集关键 tracepoint(网络、磁盘 I/O),系统调用级别的高频事件默认关掉或大幅降采样。
### Full Content
# eBPF 可观测性原理:无侵入监控实战,从 kernel trace 到生产落地
去年给公司线上 k8s 集群加可观测性时,遇到了一个诡异问题:**Java 服务偶发性 GC 停顿超过 500ms,[Prometheus](https://prometheus.io/docs/) 抓不到,[Grafana](https://grafana.com/docs/) 看不到根因**。最后用 eBPF 的 `funcslower` 抓到了——是某个 JNI 调用阻塞了 JVM 线程,但 Prometheus 的 GC metric 根本覆盖不到这个场景。
这个问题如果用传统方式排查,至少要装 APM、改代码、重启服务。eBPF 的好处是**零侵入**——不需要改代码、不需要重启、不需要插桩,直接在内核层面看发生了什么。
## eBPF 是什么:一句话解释清楚
eBPF(extended Berkeley Packet Filter)原本是用来过滤网络包的内核功能。后来被扩展成一个可以在内核里安全执行用户态编写的小程序的框架。
**核心思想**:在 [Linux](https://www.kernel.org/doc/html/latest/) 内核里跑"安全沙箱",允许用户态程序在内核上下文里执行,但经过验证器(verifier)检查,确保不会崩溃内核或访问非法内存。
```
用户态程序(BPF 字节码)
↓ ebpf verifier 检查安全
内核态执行(挂载到钩子点)
↓ 产出数据
ring buffer / perf event / map
↓ 用户态读取
监控工具(BCC / bpftrace / 自研 agent)
```
**关键点**:verifier 是核心——它保证你的 eBPF 程序不会无限循环、不会访问内核未授权内存、不会导致内核崩溃。如果 verifier 过不了,程序根本加载不进去。
## 三种 Attach 方式:kprobe / uprobe / tracepoint
这是 eBPF 监控的三大入口,选对类型决定你能看到什么。
### kprobe:内核函数级别
挂在内核函数入口或出口,能看到任何内核函数的调用。
```bash
# bpftrace 一行命令:跟踪 mkdir 系统调用的延迟分布
bpftrace -e 'kprobe:do_mkdir { @start[tid] = nsecs; }
kretprobe:do_mkdir /@start[tid]/ {
@latency = lshift(nsecs - @start[tid], 0);
delete(@start[tid]);
}'
# 输出示例
# @latency:
# [1000, 2000) 3
# [2000, 4000) 15
# [4000, 8000) 8
```
**kprobe 的限制**:kernel symbol 可能被 kabi 改名,跨内核版本兼容性差。比如 `do_mkdir` 在 5.15+ 变成了 ` vfs_mkdir`,脚本要跟着改。
### uprobe:用户空间函数级别
挂在用户态进程的函数上,能看到应用程序内部行为。
```bash
# 挂到 Java 进程的某个函数(需要 PID)
bpftrace -e 'uprobe:/usr/bin/java:_ZNK6google7protobuf7Message10InitializationErrorStringEv {
printf("Java function called by pid %d\n", pid);
}'
# 跟踪 [Python](https://docs.python.org/) 函数的执行时间
bpftrace -e 'uprobe:/usr/bin/python3.11:main { @start[pid] = nsecs; }
uretprobe:/usr/bin/python3.11:main /@start[pid]/ {
printf("python3 pid %d took %lld ns\n", pid, nsecs - @start[pid]);
delete(@start[pid]);
}'
```
**uprobe 的限制**:需要知道目标二进制路径,且函数符号可能 stripped。生产环境常用 `readelf` 或 `nm` 先确认符号名。
### tracepoint:预定义内核事件
tracepoint 是内核预先定义好的钩子,比 kprobe 稳定(不会因为内部实现改变而失效)。
```bash
# 列出所有网络相关的 tracepoint
sudo bpftrace -l 'tracepoint:*net*' | head -20
# 跟踪 TCP 连接建立
sudo bpftrace -e 'tracepoint:syscalls:sys_exit_connect {
@estab[tid] = args->err;
}'
```
**决策树**:
- 想看系统调用 → `tracepoint:syscalls` 优先,不行再 kprobe
- 想看内核函数 → kprobe
- 想看用户态函数 → uprobe
- 不确定用哪种 → 先用 `bpftrace -l` 列出可用的 tracepoint,再决定
## 生产级工具链:BCC / bpftrace / Telegraf / Cilium
### BCC:Python 脚本集合
BCC 提供几十种现成的监控脚本,是入门 eBPF 最快的路径。
```bash
# 安装 BCC(Ubuntu 22.04)
sudo apt install bpfcc-tools linux-headers-$(uname -r)
# 一键查看所有可用脚本
bcu list | head -30
# 经典脚本:tcplife - 展示 TCP 连接的生存时间和字节数
sudo tcplife -l
# 经典脚本:execsnoop - 跟踪新进程启动
sudo execsnoop -T
# 经典脚本:biosnoop - 块设备 I/O 延迟
sudo biosnoop -T
```
**个人判断**:BCC 脚本适合快速排查问题,但生产监控不建议直接用 BCC 脚本——它们是调试工具,不是监控系统。生产环境应该用 Telegraf 或自建 agent。
### bpftrace:一行命令的瑞士军刀
bpftrace 语法类似 awk + C,学习曲线比 BCC 脚本陡,但灵活性高得多。
```bash
# 安装
sudo apt install bpftrace
# 监控 open 系统调用的文件路径分布
sudo bpftrace -e 'tracepoint:syscalls:sys_exit_openat {
printf("%s %s\n", comm, str(args->filename));
}'
# 监控 TCP 重传(网络问题的神器)
sudo bpftrace -e 'kprobe:tcp_retransmit_skb {
@retrans[key(arg0, arg0->sk)] = count();
}'
```
**实操经验**:`bpftrace -e 'hist(args->size)'` 可以画出 open 系统调用参数大小的分布——这是我发现一个大文件拷贝导致磁盘 I/O 尖峰的快捷方式。
### Telegraf with eBPF:生产级方案
Telegraf 有官方 eBPF plugin,支持开箱即用的系统指标采集。
```toml
# telegraf.conf
[[outputs.prometheus_client]]
listen = ":9273"
[[inputs.ebpf]]
programs = [
{ name = "syscall", paths = ["tracepoint:syscalls:sys_exit_read", "tracepoint:syscalls:sys_exit_write"] },
{ name = "network", paths = ["tracepoint:net:net_dev_rx"] },
]
```
```bash
telegraf --config telegraf.conf --test
```
**我的建议**:Telegraf eBPF plugin 适合基础指标(system call 计数、网络统计),但复杂场景(如追踪特定应用的调用链)还是 bpftrace 更灵活。
### Cilium Hubble:[K8s](https://kubernetes.io/docs/) 网络可观测性的天花板
Cilium 自带 Hubble,用 eBPF 做 K8s 网络层的完全可观测性——流量矩阵、DNS 查询、连接状态,都不需要改业务代码。
```bash
# 查看 Hubble 拓扑
hubble observe --follow
# 查看 DNS 查询
hubble observe --type dns
# 查看连接状态变化
hubble events --type connection
```
**Hubble 的核心价值**:在 K8s 里看东西南北向流量,不需要 service mesh,不需要 sidecar,eBPF 直接搞定。如果你的集群用了 Cilium,这是必装组件。
## 性能影响:eBPF 不是零开销
很多人误以为 eBPF 零开销,这是个误区。**高频 tracepoint 会烧 CPU**,必须配合采样策略。
### 三个真实踩坑案例
**案例一:采样率设太高,CPU 飙到 40%**
```bash
# ❌ 错误:每个系统调用都打印,CPU 直接爆
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat {
printf("%s open %s\n", comm, str(args->filename));
}'
# ✅ 正确:每 100 次采样一次
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat {
@[comm] = count();
if (@[comm] % 100 == 0) {
printf("%s open %s\n", comm, str(args->filename));
}
}'
```
**教训**:生产环境不要直接跑 `bpftrace -e 'print(...)'`,一定要配采样或聚合。
**案例二:map 溢出导致程序被 verifier 拒绝**
```bash
# ❌ 错误:map 大小设太小,频繁报错
bpftrace -e 'kprobe:do_sys_open {
@a[tid] = args->dfd; # 每个 tid 一条,map 爆了
}'
# ✅ 正确:用 LRU map 限制条目数
bpftrace -e 'kprobe:do_sys_open {
@a[lru] = args->dfd; # 自动淘汰最旧条目
}'
```
**教训**:eBPF map 有大小限制(通常 4MB),高频场景要用 LRU hash 或 percpu array。
**案例三:BTF 缺失导致 kfunc 加载失败**
```
# 报错信息
Error: failed to apply BTF map: Invalid argument
Error: no BTF found for kernel
```
```bash
# 检查内核是否支持 BTF
ls /sys/kernel/btf/vmlinux && echo "BTF OK" || echo "BTF missing"
# 修复(Ubuntu 22.04 通常已有)
sudo apt install linux-modules-extra-$(uname -r)
sudo modprobe btf
```
**教训**:某些定制内核(如云厂商的优化内核)会去掉 BTF 支持,此时只能用 tracepoint,不能用 kprobe/kfunc。生产前务必先检查。
## 权限与部署:容器里怎么用 eBPF
eBPF 加载需要 `CAP_SYS_ADMIN`,这在容器里默认没有。三种方案:
```yaml
# 方案一:privileged 容器(最简单但最危险)
securityContext:
privileged: true
# 方案二:只加需要的能力(推荐)
securityContext:
capabilities:
add: ["SYS_ADMIN", "BPF", "PERFMON"]
drop: ["ALL"]
seccompProfile:
type: Unconfined
# 方案三:hostNetwork + hostPID(Cilium Hubble 推荐)
hostNetwork: true
hostPID: true
```
**我的判断**:能跑在节点上就别放容器里。eBPF 的核心优势是"看到容器看不到的东西",如果把 eBPF 本身关在容器里,反而丧失了最大价值。
## FAQ
### Q:eBPF 能监控什么?有什么限制?
能监控的范围非常广:系统调用、网络包、函数调用、磁盘 I/O、内存分配、信号、定时器……几乎内核做的任何事。
**主要限制**:
- 内核版本 ≥ 4.9(XDP 等高级功能需要 4.18+)
- 需要 BTF(5.4+ 默认开启,旧内核需要手动安装)
- 不能监控已经被内核移除的功能(如某些旧的 tracepoint)
- XDP 等高级功能需要网卡驱动支持
### Q:eBPF 和 APM 工具(如 Jaeger、SkyWalking)有什么区别?
APM 工具需要在代码里插桩(SDK、agent),要改代码或至少部署 sidecar。eBPF 完全零侵入,内核层面就能看到所有进程的系统调用和网络行为。
**适用场景**:APM 适合追踪业务逻辑链路(请求从哪个入口来、走了哪些服务);eBPF 适合系统层诊断(为什么慢、哪里卡了、资源瓶颈在哪)。两者互补,不冲突。
### Q:eBPF 程序出问题了会搞挂内核吗?
不会。eBPF verifier 在加载前会静态分析程序,确保:
- 程序会在有限步数内终止(无无限循环)
- 不会访问未授权内存
- 不会修改不属于自己的数据结构
- map 操作在边界内
如果 verifier 过不了,程序根本加载不进去。历史上出现过极少数 verifier bypass 漏洞(CVE-2021-3490 等),但都有补丁修复。生产环境保持内核更新即可。
---
## 相关文章
- [Linux 监控 CPU:top 一行 5 个百分比字段排障决策树](linux-cpu-monitor.md)
- [Linux 内存监控实战与 OOM 排障:free/vmstat/ps 字段解读 + cgroup v2 内存限制决策树](linux-memory-monitor.md)
- [node_exporter 指标缺失排查:6 大症状决策树 + 4 个常见翻车原因](node-exporter-troubleshoot.md)
- [SLO 与错误预算实战:把可靠性目标变成可执行的发布闸门](slo-definition-error-budget-policy.md)
- [主机三件套 CPU / 内存 / 磁盘IO 怎么看才不误判:指标解读决策树](monitor-host-signals.md)
---
## FinOps 可观测性成本优化:智能采样与分层存储实战指南
URL: https://ops.jiunotes.top/monitor/finops-monitoring.md
摘要: FinOps 可观测性落地:智能采样降成本、冷热分层存储、高基数指标治理、成本归因到团队/服务,附真实数据对比和采坑复盘。
### Answer
FinOps 可观测性的核心是"花得值"——通过智能采样把高频低价值指标降采样,通过冷热分层让热数据快查、冷数据便宜存,通过标签治理减少无效 cardinality。
最大成本杀手不是查询而是存储:高基数指标和全量日志是最烧钱的两类数据。
实战经验:引入智能采样后监控成本平均下降 60-80%,但要把采样率和告警灵敏度之间的 tradeoff 讲清楚。
### FAQ
Q: 智能采样会影响告警灵敏度吗?
A: 会影响,但可以接受。关键原则:告警相关的指标不降采样,只有非告警类指标(如调试用的高频 metric)才降采样。实际测试中,把 scrape_interval 从 15s 调到 60s 对 CPU/内存类指标影响可忽略,但对瞬态错误(如偶尔的 5xx)可能漏报——这类指标保持 15s。
Q: 热数据多久算热?分层阈值怎么定?
A: 没有标准答案,根据查询模式定。我们的经验:7 天内是热数据(每天查询),7-30 天是温数据(周报/月报),30 天以上是冷数据(合规审计)。热数据用 SSD 本地存储,温数据用 HDD 对象存储,冷数据用 S3/GCS 归档。
Q: FinOps 和传统成本优化有什么区别?
A: 传统成本优化是"砍预算",FinOps 是"优化每一块钱的投入产出比"。前者关注"花了多少",后者关注"花得值不值"。比如砍掉某个指标的采集是传统做法,评估这个指标带来的业务价值再决定要不要保留是 FinOps 做法。
Q: 采样率和保留期调整后怎么确认没有悄悄漏报告警?
A: 调整前后要跑一次「告警回放」:拿过去 7 天真实数据,用新策略重新评估所有告警规则,比对触发次数和触发时间有没有漂移。重点核对 P0 告警的触发时间——如果降采样导致某条 P0 告警晚了 30 秒触发,就要把该指标单独锁回 15s。降采样不是无脑降,每降一档都要回测告警灵敏度。
### Full Content
# FinOps 可观测性成本优化:智能采样与分层存储实战指南
去年我们监控栈的成本达到了月均 $8,000(主要是 [Prometheus](https://prometheus.io/docs/) 集群的存储 + Thanos 的对象存储),CFO 找我谈了一次话后,我开始认真做 FinOps 了。六个月内成本降到了 $1,800/月,降幅 77%,而且告警准确率没有下降。
这篇分享整个过程和关键决策,所有内容来自我们在 Prometheus + Thanos + VictoriaMetrics 栈上的真实部署经验。
## 成本拆解:钱花在哪了
```
月度成本分析(改造前)
─────────────────────────────────────────────
Prometheus TSDB 存储(热数据 30 天) $3,200
Thanos Query / Sidecar 运维 $1,800
S3 对象存储(冷数据归档) $1,500
外部监控服务(Datadog 免费版升级) $1,200
─────────────────────────────────────────────
合计 $7,700/月
```
**最大成本项不是查询**,而是**存储**。每增加一个活跃的时间序列,Prometheus 大约消耗 200MB 基线内存,加上磁盘存储。100 万活跃 series × 30 天 × ~$0.03/GB/月 ≈ 可观的数字。
## 第一刀:智能采样——降采样比例最高 80%
### 指标分级
不是所有指标都值得 15 秒采样一次。我们把指标分成四级:
| 级别 | 采样间隔 | 典型指标 | 理由 |
|---|---|---|---|
| **P0**(必保) | 15s | `up`、告警相关 metric、核心业务指标 | 告警依赖,不能丢 |
| **P1**(重要) | 30s | CPU、内存、磁盘、网络 | 趋势分析够用 |
| **P2**(一般) | 60s | HTTP 请求计数、错误计数 | 降采样后趋势仍清晰 |
| **P3**(可选) | 5min | 调试用的高频 metric、debug 指标 | 不影响核心告警 |
### 实现方式
**Prometheus 原生方式**(按 job 粒度控制):
```yaml
scrape_configs:
- job_name: 'critical'
scrape_interval: 15s
static_configs:
- targets: ['api-server:8080']
- job_name: 'routine'
scrape_interval: 30s
static_configs:
- targets: ['web-server:8080']
- job_name: 'debug'
scrape_interval: 5m
metrics_path: '/debug/metrics'
static_configs:
- targets: ['internal-tools:9090']
```
**VictoriaMetrics 方式**(支持更细粒度的 retention):
```yaml
# VictoriaMetrics 的 vmagent 配置
global:
scrapeInterval: 15s
remoteWriteUrls:
- http://vminsert:8480/insert/prometheus/api/v1/write
scrape_configs:
- job_name: 'critical'
metrics_path: /metrics
scrape_interval: 15s
- job_name: 'routine'
metrics_path: /metrics
scrape_interval: 30s
# VictoriaMetrics 独有的 retention_override
# 热数据保留 7 天,温数据 30 天,冷数据 1 年
_scrape_interval: 30s
```
**踩坑**:降采样后 `rate()` 计算窗口要对齐。如果 scrape_interval 是 30s,rate 窗口至少要是 4×30s=2min,否则会漏采样点导致 rate 计算不准确。
### 效果数据
改造后指标数量从 120 万降到 35 万,存储成本从 $4,700 降到 $1,400/月,降幅 **70%**。告警漏报率从 0.02% 升到 0.05%——还在可接受范围内。
## 第二刀:分层存储——冷热数据各归各位
### 分层策略
```
时间轴
─────────────────────────────────────────────────────────▶
0d 7d 30d 365d
│ │ │ │
▼ ▼ ▼ ▼
┌──────────┬────────────┬────────────────────┐
│ 热数据 │ 温数据 │ 冷数据 │
│ (SSD本地) │ (HDD本地) │ (S3/GCS归档) │
│ <7天 │ 7-30天 │ >30天 │
└──────────┴────────────┴────────────────────┘
```
**实现**:Thanos compact + object storage,或 VictoriaMetrics 的 retention 策略。
```yaml
# VictoriaMetrics 单节点方案(最简单)
vmstorage:
retentionPeriod: 1y # 总保留期
# 通过 query 参数控制查询范围
# 热查询:/api/v1/query?query=up&start=-7d
# 温查询:/api/v1/query?query=up&start=-30d
# 冷查询:/api/v1/query?query=up&start=-1y
```
```yaml
# Thanos 方案(更复杂但功能更强)
# Thanos compact 自动把 Prometheus TSDB 块压缩并推到 S3
compactor:
data-dir: /var/thanos/compact
retentions:
- 7d # 热数据(Prometheus 本地保留)
- 30d # 温数据(S3 保留)
- 1y # 冷数据(S3 归档)
```
**关键选择**:VictoriaMetrics 方案更简单(单二进制),Thanos 方案更灵活(兼容现有 Prometheus 生态)。我们选了 VictoriaMetrics,因为团队规模小、维护成本优先。
### 成本对比
| 方案 | 热数据成本 | 冷数据成本 | 总成本/月 | 复杂度 |
|---|---|---|---|---|
| 全 Prometheus 本地 | $4,700 | — | $4,700 | 低 |
| Thanos + S3 | $2,800 | $600 | $3,400 | 中 |
| VictoriaMetrics | $1,200 | $300 | $1,500 | 低 |
## 第三刀:高基数治理——清理无效 cardinality
### 诊断高基数指标
```promql
# 统计每个 __name__ 的 series 数量
topk(20, count by (__name__) ({__name__=~".+"}))
# 找出高基数标签
topk(10, count by (__name__, some_label) ({__name__=~".+"}))
```
### 常见的高基数来源
```yaml
# ❌ 危险:request_id 是高基数标签(每个请求唯一)
metric:
name: http_requests_total
labels:
- request_id # 几百万 unique value → 几百万 series
# ✅ 正确:去掉高基数标签,改用聚合
metric:
name: http_requests_total
labels:
- service_name # 几十个 value → 几十条 series
- endpoint # 几百个 value → 几百条 series
```
**实操经验**:我们清理了三个高基数指标后,活跃 series 从 120 万降到 65 万,直接省了 $1,500/月存储成本。
### recording rule 预聚合
对于需要高粒度但又不能丢的指标,用 recording rule 在采集端就聚合:
```yaml
# prometheus.yml
rule_files:
- aggregation-rules.yml
# aggregation-rules.yml
groups:
- name: http-aggregation
rules:
- record: job:http_requests:rate5m
expr: sum by (job, status) (rate(http_requests_total[5m]))
# 原始指标 http_requests_total{user_id} 被丢弃
# 只保留聚合后的 job:http_requests:rate5m
```
## 成本归因:谁在用监控资源
```yaml
# VictoriaMetrics 支持标签级别的成本归因
# 在 VM 仪表盘中加一个 cost 面板:
# sum by (team) (rate(vm_rows{team=~".+"}[1h]))
# × $0.03 / row / month
```
**我们的实践**:给每个服务打上 `team` 和 `env` 标签,然后在 [Grafana](https://grafana.com/docs/) 里做一个"成本透视"面板——每个团队能看到自己服务消耗了多少监控资源。这个做法让 teams 开始主动优化自己的指标,成本意识明显提升。
## 常见误区
**误区一:"少采集点指标就能省钱"**
错。省钱的关键是**减少 cardinality** 而不是减少指标数。1000 个指标 × 10 个 series = 1 万 series,和 10 个指标 × 1000 个 series 的成本一样。把标签精简到最小必要集合才是省钱之道。
**误区二:"对象存储就是便宜的"**
S3/GCS 确实比 SSD 便宜,但读取冷数据时的延迟和高昂的 GET 请求费用可能超出预期。我们的经验:**查询频率 <1 次/周的指标才值得归档到对象存储**,否则直接延长本地保留期更划算。
**误区三:"FinOps 是一次性项目"**
不是。监控成本会随业务增长自然上升,需要**季度审查**指标卡、采样策略和保留策略。我们每季度做一次"指标审计"——问每个 team "这个指标还在用吗?"
## 降本上线后的巡检与防反弹纪律
成本降下来不是终点,我给自己定了几条长期纪律,防止它随业务增长悄悄反弹回去。
**每季度做一次「指标审计 + 告警回放」。** 降本最大的隐患是「降完当掉链子没人管」,某次新服务接入后活跃 series 悄悄涨了 40%。我固定每季度跑两件事:一是拉全量 `count by (__name__)` 排一遍新晋高基数指标,清掉没人用的;二是用新采样策略对过去 7 天真实数据做告警回放,比对新旧 P0 告警触发次数。回放是降本的护栏——只要发现某条告警因为降采样晚触发或漏触发,就把那个指标单独锁回 15s,别为了省钱牺牲告警灵敏度。
**给存储水位设提前告警,别等爆。** 我把热/温/冷各层的存储用量都打点,在 80% 水位就告警(不是 95% 才响)。冷层对象存储的 GET 请求费用容易被忽视,我专门监控「冷数据被频繁查询」的指标,某服务如果查冷数据很频繁,说明它的数据其实该升回温层,硬留在冷层反而因高频 GET 更贵。降本要盯着「哪类数据被误放在贵层」,不是只看总账单。
**成本归因面板要落到团队,才有持续动力。** 我把按 team 维度的成本面板做进 Grafana 并配月环比,每个 team 能看到自己这月花了多少、比上月涨还是跌。纯靠运维单方省,撑不过两三个季度——业务一扩张又涨回去。让花钱的团队看到账单并负责优化,降本才能变成常态而不是项目。
## FAQ
### Q: 降采样后还能做实时告警吗?
可以,但需要分层设计。P0 级别指标保持 15s 采样,用于告警;P1-P3 降采样后只用于 Dashboard 和历史查询,不参与告警规则。告警规则和采集策略要严格分离——不要把同一个指标既用于告警又用于降采样。
### Q: 历史数据查询变慢怎么办?
分层存储后,查 30 天前的数据需要从对象存储读取,延迟从毫秒级变成秒级甚至分钟级。解决方案:
1. 用 `start` 参数限制查询范围,避免全表扫描
2. 对热点历史数据用 Thanos query-frontend 缓存
3. 查询冷数据时接受秒级延迟,不要期望即时响应
### Q: 哪些指标绝对不能降采样?
- `up`(目标存活状态)—— 15s 是底线,更低也没有意义
- 告警规则依赖的指标—— 降采样会导致告警延迟或漏报
- 计费相关的指标—— 精确计数很重要
- 短生命周期事件(如函数执行)—— 降采样后采样不到
**判断标准**:问自己"如果这个指标丢了 10 秒数据,会发生什么严重问题?"如果答案是"会",就不降采样。
---
## 相关文章
- [Prometheus TSDB 深度运维:WAL/Head/Block 结构与 5 个真实故障](prometheus-tsdb-operations.md)
- [Zabbix + Prometheus 混合监控架构:传统基础设施 + 云原生服务的双栈方案](zabbix-prometheus-hybrid.md)
- [Alertmanager 告警降噪实战:抑制器 + 路由树 + 静默配置四步降噪法](alertmanager-noise-reduction.md)
- [Prometheus 长期存储与多集群查询实战:Thanos 架构落地与踩坑复盘](prometheus-thanos-storage.md)
---
## GitOps 基础设施管理:ArgoCD/FluxCD 声明式部署实战与选型决策树
URL: https://ops.jiunotes.top/monitor/gitops-infra.md
摘要: GitOps 核心原理、ArgoCD vs FluxCD 选型对比、多集群管理、Rollback 策略、以及应用级回滚 vs 基础设施级回滚的实战经验。
### Answer
GitOps 的核心是"代码即基础设施"——所有资源定义在 Git 仓库,ArgoCD/FluxCD 等 controller 持续同步集群状态到 Git 描述的状态。
ArgoCD 适合 UI 依赖强、多环境管理的场景;FluxCD 适合 CLI 优先、CI/CD 深度集成的团队。
关键陷阱:直接 `kubectl apply` 绕过 Git 会导致漂移,GitOps 工具检测到 drift 后会自动修复,但可能覆盖掉你的手动变更。
### FAQ
Q: ArgoCD 和 FluxCD 选哪个?
A: 没有绝对答案。ArgoCD 可视化强、UI 体验好,适合运维主导的团队;FluxCD 轻量、Git native、与 GitHub Actions 集成更顺滑,适合开发主导的团队。我们的判断:小团队 (<50 人) 用 FluxCD,大团队或多集群用 ArgoCD。
Q: GitOps 和传统 CI/CD 有什么区别?
A: 传统 CI/CD 是 push 模型——构建后主动推送到集群;GitOps 是 pull 模型——集群上的 controller 主动拉取 Git 状态并同步。GitOps 的好处是声明式、可审计、可回滚——所有变更都在 Git 里有记录。
Q: 直接 kubectl 改集群会破坏 GitOps 吗?
A: 会。ArgoCD/FluxCD 检测到 drift 后会强制将集群状态重置为 Git 中的期望状态,你刚才的改动就丢了。正确做法:所有变更都走 Git PR,经过 review 后再 merge。这是 GitOps 的文化约束,不是技术限制。
Q: GitOps 上线之后怎么持续巡检和防漂移?
A: 盯三条。一,定期跑一次「集群实际状态 vs Git 期望状态」的漂移扫描(ArgoCD 用 argocd app get --show-diff、FluxCD 用 flux reconcile),非零漂移必须有人认领原因。二,把 controller 自身的健康(reconcile 成功率、git pull 时延、controller Pod 重启次数)挂进监控,controller 自己挂了 GitOps 会静默失效。三,prune 误删前强制 dry-run 预览删除列表,生产环境配好保护性 ignoreDifferences。
### Full Content
# GitOps 基础设施管理:ArgoCD/FluxCD 声明式部署实战与选型决策树
2023 年我们团队从 Jenkins pipeline 切换到 ArgoCD,过程不算痛苦,但有几个踩坑点值得记下来——尤其是要处理好"手动变更"和"GitOps 流程"之间的摩擦。
## GitOps 核心概念:一句话讲清楚
GitOps = Git 作为单一事实源 + 自动同步机制。
```
Git 仓库(source of truth)
↓ 开发者 push manifest
Controller(ArgoCD/FluxCD)
↓ 持续 reconcile
[Kubernetes](https://kubernetes.io/docs/) 集群(desired state → actual state)
```
**三个关键原则**:
1. **所有变更走 Git**——禁止直接 kubectl 操作生产集群
2. **自动同步**——Controller 持续比对并修复 drift
3. **版本可追溯**——每次变更都有 commit hash,可回滚到任意历史版本
## ArgoCD vs FluxCD:选型决策树
| 维度 | ArgoCD | FluxCD |
|---|---|---|
| 架构 | Go 编写,单二进制 | Go 编写,模块化 |
| 界面 | **Web UI(强项)** | CLI 为主,Web UI 较弱 |
| 同步模式 | pull(controller 主动拉) | pull(同 ArgoCD) |
| 多集群 | 原生支持,Web UI 可视化 | 支持,需配置多个 source |
| 与 GitHub 集成 | 通过 Webhook | **原生支持 GitHub App** |
| 学习曲线 | 中(概念多但 UI 友好) | 低(简单直接) |
| 资源占用 | 较高(UI + 数据库) | 较低(无状态) |
| 适合团队 | 大团队、多环境、UI 偏好 | 小团队、CLI 偏好、GitHub 深度用户 |
**选型建议**:
- 团队有专职运维 → **ArgoCD**(UI 降低运维负担)
- 团队是纯开发导向、GitHub 重度用户 → **FluxCD**(CI/CD 集成更顺滑)
- 同时管 K8s + [Terraform](https://developer.hashicorp.com/terraform/docs) → **ArgoCD**(支持跨平台资源)
- 最小化运维成本 → **FluxCD**(轻量、少依赖)
## ArgoCD 最小可用配置
```yaml
# app-of-apps 模式:用一个 Application 管理所有子应用
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: platform-apps
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/myorg/platform-infra.git
targetRevision: main
path: apps
destination:
server: https://kubernetes.default.svc
namespace: argocd
syncPolicy:
automated:
prune: true # 删除 Git 里不存在的资源
selfHeal: true # 自动修复 drift
syncOptions:
- CreateNamespace=true
```
```yaml
# apps/monitoring.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: monitoring
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/myorg/platform-infra.git
targetRevision: main
path: overlays/monitoring
destination:
server: https://kubernetes.default.svc
namespace: monitoring
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
```
**关键配置解析**:
- `prune: true`:Git 里删了资源,集群上也会跟着删——**危险但必要**
- `selfHeal: true`:有人手动改了集群,Controller 会自动改回来——**防止 drift 累积**
- `targetRevision: main`:指向具体分支,建议**不要指向 main,指向 release tag 或特定 branch**
## FluxCD 最小可用配置
```yaml
# fluxctl install --namespace=flux-system | kubectl apply -f -
# 上面的命令会自动安装 FluxCD
# 定义 Git 源
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: GitRepository
metadata:
name: platform-infra
namespace: flux-system
spec:
interval: 1m0s # 每 1 分钟检查一次变化
url: https://github.com/myorg/platform-infra.git
ref:
branch: main
secretRef:
name: github-token # 需要 Git token
---
# 定义 K8s 目标
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
name: monitoring
namespace: flux-system
spec:
interval: 5m0s
sourceRef:
kind: GitRepository
name: platform-infra
path: ./overlays/monitoring
prune: true
wait: true
healthCheck:
- apiVersion: v1
kind: Namespace
name: monitoring
```
**ArgoCD vs FluxCD 实际使用感受**:
- ArgoCD 的 UI 是真实生产力工具——可以直接在 Web 上看每个资源的 diff、手动 sync、看事件日志
- FluxCD 的 CLI 体验好但调试麻烦——出问题要看 `kubectl get events -n flux-system` 和 flux 的 reconcile log
## 多集群管理:一个 Git 管所有集群
```yaml
# clusters/prod/kustomization.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
name: prod-apps
namespace: flux-system
spec:
interval: 5m
sourceRef:
kind: GitRepository
name: platform-infra
path: ./clusters/prod
prune: true
wait: true
targetNamespace: apps-prod
---
# clusters/staging/kustomization.yaml(同上结构,不同 path)
```
**ArgoCD 的多集群方式**:通过 `argocd cluster add ` 把多个集群注册到同一个 ArgoCD 实例,然后在 UI 里为每个集群创建独立的 Application。
**踩坑**:多集群时 **namespace 隔离要显式配置**——两个集群的同一个 namespace 会冲突。建议在 Git 里用 `namespace: prod-apps` vs `namespace: staging-apps` 做区分。
## Rollback 策略:三种回滚方式
### 方式一:Git revert(推荐)
```bash
# 找到出问题的 commit
git log --oneline -10
# revert 那个 commit
git revert abc1234
# push 后 Controller 自动同步回滚
git push origin main
```
**优点**:可审计、可 review、有历史记录。**这是生产环境的首选方式**。
### 方式二:ArgoCD UI 回滚
在 ArgoCD UI 里选择 "Rollback" → 选历史版本 → "Sync"。
**优点**:快速、可视化。**缺点**:绕过了 Git,没有 commit 记录,不适合审计要求高的场景。
### 方式三:FluxCD image update rollback
```bash
# 查看当前镜像版本
flux get images -n flux-system
# 回滚到指定版本
flux create image update my-app \
--image=myregistry/my-app \
--target-value=1.2.3 \
--export | kubectl apply -f -
```
**适用场景**:只在镜像更新场景下用,其他场景不适用。
## 常见问题排障
**问题一:应用一直处于 `OutOfSync` 状态**
原因:集群状态和 Git 定义不一致,但 `selfHeal` 没有启用或 sync policy 配置错误。
排查:
```bash
# ArgoCD
argocd app get --refresh
# FluxCD
flux get kustomizations
```
修复:手动 sync 一次,确认 Git 定义是正确的,再让 Controller 自动修复。
**问题二:Prune 误删了生产资源**
原因:`prune: true` + 开发者忘记从 Git 里删除旧资源。
修复:
```bash
# 立即恢复被删除的资源
kubectl apply -f
# 然后配置保护性 prune
# 在 ArgoCD 的 Application 里加:
# spec:
# ignoreDifferences:
# - jsonPointers:
# - /spec/replicas
```
**教训**:prune 是双刃剑,生产环境建议先用 `--dry-run` 确认删除列表,再正式执行。
**问题三:ArgoCD 登录 401**
```bash
# 获取 admin 密码
kubectl -n argocd get secret argocd-initial-admin-secret \
-o jsonpath="{.data.password}" | base64 -d
# 如果是 K8s 内置认证问题,检查 argocd-cm ConfigMap
kubectl get configmap argocd-cm -n argocd -o yaml
```
## FAQ
### Q: GitOps 适合微服务架构吗?
适合,而且微服务越多越需要 GitOps。微服务的部署复杂度呈指数增长——20 个服务手动部署是噩梦,但用 GitOps 就是 20 个 YAML 文件的事。关键是要有**分层管理**:基础组件(monitoring、logging)一层,业务服务一层,配置和环境差异通过 overlay 管理。
### Q: 和 Helm/Kustomize 是什么关系?
GitOps 是**流程**(怎么管变更),Helm/Kustomize 是**工具**(怎么渲染模板)。两者正交:
- ArgoCD/FluxCD 可以用 Helm chart 作为 source
- ArgoCD/FluxCD 可以用 Kustomize overlay 管理多环境
- 也可以直接用裸 YAML(不推荐,维护成本高)
**我们的实践**:基础组件用 Helm(成熟稳定),业务应用用 Kustomize overlay(轻量灵活),GitOps controller 负责同步。
### Q: GitOps 能解决所有部署问题吗?
不能。GitOps 解决的是**声明式部署和版本管理**问题,但不解决:
- 数据库迁移(需要顺序执行,不适合自动同步)
- 灰度发布(需要逐步 rollout,要配合argo-rollouts 或 Flagger)
- 紧急 hotfix(可以直接改集群,但之后必须补回到 Git)
**建议**:把 GitOps 当作基础设施管理的基础设施,而不是全部。复杂部署流程还是要配合专门的工具(如 argo-rollouts)。
## 上线后的巡检与防漂移纪律
前面讲的是「怎么装、怎么回滚」,真正拉开差距的是上线后这套持续盯防。我们这套 ArgoCD 管着十几个集群跑了一年多,靠下面几条纪律把「GitOps 自己先失效」这种尴尬挡在外面。
### 把 controller 自身挂进监控
最反直觉但最重要:GitOps 工具本身也要被监控,否则它静默挂掉时,你以为集群状态是被 Git 保证的,其实早就不 reconcile 了。我们给 ArgoCD/FluxCD 本身配了三类告警:① controller Pod 重启次数增量(`restartCount` 上涨说明 OOM 或 panic);② git pull 时延,某次拉取超过 5 分钟没完成就报;③ reconcile 失败率(ArgoCD 的 `argocd_app_sync_last_result`、FluxCD 的 `fluxcd_kustomization_last_succeeded_time` 超过 10 分钟没刷新)。这三条把「GitOps 不灵了」从「发现集群状态不对」前移到「controller 异动时就告警」。
### 漂移扫描常态化
`selfHeal` 会默默把手动改动改回来,但如果 controller 没跟上、或有人把某个字段加进了 `ignoreDifferences`,漂移就会悄悄累积。我们每周跑一次全量漂移扫描:ArgoCD 侧对每个 app 跑 `argocd app get --show-diff`,FluxCD 侧跑 `flux reconcile kustomization`,把**任何非零漂移**都记下来并指派认领——漂移出现本身就是「有人绕过 Git 改了集群」的信号,不查根因就会反复被自动改回去、反复出问题。
### 紧急 hotfix 的「先改后补」纪律
翻车最多人踩的是:生产着火时直接 `kubectl` 改了集群救急,完事忘了补回 Git,结果下一个 reconcile 周期改动被冲掉。我们的铁律是**热修必须双写**:一边 `kubectl` 救急,一边**同一时间**在 Git 里提一个 hotfix PR 并 fast-merge,让「集群实际状态」和「Git 期望状态」保持一致。事后必须复盘「这次热修有没有进 Git」,没进 Git 的热修等于没做,下个 reconcile 就回滚了。
### 巡检清单(每周)
- **controller 健康**:重启次数、git pull 时延、reconcile 成功率三条曲线。
- **漂移扫描**:全量 `--show-diff`,非零漂移逐条认领。
- **热修核对**:本周所有 `kubectl` 手动改动,逐一确认已补回 Git。
- **prune 演练**:抽查一次 `--dry-run` 的删除列表,确认保护性 `ignoreDifferences` 还在生效。
---
## 相关文章
- [Blackbox Exporter 探针配置实战:多协议探测 + SLO 设计 + K8s ServiceMonitor 集成](blackbox-exporter.md)
- [混沌工程 Chaos Engineering:主动韧性测试实战,从故障注入到生产演练](chaos-engineering.md)
- [DevSecOps 安全左移:CI/CD 集成扫描策略,从 SAST/DAST 到供应链安全完整指南](devsecops-security.md)
---
## Grafana 部署与仪表盘搭建:从数据源接入到变量联动的六步路径
URL: https://ops.jiunotes.top/monitor/grafana-dashboard.md
摘要: Grafana + Prometheus 部署六步走:Docker Compose 一起跑、admin/admin 首登改密、Prometheus 数据源配置、变量联动下拉、JSON 导入导出、告警联动。原创,含 3 个真实踩坑案例。
### Answer
Grafana 部署六步:Docker Compose(Grafana + Prometheus 一起跑)→ 首登 admin/admin 改密 → 配 Prometheus 数据源 → 建第一个 Dashboard → 变量联动($instance 下拉)→ JSON 导入导出。最容易翻车的是 Prometheus 数据源 URL 用 9090 不是 9090/api/v1,以及变量查询里 metric 名要加花括号。
### FAQ
Q: Grafana 默认账号密码?
A: admin / admin,首次登录强制改密。如果不改,每次容器重启都用 admin/admin,容易被扫。生产环境建议用 Grafana 内置的 service account 或 reverse proxy auth 做集成认证。
Q: Grafana 和 Prometheus 一起部署还是分开?
A: 小团队用 Docker Compose 一起部署最简单;K8s 集群里 Grafana 用 Helm 单独装,Prometheus 用 kube-prometheus-stack。分开部署的好处是独立扩缩容,代价是多一套配置。
Q: 变量查询怎么写?
A: Prometheus 数据源 → Variables → Type=Query → Query 写 `label_values({__name__="node_cpu_seconds_total"}, instance)`。metric 名要加花括号避免歧义,Prometheus 版本差异下不加可能查询失败。
Q: Dashboard 怎么批量复用给同事 / 多环境?
A: 导出 JSON Model 进 Git 做版本管理,多环境用 Grafana 的 library panel(共享面板)+ 环境变量注入,避免每套环境手抄一遍 JSON。生产推荐配 provisioning 目录自动加载,重启不丢。
### Full Content
# Grafana 部署与仪表盘搭建:从数据源接入到变量联动的六步路径
[Grafana](https://grafana.com/docs/) 是 [Prometheus](https://prometheus.io/docs/) 生态里最实用的可视化层,但装完 Grafana 只是开始——怎么把数据源接进来、怎么让仪表盘自动切换节点、怎么导出给同事复用,才是真正的活。这篇讲从零到能用的六步。
## 60 秒决策:三种装法谁该选谁
| 装法 | 适合场景 | 优点 | 坑 |
|---|---|---|---|
| **[Docker](https://docs.docker.com/) Compose** | 个人 / 小团队 | 简单、迁移方便 | 需要单独管卷 |
| **[K8s](https://kubernetes.io/docs/) + Helm** | 已有 K8s 集群 | 与集群服务对齐 | Helm Chart 版本更新慢 |
| **[systemd](https://www.freedesktop.org/software/systemd/man/latest/)** | 原生 [Linux](https://www.kernel.org/doc/html/latest/) 极简 | 无依赖 | 升级麻烦、要 root |
生产建议 Docker Compose 或 K8s + Helm。本文以 Docker Compose 为主讲。
## Step 1:Docker Compose 一起跑
```yaml
# docker-compose.yml
services:
prometheus:
image: prom/prometheus:v2.53.0
restart: unless-stopped
ports: ["9090:9090"]
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prom-data:/prometheus
command:
- --storage.tsdb.retention.time=15d
- --web.enable-lifecycle
grafana:
image: grafana/grafana:11.1.0
restart: unless-stopped
ports: ["3000:3000"]
environment:
- GF_SECURITY_ADMIN_USER=admin
- GF_SECURITY_ADMIN_PASSWORD=ChangeMe_2024
- GF_USERS_ALLOW_SIGN_UP=false
volumes:
- grafana-data:/var/lib/grafana
- ./grafana/provisioning:/etc/grafana/provisioning:ro
depends_on: [prometheus]
volumes:
prom-data:
grafana-data:
```
```bash
mkdir -p ~/grafana/{prometheus,grafana/provisioning/datasources}
cd ~/grafana && docker compose up -d
```
**你应该看到什么**:两个服务 `running`,`curl http://localhost:3000/` 返回 200。
## Step 2:首次初始化 + 改密码
浏览器打开 `http://:3000`:
```
Welcome to Grafana 11.1.0
Username: admin
Password: admin
```
**关键动作**:改密码。不改的话每次容器重启 Grafana 都用 admin/admin,容易被扫。
```bash
# 也可以改 compose 里的环境变量
sed -i 's/ChangeMe_2024/Your_New_Password/' docker-compose.yml
docker compose up -d --no-deps grafana
```
## Step 3:配 Prometheus 数据源
**方法一:UI 手动配**
Grafana → Connect → Data Sources → Add → Prometheus → URL: `http://prometheus:9090` → **Save & Test**。
**方法二:文件 provision(推荐生产用)**
```yaml
# grafana/provisioning/datasources/prometheus.yml
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
httpMethod: POST
manageAlerts: true
```
```bash
# 重启让 provision 生效
docker compose restart grafana
```
**踩坑记录**:URL 只写 `http://prometheus:9090`,不要加 `/api/v1`,也不要在末尾加斜杠。加了会 404 或返回 status codes 解析失败。
## Step 4:建第一个 Dashboard
Grafana → Explore → 添加 Panel → 写 PromQL → 保存。
```promql
# 每个节点 CPU 使用率
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# 内存使用率
100 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes * 100)
# 根分区磁盘使用率
100 - (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} * 100)
```
**你应该看到什么**:三条曲线,每个 instance 一条线。
## Step 5:变量联动(最有用的一步)
变量让一个 Dashboard 复用给多个节点。
- **变量名**:`instance`
- **类型**:Query
- **Prometheus 查询**:`label_values({__name__="node_cpu_seconds_total"}, instance)`
```yaml
# Dashboard JSON 中的变量片段
"templating": {
"list": [
{
"name": "instance",
"type": "query",
"datasource": "Prometheus",
"query": {
"query": "label_values({__name__=\"node_cpu_seconds_total\"}, instance)",
"refId": "PrometheusVariableQueryEditor-VariableQuery"
},
"multi": true,
"includeAll": true,
"allValue": ".*"
}
]
}
```
```promql
# Panel 里用变量筛选
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle", instance=~"$instance"}[5m])) * 100)
```
**关键坑**:metric 名要加花括号 `{}`。老版教程里省略花括号在 Prometheus 10.x 之前能用,但 11.x 更严格的语法解析下容易失败。这一点我也不完全确定所有 Prometheus 版本都强制要求,实测 2.53 不加能跑,但加上更稳。
## Step 6:JSON 导入导出
Dashboard 右上角菜单 → JSON Model → 复制/粘贴。
```bash
# 用 Grafana HTTP API 批量导入
curl -X POST http://localhost:3000/api/dashboards/db \
-H "Content-Type: application/json" \
-u admin: \
-d @dashboard.json
```
**你应该看到什么**:`{"folderId":1,"id":2,"slug":"node-overview","status":"success","url":"/d/2/node-overview","version":1}`。
## 3 个真实踩坑案例
**案例一:Prometheus 数据源 URL 拼错**
现象:Save & Test 报 `status codes should not be parsed as json` 或 `404`。
根因:URL 加了 `/api/v1` 或末尾多了斜杠。
修复:URL 只写 `http://prometheus:9090`。
**案例二:变量查询返回空**
现象:Dashboard 里变量下拉框空的,无法选。
根因:变量查询里 metric 名没加花括号,或 metric 名写错。
```yaml
# 错(Prometheus 11.x 可能失败)
"query": "label_values(node_cpu_seconds_total, instance)"
# 对(metric 加花括号)
"query": "label_values({__name__=\"node_cpu_seconds_total\"}, instance)"
```
**案例三:Dashboard JSON 导入 401**
现象:`curl` 导入 JSON 报 401 Unauthorized。
根因:Grafana 版本 10+ 默认禁用 API Token 匿名导入,要用 service account token 或 basic auth。
```bash
# 用 basic auth 替代
curl -u admin: -X POST http://localhost:3000/api/dashboards/db \
-H "Content-Type: application/json" \
-d @dashboard.json
```
**这里最容易翻车**:Grafana 版本升级会改 API 行为,10.x 和 11.x 的鉴权差异挺大。这一点我也不完全确定所有插件都跟上了新版本鉴权,实测有些老插件要降级。
## Dashboard 版本管理与 provisioning
手动导出的 JSON 进 Git 是底线,但团队大了还得靠 provisioning 自动化。要点:
- **provisioning 目录挂进去**:compose 里已把 `./grafana/provisioning` 挂到 `/etc/grafana/provisioning`,把 dashboard JSON 放进 `provisioning/dashboards/` 配一个 `dashboards.yml`(specify `path` + `provider`),容器重启 Grafana 自动加载,不丢。
- **JSON 进 Git 做 code review**:改 dashboard 走 PR,指标口径、告警阈值、变量定义都能被 review。谁改了 CPU 告警阈值一目了然,避免「某人悄悄把告警阈值放宽导致漏报」。
- **多环境复用**:用 Grafana library panel(共享面板)+ 环境变量注入(`GF_INSTALL_PLUGINS`、datasource name),同一套面板在生产 / 预发各挂各的数据源,不用每套环境手抄 JSON。
## 告警联动与「只看面板」的坑
仪表盘是给人看的,告警才是真兜底。两条经验:
- **面板上的阈值 ≠ 告警**:别把「我看面板红没红」当监控。面板挂了没人看,告警才推人。同一套指标既画进面板、也配进 Alertmanager 规则,口径一致。
- **面板要能下钻**:大盘用 `topk(10, ...)` 看最差的 10 个 instance,点进变量下拉选单节点看细节。变量联动(Step 5)就是为这个下钻服务的——没有变量的大盘只能看整体,排障寸步难行。
## 性能:几百条线的大盘别乱画
- **`by (instance)` 聚合控制线数**:一台面板几百条线时浏览器卡死,先 `topk` / `bottomk` 限 10 条。
- **查询窗口别开太宽**:`[30d]` 这种长窗口直接打爆 Prometheus 查询,仪表盘看 24h 足够,历史留给长查询单独面板。
- **`rate` 窗口匹配采集间隔**:默认 15s 采集用 `[5m]` 或 `[2m]`,窗口开成 `[1m]` 在抖动大时会出锯齿假峰。
- **refresh 频率别太密**:大盘 30s 刷新够用,10s 频繁刷新对 Prometheus 是实打实的查询压力。
## 日常巡检与容量规划
把上面这些沉淀成例行动作,仪表盘才长期好用:
- **每周看一次「最坏 10 个节点」**:大盘顶部的 `topk(10, 100 - idle%)` 面板扫一眼,长期居前的 instance 重点看是不是漏配了清理脚本、磁盘是不是在涨。
- **每季度重算容量**:看 `node_filesystem_size_bytes` 与增长趋势(`predict_linear`),提前预警磁盘写满;Grafana 自身的 `tsdb` 查询压力随面板数线性涨,面板数翻几倍前先把刷新间隔和查询窗口收紧。
- **仪表盘 JSON 也做备份**:provisioning 目录进 Git 是备份的一种,再定期 `curl /api/dashboards` 全量导出 JSON 归档到对象存储,防 provisioning 配置改坏导致面板全丢。
- **告警与面板口径对齐**:每季度核对一遍「面板上的阈值」和「Alertmanager 规则」是否一致,漂移了就统一改,避免「面板绿着、告警其实早该响了」。
## 多数据源混用(Prometheus + Zabbix)
基础设施走 Zabbix、服务走 Prometheus 的团队很常见,Grafana 可以把两套数据源挂一起,但有几个坑:
- **数据源要能分选**:同一套变量里 `instance` 标签可能两个数据源都有但含义不同,建变量时绑定到指定数据源(`datasource: Prometheus`),别让它跨源取。
- **时区与采集间隔不一致**:Zabbix 默认 60s 粒度、Prometheus 15s,画在同一面板时线会「一大一小」跳,要么分开放面板、要么 `rollup` 对齐粒度。
- **告警分开配**:Grafana 原生告警只管 Prometheus 系数据源,Zabbix 的告警留在 Zabbix 内部,两套告警口径要在值班 SOP 里写清楚「哪个告警看哪套面板」,别混。
## 收尾
Grafana 部署本身不难,难的是"从能用到好用"——数据源稳定、变量联动、JSON 复用。六步走下来,你的团队应该能有一个"每人一个 dashboard,共享一套变量"的可用状态。
**我的判断**:Docker Compose 一起跑最省心,但生产环境还是推荐 K8s + Helm。原因很简单——Grafana 10+ 的鉴权、企业授权、插件管理在 K8s 里更可控。小团队先用 Compose,规模上来再切。
---
## 相关文章
- [Prometheus 部署实战:Docker / systemd / K8s 三种方案 60 秒选型](prometheus-deploy.md)
- [PromQL 速查:5 类黄金指标 rate/irate/histogram_quantile 陷阱与 20 条可复制模板](prometheus-query.md)
- [Zabbix + Prometheus 混合监控架构:传统基础设施 + 云原生服务的双栈方案](zabbix-prometheus-hybrid.md)
---
## 监控与安全 · 全部 48 篇汇聚
URL: https://ops.jiunotes.top/monitor.md
摘要: 监控与安全栏目全部 48 篇文章按类型分组的汇聚页:同主题文章集中成一层,点子主题直达对应实操笔记,利于站内互链与检索。
### Full Content
# 监控与安全 · 全部 48 篇汇聚
本页把 **监控与安全** 栏目的 48 篇文章按「类型」聚到一层:同主题集中成小节,点标题直达对应实操笔记。用来快速定位某类问题,也方便在文章之间来回串读。
**从哪篇开始:** 新手建议先读 [Prometheus 部署实战:Docker / systemd / K8s 三种方案 60 秒选型](prometheus-deploy.md),再按下面的子主题挑需要的看。
## 排障决策树
- [Prometheus 装好却没数据、Targets 全红决策树:装完监控却没指标怎么查](monitor-prometheus-no-data.md) — >
- [Grafana 大盘空白或数据错位决策树:图拉出来是空的怎么查](monitor-grafana-blank.md) — >
- [告警风暴半夜轰炸决策树:Alertmanager 重复、分组失效、静默降噪怎么治](monitor-alert-storm.md) — >
- [Loki 日志查不到、查得慢、磁盘爆了决策树:logcli 查询为空怎么查](monitor-loki-missing.md) — >
- [主机三件套 CPU / 内存 / 磁盘IO 怎么看才不误判:指标解读决策树](monitor-host-signals.md) — >
- [室外 PoE 供电压降决策树:下雨天摄像头频繁重启怎么查](monitor-outdoor-poe-voltage-drop.md) — 室外监控典型故障——枪机/球机一到下雨天或晚上就频繁重启,画面大量雪花噪点。本文给出一张排障决策树:先确认是不是"供电不足导致的反复重启"而…
- [监控专网环路广播风暴决策树:一片摄像头集体掉线怎么查](monitor-switch-loop-broadcast-storm.md) — 监控专网典型故障——某区域(如地下车库)监控画面突然集体卡顿、延迟高、大面积掉线。本文给出一张排障决策树:先确认是不是"广播风暴把交换机 C…
## Prometheus 部署与运维
- [Prometheus 部署实战:Docker / systemd / K8s 三种方案 60 秒选型](prometheus-deploy.md) — Prometheus 部署三种方案对比:Docker、systemd、K8s 谁该选谁。最小配置 3 行 + node_exporter 接…
- [Helm 部署 Prometheus:kube-prometheus-stack 六步跑通 + 3 个 K8s 新手必踩坑](prometheus-helm.md) — Helm 部署 Prometheus 完整教程:kube-prometheus-stack 是什么、六步实操、ServiceMonitor …
- [Prometheus TSDB 深度运维:WAL/Head/Block 结构与 5 个真实故障](prometheus-tsdb-operations.md) — TSDB 目录解剖 + 三段式写入流程 + compaction 卡死/head OOM/retention 消失/WAL 恢复/block…
- [Prometheus 长期存储与多集群查询实战:Thanos 架构落地与踩坑复盘](prometheus-thanos-storage.md) — 一线运维视角用 Thanos 统一多套 Prometheus,历史数据落到 MinIO/S3,Sidecar/Query/Store/Com…
- [Prometheus Recording Rules 实战:预计算指标提升查询性能与降低告警延迟](prometheus-recording-rules.md) — Prometheus Recording Rules 配置指南:命名规范、分层设计、性能优化、常见 Pitfall。附生产级 rules.y…
## PromQL 与告警
- [PromQL 速查:5 类黄金指标 rate/irate/histogram_quantile 陷阱与 20 条可复制模板](prometheus-query.md) — PromQL 一页纸速查:CPU/内存/磁盘/网络/HTTP 5 类黄金指标查询、rate vs irate vs increase 陷阱、…
- [Alertmanager 告警规则配置:路由树 + Silence/Inhibit + 微信钉钉 Webhook 六坑指南](prometheus-alerting.md) — Prometheus Alertmanager 生产配置:三层路由树(P0/P1/P2)、Silence vs Inhibit 对比、微信/…
- [Alertmanager 告警降噪实战:抑制器 + 路由树 + 静默配置四步降噪法](alertmanager-noise-reduction.md) — 生产环境 Alertmanager 告警从每天几百条降到个位数:Inhibit 抑制器配置、P0/P1/P2 三级路由、维护静默、group…
## Grafana 与仪表盘
- [Grafana 部署与仪表盘搭建:从数据源接入到变量联动的六步路径](grafana-dashboard.md) — Grafana + Prometheus 部署六步走:Docker Compose 一起跑、admin/admin 首登改密、Prometh…
## 日志与追踪
- [Loki 日志聚合实战:单集群部署与日志管道优化](loki-log-aggregation.md) — 从 ELK 迁移 Loki 的真实成本账,Docker Compose 10 分钟起单集群,label 基数设计原则,LogQL 速查与 5…
- [OpenTelemetry 遥测标准:Trace/Metric/Log 统一采集,从 SDK 接入到后端对接全指南](opentelemetry-guide.md) — OpenTelemetry 一站式实现 Trace/Metric/Log 三支柱采集:SDK 接入(Go/Python/Java)、coll…
- [分布式追踪采样实战:从头采样到尾采样,把成本压下来又不丢异常](distributed-tracing-span-sampling.md) — 分布式追踪采样怎么做才不丢关键信息又控住成本?本文讲清头采样与尾采样的取舍、概率采样/限流采样/自适应采样/父级采样策略,附 OpenTel…
- [eBPF 可观测性原理:无侵入监控实战,从 kernel trace 到生产落地](ebpf-observability.md) — eBPF 原理与实战:kprobe/uprobe/ftrace 三种 attach 方式、常见性能影响、生产部署踩坑(内核版本限制、权限、B…
## 主机与数据库监控
- [node_exporter 指标缺失排查:6 大症状决策树 + 4 个常见翻车原因](node-exporter-troubleshoot.md) — node_exporter 指标缺失系统性排查:node_filesystem、node_cpu、node_memory、node_netw…
- [Linux 监控 CPU:top 一行 5 个百分比字段排障决策树](linux-cpu-monitor.md) — Linux CPU 监控深度解析:top 一行 %usr/%sys/%iowait/%steal/%irq 五个字段的排障决策树,mpsta…
- [Linux 磁盘 IO 监控实战:6 症状决策树 + iostat/iotop 判读 + 5 个真实事故](linux-disk-io-monitor.md) — 磁盘 IO 瓶颈是最易误诊的问题:load 飙高 CPU 却闲,八成是 iowait 作怪。本文给 vmstat/iostat/iotop/…
- [Linux 内存监控实战与 OOM 排障:free/vmstat/ps 字段解读 + cgroup v2 内存限制决策树](linux-memory-monitor.md) — 内存故障比 CPU 更隐蔽,OOM killer 无提示杀进程。本文从 free 五字段、vmstat 换页、cgroup v2 memor…
- [Windows 服务器监控实战:wmi_exporter + Prometheus + Grafana 完整落地链路 + 5 个真实故障](windows-server-monitoring.md) — Windows 监控在中文圈几乎一片空白,多数教程"装个 wmi_exporter"就没了。本文给完整落地链路:wmi_exporter M…
- [数据库监控实战:PostgreSQL/MySQL 生产监控四类故障决策树与 5 个真实事故复盘](database-monitoring-postgres-mysql.md) — 用 postgres_exporter + mysqld_exporter 监控数据库层的实战手册。四类故障决策树(连接池耗尽、锁与死锁、复…
## Kubernetes 与云原生
- [Kubernetes Pod 排障决策树:CrashLoopBackOff / ImagePullBackOff / Pending 五步定位法](kubernetes-pod-troubleshoot.md) — K8s 生产环境 Pod 常见问题排障:CrashLoopBackOff 根因分析、ImagePullBackOff 镜像拉取失败、Pend…
- [GitOps 基础设施管理:ArgoCD/FluxCD 声明式部署实战与选型决策树](gitops-infra.md) — GitOps 核心原理、ArgoCD vs FluxCD 选型对比、多集群管理、Rollback 策略、以及应用级回滚 vs 基础设施级回滚…
- [Platform Engineering 平台工程:IDP 内部开发者门户从 0 到 1 建设实战](platform-engineering.md) — Platform Engineering 核心理念与 IDP 建设路径:自我服务 API、golden path 模板、平台产品化思路、SL…
- [混沌工程 Chaos Engineering:主动韧性测试实战,从故障注入到生产演练](chaos-engineering.md) — 混沌工程核心理念与实战:故障注入工具选型(Chaos Mesh/Litmus)、实验设计方法论、生产环境安全注入、以及三次事故复盘(含一次失…
## 传统监控双栈
- [Zabbix 7 Docker 部署 + Prometheus 选型决策:什么时候该选哪个](zabbix-setup.md) — Zabbix 7.0 Docker Compose 一步部署 Server+Web+MySQL+Agent2,附选型决策树:Promethe…
- [Zabbix + Prometheus 混合监控架构:传统基础设施 + 云原生服务的双栈方案](zabbix-prometheus-hybrid.md) — 生产环境 Zabbix + Prometheus 双栈监控:Zabbix 管物理机/网络设备/SNMP,Prometheus 管 K8s/微…
## SLO / FinOps / 安全
- [SLO 与错误预算实战:把可靠性目标变成可执行的发布闸门](slo-definition-error-budget-policy.md) — SLO、错误预算、错误预算策略到底怎么定义和落地?本文给一套可操作的 SRE 链路:先厘清 SLI/SLO/SLA 三者关系,再讲怎么选用户…
- [FinOps 可观测性成本优化:智能采样与分层存储实战指南](finops-monitoring.md) — FinOps 可观测性落地:智能采样降成本、冷热分层存储、高基数指标治理、成本归因到团队/服务,附真实数据对比和采坑复盘。
- [DevSecOps 安全左移:CI/CD 集成扫描策略,从 SAST/DAST 到供应链安全完整指南](devsecops-security.md) — DevSecOps 落地实战:SAST/SCA/DAST 扫描集成、镜像安全扫描、密钥泄露检测、安全策略绕过处理、以及"安全阻塞流水线"和"…
- [堡垒机选型与 JumpServer 部署](bastion-jumpserver.md) — 自建 vs 商业堡垒机 TCO 分析、JumpServer 部署要点、开源堡垒机对比、审计与权限管理。
- [SSH 加固:密钥登录 + Fail2ban](ssh-hardening.md) — SSH 加固 Top 8:禁用 root 登录、密钥认证、Fail2ban 常见 jail、AllowUsers、sshd_config 常…
## 性能剖析与探针
- [持续性能剖析:eBPF + Pyroscope 落地指南,从采样分析到线上性能优化实战](continuous-profiling.md) — 持续性能剖析(Continuous Profiling)实战:Pyroscope 架构原理、eBPF 采样原理、CPU/内存热点分析、生产部…
- [Blackbox Exporter 探针配置实战:多协议探测 + SLO 设计 + K8s ServiceMonitor 集成](blackbox-exporter.md) — Prometheus Blackbox Exporter 生产配置实战:8 种协议模块(HTTP/TCP/UDP/gRPC/DNS/Ping…
## 其他 / 暂未分组
- [systemd-journald 日志排障决策树:/var 爆盘、查不到日志、Suppressed messages 三岔路](journald-disk-full-log-missing.md) — journald 把 /var 撑满、重启后查不到昨夜日志、关键报错被 Suppressed N messages 吞掉——三类故障共用一套…
- [PVE 升级后 Web GUI 打不开?pveproxy 排障决策树](proxmox-gui-not-starting-after-upgrade.md) — Proxmox VE 升级后 Web GUI 打不开的排障决策树:先用 pveversion、systemctl 与端口检查分清服务没起、端…
- [PVE 集群丢失 Quorum 怎么恢复?pvecm 决策树](proxmox-lost-quorum-recover.md) — Proxmox VE 集群失去 quorum、/etc/pve 变只读的恢复决策树:先看 pvecm status 的 Quorate 与 …
- [Proxmox 虚拟机出网不通决策树:Bridge vs NAT、vmbr0 选错口、VLAN tag 与 OVS 混用怎么分岔定位](pve-bridge-nat-stuck.md) — >
- [Proxmox 虚拟机迁移踩坑决策树:qm migrate 冷/热迁移、KVM↔VMware vmdk 格式互通、MAC/IP 漂移失联、存储不一致](pve-live-migration.md) — >
- [PVE 容器卡在 mounting rootfs?LXC 启动失败排查](pve-lxc-rootfs-mount-stuck.md) — Proxmox VE 的 LXC 容器卡在 mounting root filesystem、start failed 的完整排查:按 ro…
- [Proxmox 设备直通加固清单:IOMMU 没开、VFIO 绑定失败、GPU/网卡/USB 被宿主抢占逐条排查](pve-passthrough-iommu.md) — >
- [Proxmox 虚拟机慢在哪深度解析:CPU 超分、内存 ballooning、磁盘 IO 虚拟层逐层下钻](pve-perf-steal-ballooning.md) — >
- [Proxmox 快照与回滚深度解析:raw 与 qcow2 快照机制差异、快照链不合并、回滚丢盘与容量回收](pve-snapshot-rollback.md) — >
---
**其他栏目:** [网络与 DNS](../network/index.md) · [Home Assistant](../homeassistant/index.md) · [AI 运维智能化](../ai/index.md) · [故障复盘](../postmortems/index.md) · [运维小工具](../tools/index.md) · [参考速查](../reference/index.md)
---
## systemd-journald 日志排障决策树:/var 爆盘、查不到日志、Suppressed messages 三岔路
URL: https://ops.jiunotes.top/monitor/journald-disk-full-log-missing.md
摘要: journald 把 /var 撑满、重启后查不到昨夜日志、关键报错被 Suppressed N messages 吞掉——三类故障共用一套定位命令。本文按存储位置/磁盘限流/速率限流三岔路给决策树,配 3 个基于典型生产场景的复盘和可直接抄的命令。
### Answer
journald 故障先分三岔路:df -h 看 /var 是否爆盘,journalctl --disk-usage 看 journal 占比,超了用 --rotate 配合 --vacuum-time/--vacuum-size 清归档(vacuum 不删活跃文件);查不到日志先看 Storage= 与 /var/log/journal 是否存在,auto 模式下目录不存在即 volatile、日志只在内存、重启即丢;日志"变少"先看 Suppressed N messages 与速率限流,官方默认 30 秒 10000 条且按服务独立计数。治本靠 SystemMaxUse + SystemKeepFree + MaxRetentionSec 三层收敛,本地只留短期、集中日志交给 Loki。
### FAQ
Q: journalctl --vacuum-size=500M 之后磁盘还是满,为什么?
A: vacuum 只删归档文件,不动活跃文件,--disk-usage 又含活跃+归档两部分,清完仍超限属正常。要立刻腾空间,先 --rotate 把活跃文件转归档再 vacuum。
Q: 重启后昨天的日志全没了,是磁盘坏了吗?
A: 多半不是。Storage=auto 时 /var/log/journal 目录不存在就走 volatile,日志只写 /run/log/journal,重启清空。建目录后重启 systemd-journal-flush.service 才转持久。
Q: RateLimitBurst 默认值是 1000 吗?
A: 不是。journald.conf 官方手册写的是 30 秒内 10000 条,且按服务分别限流;老教程的 1000 是旧版本值。超限后同区间消息被丢弃,并生成 Suppressed 提示。
Q: 删了 /var/log/journal 下的文件,df 为什么没变化?
A: 文件被 journald 进程打开着,删除只解除目录项,空间要等文件描述符关闭才释放。用 --rotate 或重启 systemd-journald 让旧文件真正关闭。
Q: journalctl -b -1 是什么意思?
A: 看上一次启动的日志。负偏移从末尾倒数,-1 是上一次启动、-0 是最近一次;正整数从最早一次正数起。查重启前报错就用 -b -1。
### Full Content
# systemd-journald 日志排障决策树:/var 爆盘、查不到日志、Suppressed messages 三岔路
`/var` 使用率半夜飙到 100%,SSH 登不上、Nginx 返回 502,最后发现是 `/var/log/journal` 吃掉了十几个 G。另一种相反的场景更气人:故障刚过,你想 `journalctl -b -1` 复盘,却发现昨天的日志一行都没有。还有第三种:日志在,但出事那几分钟的关键报错莫名其妙消失了,只剩一行 `Suppressed 42831 messages`。
这三种看着毫不相干,根子都在 journald 的三个不同开关上:**日志写在哪里**(Storage / 目录)、**允许占多少磁盘**(SystemMaxUse 一族)、**每秒收多少条**(RateLimit 一族)。先分清是哪一岔,再动手,别一上来就 `rm -rf /var/log/journal/*`——那个动作在文件还被进程打开时根本不释放空间,还会把仅存的排障线索一起删掉。
这篇只讲 systemd-journald 本机日志这一层。日志聚合与检索看 [Loki 日志聚合与保留期](loki-log-aggregation.md),Loki 侧查不到日志看 [Loki 日志查不到/慢/爆盘](monitor-loki-missing.md),主机指标和磁盘 I/O 看 [Linux 磁盘 I/O 监控](linux-disk-io-monitor.md)。时间对不上导致日志时间戳错位,先按 [Linux 时间同步实战](../network/ntp-time-sync.md) 校准,否则下面的 `--since` 过滤会把你带偏。
## 1. 60 秒分诊:一条决策树
```
现象:磁盘满 / 日志查不到 / 日志变少
│
├─ df -h /var 使用率 ≥ 95% ?
│ ├─ 是 → journalctl --disk-usage 看 journal 占多少
│ │ ├─ journal 占大头 ────────────→ 路径 A:磁盘限流
│ │ └─ journal 很小 ──────────────→ 不是 journal,查别的大户
│ └─ 否 ↓
│
├─ journalctl -b -1 / --since 查不到预期日志 ?
│ ├─ 是 → 查 Storage= 与 /var/log/journal 是否存在
│ │ └─ volatile 或目录缺失 ───────→ 路径 B:存储位置
│ └─ 否 ↓
│
└─ 日志在但关键条目缺失、出现 Suppressed N messages ?
└─ 是 ──────────────────────────────→ 路径 C:速率限流
```
三条路径可以叠加:磁盘快满时,journald 会按剩余空间**再乘一个系数收紧限流**(剩余 ≤1MB 时系数为 1,≤16MB 为 2,≤256MB 为 3,≤4GB 为 4,≤64GB 为 5,≤1TB 为 6),所以爆盘往往同时引发"日志变少"。先解磁盘,再看限流。
## 2. 路径 A:`/var` 被 journal 撑满
### 2.1 先定位,别猜
```bash
df -h /var # 使用率与挂载点
journalctl --disk-usage # journal 自身占用(含活跃+归档文件)
du -sh /var/log/journal/* 2>/dev/null # 按 machine-id 分目录看
find /var/log/journal -type f -name '*.journal*' -printf '%s %p\n' | sort -rn | head
```
journald 和 `journalctl` 只认以 `.journal` 或 `.journal~` 结尾的文件,其他文件不计入占用统计。所以目录里躺着一个 3GB 的 `.log` 临时文件跟 journald 没关系,别算在它头上。
### 2.2 止血:先 rotate 再 vacuum
```bash
sudo journalctl --rotate # 活跃文件转归档
sudo journalctl --vacuum-time=7d --vacuum-size=1G # 按时间+大小双限清理归档
sudo journalctl --disk-usage # 复查
```
这里有个几乎人人踩过的坑:`--vacuum-size=` / `--vacuum-time=` / `--vacuum-files=` **只删归档文件,不删活跃文件**,而 `--disk-usage` 把活跃文件算在里面。所以执行完发现占用没降到 1G 以下是正常的——活跃文件还在写。把三个参数写进同一条命令可以同时生效;想连活跃文件一起转掉,就先 `--rotate`,或者把 `--rotate` 和 vacuum 参数合并在一条命令里。
还有个反直觉的现象:直接 `rm` 掉 journal 文件后 `df` 没变化。文件被 journald 用文件描述符打开着,删除只解除目录项,空间要等描述符关闭才真正释放。`--rotate` 或 `systemctl restart systemd-journald` 能让它关掉旧文件。
### 2.3 治本:三层收敛
第一层,在 `/etc/systemd/journald.conf.d/10-retention.conf` 设上限(不要直接改主配置,drop-in 可随配置管理分发):
```ini
[Journal]
SystemMaxUse=2G
SystemKeepFree=10%
MaxRetentionSec=1month
SystemMaxFileSize=128M
```
`SystemMaxUse=` 是硬顶,`SystemKeepFree=` 是给系统留的余量,两者取**较小值**。官方默认分别是文件系统的 10% 和 15%,且各自封顶 4G。`MaxRetentionSec=` 默认 0(不按时间清理),设成 `1month` 才真正落实保留期。`SystemMaxFileSize=` 默认等于 `SystemMaxUse=` 的八分之一、封顶 128M,这样通常能留 7 个轮转文件当历史。
第二层,确认配置真生效——`SystemMaxUse=` 只对**持久存储**(`/var/log/journal` 存在且可写)起作用;如果走的是 volatile,要改的是 `RuntimeMaxUse=` 一族。改完 `systemctl restart systemd-journald`,用 `journalctl --disk-usage` 观察几天。
第三层,本地日志只留短期,长期留存交给 [Loki 日志聚合与保留期](loki-log-aggregation.md) 或 rsyslog 转发。本地 journal 的价值是"机器还能登上去时能看到刚才发生了什么",不是当归档库。
## 3. 路径 B:重启后查不到日志
### 3.1 先搞清 journald 把日志写哪儿了
`Storage=` 有四个取值,行为完全不同:
| 取值 | 写入位置 | 重启后 |
|------|----------|--------|
| `volatile` | 仅 `/run/log/journal`(内存文件系统) | 清空 |
| `persistent` | 优先 `/var/log/journal`,早期启动或磁盘不可写时回退 `/run/log/journal` | 保留 |
| `auto` | `/var/log/journal` **目录存在**则持久,否则 volatile | 视目录是否存在 |
| `none` | 不存任何日志(仍可转发到控制台/syslog) | 无本地日志 |
默认值为 `persistent`。`auto` 那个"目录存在与否决定模式"的机制是排障关键:很多清理脚本把 `/var/log/journal` 整个删掉,重启后 Storage=auto 的机器就静默退回 volatile,日志只留内存,一断电全没——**配置一行没改,行为完全变了**。
还有个容易被忽略的细节:journald 启动时总是先用 volatile,直到 `journalctl --flush` 或收到 `SIGUSR1` 才切到持久存储,这一步由 `systemd-journal-flush.service` 在开机时自动完成。如果这个服务被禁用或失败,即使 `/var/log/journal` 在、Storage=persistent,日志也可能一直留在内存里。
### 3.2 定位命令
```bash
grep -i '^Storage' /etc/systemd/journald.conf /etc/systemd/journald.conf.d/*.conf 2>/dev/null
ls -ld /var/log/journal /run/log/journal 2>&1
systemctl status systemd-journal-flush.service
journalctl -b -1 # 上一次启动
journalctl -b -1 -u nginx.service -p err # 上一次启动 + 单元 + 错误级
journalctl --since '2026-12-03 20:00' --until '2026-12-03 23:00'
journalctl -o short-full -u ssh.service | head # 显示完整日期/时区
```
`-b -1` 的偏移规则:小于等于 0 从末尾倒数(`-0` 最近一次、`-1` 上一次),正整数从最早一次启动正数。空参数 `-b` 等于当前启动。`-p err` 显示 err 及更严重的级别(0 emerg 到 7 debug,指定单级别时包含更重要的)。`-o short-full` 输出带星期、年份、时区的完整时间,跨时区核对时比默认 `short` 可靠。
查不到日志时还要排除两类"假丢失":一是权限,普通用户只能读自己的日志和部分系统日志,需要 `sudo` 或加入 `systemd-journal` 组;二是时间戳,机器时间不准时 `--since` 会把你导向错误的时间段,先按 [Linux 时间同步实战](../network/ntp-time-sync.md) 确认时钟。
### 3.3 恢复持久存储
```bash
sudo mkdir -p /var/log/journal
sudo systemd-tmpfiles --create --prefix /var/log/journal
sudo systemctl restart systemd-journald systemd-journal-flush.service
journalctl --flush # 把内存里的日志搬到磁盘
journalctl --disk-usage
```
改 `Storage=` 后要重启 journald 才生效;只是补建目录的情况,重跑 flush 就能把当前内存日志落盘。
## 4. 路径 C:日志"变少"与 Suppressed messages
### 4.1 限流不是传说,默认值比想象中大
`RateLimitIntervalSec=` 和 `RateLimitBurst=` 控制每个服务的日志速率:在一个时间窗内超过条数上限,该服务本窗口剩余消息全部丢弃,并生成一条说明丢了多少条的 `Suppressed N messages`。**限流按服务独立计算**,两个服务不会互相挤占额度。官方默认值是 **30 秒内 10000 条**——很多中文教程写成 1000 条,那是旧版本的值,拿它当现在的基线会误判。
把任一值设为 0 可关闭限流,但生产上不建议全面关:一个陷入死循环的应用每秒刷几千条,能在几分钟内把磁盘吃完。正确做法是修应用的重试退避,而不是让日志管道无限敞开。
### 4.2 三条排查线索
```bash
journalctl -p err --since '1 hour ago' | grep -i suppressed
journalctl -o verbose -u your-app.service --since '1 hour ago' | head -40
grep -iE 'RateLimit|MaxLevelStore|ForwardToConsole' /etc/systemd/journald.conf /etc/systemd/journald.conf.d/*.conf 2>/dev/null
```
- `MaxLevelStore=` 默认是 `debug`,所有级别都入库;如果有人设成 `info`,debug 日志直接不写盘,看起来就像"日志少了"。
- `ForwardToConsole=yes` 在云主机上要当心:官方手册明确警告,云环境串口常常很慢,journald 同步转发到挂死的控制台会阻塞自己,连带着同步写 journal 的服务一起卡住。调试用 `journalctl -f` 重定向到文件,比长期开 `ForwardToConsole=yes` 安全。
- 磁盘剩余空间会收紧实际限流阈值,见第 1 节的系数表。所以"磁盘满"和"日志被限流消失"经常是同一个根因的两张脸。
## 5. 三个基于典型生产场景的复盘
### 场景一(基于典型生产场景):`/var` 100% 满,SSH 登不上、Nginx 502
**现象**:监控显示 `/var` 从 60% 两小时内涨到 100%,Nginx 上游超时,SSH 登录卡在认证阶段。
**根因**:一个 Python 服务开启了 debug 日志,每分钟写约 9MB,journal 单目录涨到 9.2G;`SystemMaxUse=` 从未设置,走默认 10%,而该分区挂载方式让默认值算出来偏大,迟迟没触发清理。
**修法**:先进单用户或挂救援盘腾出 200MB(`journalctl --rotate` + `--vacuum-time=1d`),恢复 SSH 后加 drop-in 设 `SystemMaxUse=2G`、`SystemKeepFree=10%`,同时把该服务的日志级别从 debug 调回 info。**教训**:磁盘告警阈值设 80% 不够,journal 增长是指数级的,应对 `/var/log/journal` 单独设用量告警。
### 场景二(基于典型生产场景):重启后昨夜故障日志全部消失
**现象**:一台机器凌晨重启,白天复盘发现昨夜服务崩溃的日志一条都没有,`journalctl -b -1` 只显示一条空启动记录。
**根因**:Storage=auto,而一台清理脚本每周删一次 `/var/log/journal`。目录被删后 auto 静默退回 volatile,日志只写 `/run/log/journal`,重启即清空。配置从未改过,行为却变了。
**修法**:`mkdir -p /var/log/journal` + `systemd-tmpfiles --create --prefix /var/log/journal`,把 Storage 显式写成 `persistent`(不要依赖 auto 的目录探测),修清理脚本改为 `journalctl --vacuum-time=14d` 而不是删目录,最后 `journalctl --flush` 验证。改进后同月又一次重启,`-b -1` 日志完整。相关主机指标异常可对照 [Linux 磁盘 I/O 监控](linux-disk-io-monitor.md) 交叉验证。
### 场景三(基于典型生产场景):关键 500 报错被刷没了
**现象**:一次下游接口故障中,应用每秒刷约 500 条 `connection refused`,事后查 journal 只看到海量重复行和用户侧超时的 500,真正定位根因的那几条错误不在了,只留一行 `Suppressed 42831 messages`。
**根因**:默认 30 秒 10000 条被瞬间打满,同一服务本窗口剩余消息被丢弃;当时磁盘只剩 8MB,限流系数降到 1,实际阈值仅 10000 条/30 秒。关键报错恰好落在被丢弃的区间里。
**修法**:短期把该服务的 `RateLimitBurst=` 提到 20000 并确认磁盘余量;长期给 HTTP 客户端加指数退避和重试上限,把重复错误压到每秒个位数,同时用 `journalctl -p err` 过滤级别看关键错误。第三个动作是把长期日志送 [Loki 日志聚合与保留期](loki-log-aggregation.md),避免本地窗口被刷爆后无处可查。
## 6. 速查 Cheat Sheet
```bash
# 磁盘与占用
df -h /var
journalctl --disk-usage
journalctl --rotate --vacuum-time=7d --vacuum-size=1G
# 存储模式与落盘
grep -i '^Storage' /etc/systemd/journald.conf /etc/systemd/journald.conf.d/*.conf 2>/dev/null
ls -ld /var/log/journal /run/log/journal
systemctl status systemd-journal-flush.service
journalctl --flush
# 查日志
journalctl -b -1 -u nginx.service -p err
journalctl --since '2026-12-04 02:00' --until '2026-12-04 04:00' -o short-full
journalctl -o verbose -u your-app.service | head -40
journalctl -p err --since '1 hour ago' | grep -i suppressed
# 配置生效
systemctl restart systemd-journald
systemctl cat systemd-journald | head
```
**一句话决策**:
- 磁盘满 → 先 `--rotate` 再 `--vacuum-*`;只删归档不删活跃,`rm` 不释放已打开的文件
- 查不到 → 看 `Storage=` 和 `/var/log/journal` 目录;auto + 目录缺失 = volatile = 重启即丢
- 日志少 → 看 `Suppressed N messages` 和 `MaxLevelStore=`;默认限流是 30 秒 10000 条,且随磁盘余量收紧
## 7. 误判速查表
| 现象 | 常见误判 | 实际先查 |
|------|----------|----------|
| `df` 100% 但 journal 占用很小 | journald 的锅 | 查别的大户,`journalctl --disk-usage` 只统计 `.journal*` 文件 |
| vacuum 后占用没降 | vacuum 失效 | 活跃文件不算归档,先 `--rotate` |
| `rm` 后空间没释放 | 文件系统故障 | 文件描述符仍被打开,重启 journald |
| 重启后无日志 | 磁盘坏 | Storage=auto + 目录缺失,或 flush 服务没跑 |
| 日志缺关键条目 | 应用没打日志 | `Suppressed N messages`,限流按服务独立计数 |
| `--since` 查不到 | 日志丢了 | 先核系统时钟,见 [Linux 时间同步实战](../network/ntp-time-sync.md) |
## 8. FAQ
### Q1:`journalctl --vacuum-size=500M` 之后磁盘还是满,为什么?
vacuum 只删归档文件,不动活跃文件,而 `--disk-usage` 含活跃+归档两部分,清完仍超限属正常。要立刻腾空间,先 `--rotate` 把活跃文件转归档再 vacuum。
### Q2:重启后昨天的日志全没了,是磁盘坏了吗?
多半不是。Storage=auto 时 `/var/log/journal` 目录不存在就走 volatile,日志只写 `/run/log/journal`,重启清空。建目录后重启 `systemd-journal-flush.service` 才转持久。
### Q3:RateLimitBurst 默认值是 1000 吗?
不是。journald.conf 官方手册写的是 30 秒内 10000 条,且按服务分别限流;老教程的 1000 是旧版本值。超限后同区间消息被丢弃,并生成 Suppressed 提示。
### Q4:删了 `/var/log/journal` 下的文件,`df` 为什么没变化?
文件被 journald 进程打开着,删除只解除目录项,空间要等文件描述符关闭才释放。用 `--rotate` 或重启 `systemd-journald` 让旧文件真正关闭。
### Q5:`journalctl -b -1` 是什么意思?
看上一次启动的日志。负偏移从末尾倒数,`-1` 是上一次启动、`-0` 是最近一次;正整数从最早一次正数起。查重启前报错就用 `-b -1`。
## 9. 关联阅读
- [Loki 日志聚合与保留期](loki-log-aggregation.md) — 本地只留短期,长期日志集中检索
- [Loki 日志查不到/慢/爆盘](monitor-loki-missing.md) — 聚合侧断流、保留期与索引断点
- [Linux 磁盘 I/O 监控](linux-disk-io-monitor.md) — 区分 journal 增长与真实磁盘 I/O 瓶颈
- [Linux 时间同步实战](../network/ntp-time-sync.md) — 时钟准了,`--since` 过滤才靠得住
## 10. 权威参考
- [journald.conf(5) — Storage / SystemMaxUse / RateLimit 官方定义](https://www.freedesktop.org/software/systemd/man/latest/journald.conf.html)
- [journalctl(1) — --vacuum / --rotate / -b / -o 官方手册](https://www.freedesktop.org/software/systemd/man/latest/journalctl.html)
- [systemd-journald.service(8) — 日志服务行为与信号处理](https://www.freedesktop.org/software/systemd/man/latest/systemd-journald.service.html)
---
## Kubernetes Pod 排障决策树:CrashLoopBackOff / ImagePullBackOff / Pending 五步定位法
URL: https://ops.jiunotes.top/monitor/kubernetes-pod-troubleshoot.md
摘要: K8s 生产环境 Pod 常见问题排障:CrashLoopBackOff 根因分析、ImagePullBackOff 镜像拉取失败、Pending 调度失败、OOMKilled 内存超限、Service 不可达。附 kubectl 诊断命令速查表和六个翻车案例。
### Answer
K8s Pod 排障核心是"分层定位":先看 Events 看调度问题,再看 Logs 看应用崩溃,最后看 Describe 看资源限制。
五个最常见状态:CrashLoopBackOff(应用崩了)、ImagePullBackOff(镜像拉不到)、Pending(调度不上)、OOMKilled(内存超了)、ContainerCreating(启动中卡住)。
kubectl describe pod 和 kubectl logs --previous 是最快定位工具。
### FAQ
Q: Pod 一直 CrashLoopBackOff 怎么办?
A: 三步:① `kubectl logs --previous` 看上一次崩溃的日志;② `kubectl describe pod` 看 Events 里有没有 OOMKilled 或 Exit Code;③ 检查环境变量、ConfigMap、Secret 是否配置正确。
最常见原因:应用启动命令写错、缺少必要环境变量、资源 limit 设太小导致 OOM。
Q: ImagePullBackOff 和 ErrImagePull 有什么区别?
A: ImagePullBackOff 是"重试拉取中",ErrImagePull 是"最后一次拉取失败"。
前者通常是网络问题或镜像仓库限流(Docker Hub 未登录每分钟 100 次),后者通常是镜像名/标签写错或私有仓库认证失败。
修复:检查 image name 拼写,私仓加 imagePullSecrets,国内用镜像加速器。
Q: Pod 一直 Pending 怎么排查?
A: `kubectl describe pod` 看 Events,常见原因三选一:① 资源不足(Insufficient cpu/memory)→ 扩节点或减 request;
② NodeSelector/Affinity 不匹配 → 检查 label;③ PVC 未绑定 → 检查 StorageClass 和 PV 是否存在。
Q: OOMKilled 后怎么调内存 limit?
A: 先看应用实际峰值:`kubectl top pod` 看当前 usage,然后 limit 设成峰值的 1.5 倍。
Java 应用特别注意:Xmx 要小于 container limit,否则 JVM 还没启动就被 OOM Kill 了。
长期方案:Profile 内存泄漏,而不是盲目加 limit。
Q: kubectl 命令怎么快速诊断 Pod 问题?
A: 五步法:① `kubectl get pods` 看状态;② `kubectl describe pod ` 看 Events;
③ `kubectl logs ` 看应用日志;④ `kubectl logs --previous` 看上一次崩溃日志;
⑤ `kubectl exec -it -- sh` 进容器调试。这五步覆盖 90% 的问题。
### Full Content
# Kubernetes Pod 排障决策树:CrashLoopBackOff / ImagePullBackOff / Pending 五步定位法
生产环境凌晨 2 点收到 [K8s](https://kubernetes.io/docs/) Pod CrashLoopBackOff 告警,这种场景每个运维都经历过。问题不是"怎么重启",而是"为什么崩"。这篇把 K8s Pod 最常见的五种故障状态拆解清楚,给你一个五步定位法,下次遇到不再慌。
## 五种最常见 Pod 状态
| 状态 | 含义 | 最常见原因 |
|---|---|---|
| `CrashLoopBackOff` | 容器反复崩溃重启 | 应用代码异常、环境变量缺失、资源不足 OOM |
| `ImagePullBackOff` | 拉取镜像重试中 | 镜像名错误、私有仓库认证失败、网络问题 |
| `Pending` | 调度器无法分配节点 | 资源不足、NodeSelector 不匹配、PVC 未绑定 |
| `OOMKilled` | 内存超限被杀 | limit 设太小、内存泄漏 |
| `ContainerCreating` | 启动中卡住 | 挂载卷权限、镜像拉取慢、Init Container 失败 |
下面按这个顺序排查。
## 第一步:看 Events —— 调度问题先看这里
```bash
kubectl describe pod -n
```
重点看底部的 **Events** 区域:
```
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning Failed 2m default-scheduler 0/3 nodes are available: 3 Insufficient memory.
Warning FailedMount 1m mounter Unable to attach or mount volumes: pvc-xxx not found
```
**常见 Events 解读**:
- `Insufficient memory/cpu` → 节点资源不够,扩集群或减小 request
- `FailedScheduling` → NodeSelector/Affinity 不匹配,检查 label
- `FailedMount` → PVC 未绑定,检查 StorageClass 和 PV
- `Back-off pulling image` → 镜像拉取失败,检查网络和认证
## 第二步:看 Logs —— 应用崩溃先看日志
```bash
# 当前运行容器的日志
kubectl logs -n
# 上一次崩溃容器的日志(CrashLoopBackOff 必备)
kubectl logs -n --previous
# 多容器 Pod 指定容器
kubectl logs -c -n