Subscribe
EC2

An nginx TCP proxy to RDS on a bastion died after unattended-upgrades

An nginx stream proxy to RDS stopped for two days after unattended-upgrades restarted it and systemd-resolved in the same second. Why nginx stayed down, the systemd drop-in that fixed it, and runtime DNS plus a TCP alarm.

An nginx TCP proxy to RDS on a bastion died after unattended-upgrades

On 4 November at 06:08 UTC, nginx on our production bastion stopped. Nobody noticed for two days. The bastion's only job is to forward port 5432 to a private RDS Postgres instance, so operators and a dashboard tool can reach the database, and for two days that forward simply wasn't there.

Ten days later the same thing happened on the second bastion. That one sat dead for four days.

In this blog we will look at what actually killed it, why nginx didn't come back on its own, the small systemd drop-in that fixed it, and two things I would add on top so it can't fail silently again.

The setup

The bastion is a plain Ubuntu 24.04 EC2 instance. nginx is installed from the Ubuntu archive (1.24 on noble) and it doesn't serve any HTTP at all. It uses the stream {} module, which proxies raw TCP:

events {}

stream {
    server {
        listen 5432;
        proxy_pass mydb.abcdefghijkl.ap-south-1.rds.amazonaws.com:5432;
        proxy_connect_timeout 5s;
    }
}

The security group allows 5432 only from a short list of sources. Clients connect to the bastion, nginx opens a TCP connection to the RDS endpoint and copies bytes both ways. Postgres TLS goes straight through, nginx never sees the password.

It's not glamorous. It had worked since months without anyone touching it, which is exactly why nobody was watching it.

What happened at 06:08

The first thing I looked at was systemctl status nginx. It said failed, and the journal told the rest of the story:

journalctl -u nginx --since "2026-11-04 06:00" --until "2026-11-04 06:15"
journalctl -u unattended-upgrades --since "2026-11-04"
grep -h "Packages that will be upgraded" /var/log/unattended-upgrades/unattended-upgrades.log

unattended-upgrades had installed security updates for libpcre2 and some bind9 libraries. On Ubuntu 24.04, needrestart then restarts every service that has an old copy of an upgraded library mapped. That change came in noble: before, the non-interactive run only listed the services, now it restarts them (the Ubuntu Discourse post about it). nginx uses pcre2. systemd-resolved uses the bind9 bits. So both got restarted, in the same second.

See, here is the problem. nginx resolves a hostname in proxy_pass once, at startup. While it was starting, systemd-resolved was also restarting, so the lookup for the RDS endpoint failed:

nginx: [emerg] host not found in upstream "mydb.abcdefghijkl.ap-south-1.rds.amazonaws.com" in /etc/nginx/nginx.conf:6
nginx: configuration file /etc/nginx/nginx.conf test failed

An [emerg] at startup means nginx exits. And the stock nginx unit on Ubuntu has no Restart= line, which means systemd's default of Restart=no. So it failed once and systemd just left it there. A few seconds later DNS was fine again, there was nobody to start nginx.

I wanted to be sure about the startup behaviour, so while writing this I ran nginx -t in a throwaway nginx:1.24-alpine container with that config. The container can't resolve the made-up hostname, and I got exactly the same host not found in upstream line and test failed. Same failure, no AWS needed to reproduce it.

Why nobody noticed

Two days is quite long. But think about who uses this forward: a couple of people running ad-hoc queries, and a dashboard tool that refreshes on its own schedule. When the query fails, a person assumes their own VPN or laptop is the problem. The dashboard showed stale numbers, which honestly looks the same as fresh numbers most of the time.

There was no alarm on the forward at all. EC2 status checks were green the whole time, because the instance was perfectly healthy. Only one process was missing.

On the second bastion it went the same way on 14 November at 06:18 UTC, and it was found on the 18th. That one hurt a bit more, because by then we knew the cause and had fixed only the first box.

The fix: let systemd restart it

The smallest fix is a drop-in for the nginx unit. You don't edit /lib/systemd/system/nginx.service (a package upgrade overwrites it), you add a file next to it:

sudo mkdir -p /etc/systemd/system/nginx.service.d
sudo tee /etc/systemd/system/nginx.service.d/restart.conf >/dev/null <<'EOF'
[Unit]
StartLimitIntervalSec=0

[Service]
Restart=on-failure
RestartSec=5s
EOF
sudo systemctl daemon-reload
systemctl show nginx -p Restart -p RestartUSec -p StartLimitIntervalUSec

Restart=on-failure covers a non-zero exit, a crash and a kill by signal. RestartSec=5s waits a bit between tries, so a DNS blip of a few seconds is over by the second attempt. StartLimitIntervalSec=0 turns off the start rate limit; without it, systemd gives up after 5 starts in 10 seconds and you are back to a dead unit. That last one lives in the [Unit] section since systemd 229, so the drop-in needs both sections. Easy to miss when you copy the three lines from a chat message.

Then test it the rude way:

sudo systemctl kill -s KILL nginx
sleep 6
systemctl is-active nginx

On the second bastion it was back in 5 seconds, which is the RestartSec. That is the test I'd actually trust. A clean systemctl stop doesn't count as a failure, so it proves nothing here.

Better: don't resolve only at startup

The drop-in makes nginx retry. It doesn't change the fact that nginx needs DNS to start at all, and it also keeps the old IP forever once it has started. RDS endpoints are DNS names for a reason: after a Multi-AZ failover the name points somewhere else. A proxy that resolved once at boot keeps sending traffic to the old address until someone restarts it.

The stream module can resolve at runtime if proxy_pass uses a variable and you give it a resolver:

events {}

stream {
    # Amazon's DNS inside the VPC, not the local systemd-resolved stub
    resolver 169.254.169.253 valid=30s ipv6=off;
    resolver_timeout 5s;

    server {
        listen 5432;
        set $rds mydb.abcdefghijkl.ap-south-1.rds.amazonaws.com;
        proxy_pass $rds:5432;
        proxy_connect_timeout 5s;
    }
}

169.254.169.253 is the Amazon-provided DNS address that every Nitro instance can reach, so it doesn't depend on systemd-resolved being up. The set directive in the stream module needs nginx 1.19.3 or newer, which 1.24 on Ubuntu 24.04 is. valid=30s makes nginx look the name up again every 30 seconds, so a failover gets picked up quickly.

With this config nginx -t passed in the same container where the static one failed, because nothing is resolved at load time any more. If DNS is down when a client connects, that one connection fails and the next one works. Much better than the whole process being gone.

I'd still keep the drop-in. They solve different things.

Make the box remember the fix

Here's the part I'm not proud of. Why did it take two outages? The drop-in went in by hand, over a shell on each bastion. It isn't in the AMI and it isn't in Terraform, so a rebuilt bastion would come up exactly as fragile as before. If you have the same setup, put it in user data:

#!/bin/bash
set -euo pipefail
apt-get update
apt-get install -y nginx
install -d /etc/systemd/system/nginx.service.d
printf '[Unit]\nStartLimitIntervalSec=0\n\n[Service]\nRestart=on-failure\nRestartSec=5s\n' \
  > /etc/systemd/system/nginx.service.d/restart.conf
systemctl daemon-reload
systemctl enable --now nginx

While I was on the box I also saw the root disk at 84%. Not related to this outage, but a full disk is the next thing that stops nginx, so it went on the list.

An alarm that would have caught it in 5 minutes

The real failure was two days of silence. A tiny check on the bastion itself pushes a 1 or 0 to CloudWatch every minute:

#!/bin/bash
# /usr/local/bin/db-forward-check.sh
# Pushes 1 if the local 5432 forward accepts a TCP connection, else 0.
set -u
up=0
if timeout 3 bash -c '</dev/tcp/127.0.0.1/5432' 2>/dev/null; then
  up=1
fi
aws cloudwatch put-metric-data \
  --namespace Bastion \
  --metric-name DbForwardUp \
  --dimensions Host="$(hostname)" \
  --value "$up"

Connecting to 127.0.0.1:5432 only proves nginx is listening; RDS could still be down behind it. For this failure that's enough, because nginx being gone was the whole problem. Run it from a systemd timer:

# /etc/systemd/system/db-forward-check.timer
[Unit]
Description=Run db-forward-check every minute

[Timer]
OnBootSec=2min
OnUnitActiveSec=1min

[Install]
WantedBy=timers.target

The matching db-forward-check.service is a Type=oneshot unit whose ExecStart is the script. The instance role needs cloudwatch:PutMetricData. Then the alarm:

aws cloudwatch put-metric-alarm \
  --alarm-name bastion-db-forward-down \
  --namespace Bastion --metric-name DbForwardUp \
  --dimensions Name=Host,Value=bastion-1 \
  --statistic Maximum --period 60 --evaluation-periods 5 \
  --threshold 1 --comparison-operator LessThanThreshold \
  --treat-missing-data breaching \
  --alarm-actions arn:aws:sns:ap-south-1:111122223333:ops-alerts

--treat-missing-data breaching matters. If the whole instance dies, the script stops sending anything, and missing data should page you as well.

If you would rather not run a bastion at all, SSM port forwarding to RDS removes this whole class of problem; I use SSM instead of SSH on my own blog host, written up in Running a Docker host on EC2 with SSM instead of SSH. For a dashboard tool that needs a fixed address to connect to, though, a small proxy is still the easy answer. Just give it a restart policy and an alarm.