Linux and servers · Intermediate · 15 min
Tune Linux kernel parameters with sysctl
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · procps 4.0.4 · systemd 259
You will read kernel parameters from /proc/sys, find which file sets each one, change a value for one boot and then for good in an /etc/sysctl.d drop-in, apply the hardening keys Lynis checks, and measure whether each change helped.
On this page
The Linux kernel exposes a few thousand settings at run time: how eagerly it swaps, how many connections can wait for a server to accept them, how many files a user can watch for changes, whether it trusts ICMP redirects. sysctl is the tool that reads and writes them, and files in /etc/sysctl.d/ make your changes survive a reboot.
These settings are also where copied advice does the most quiet damage. A "high performance sysctl.conf" pasted from a forum can lower a limit Ubuntu already raised, name keys that no longer exist, or turn off a protection, and nothing complains until something breaks months later. So this tutorial treats every change the same way: read the current value, find out which file set it, measure the problem, change one thing, and measure again.
You will keep one useful result, a small hardening drop-in for the keys Lynis reports, and you will know how to back out any change.
Step 1 · Read kernel parameters from /proc/sys
Every parameter is a small file under /proc/sys. The path and the sysctl name are the same thing written two ways: slashes become dots.
ls /proc/sys
cat /proc/sys/vm/swappiness
sysctl vm.swappiness
sysctl -n net.core.somaxconnls shows the top-level groups: fs (filesystems), kernel, net (networking), vm (memory) and a few more. sysctl vm.swappiness reads /proc/sys/vm/swappiness and prints it as name = value; -n prints only the value, which is handy in scripts.
Before you change anything, save every current value to a file. You will compare against it later, and it tells you exactly what to put back if a change goes wrong:
mkdir -p ~/sysctl-demo
sudo sysctl -a 2>/dev/null | sort > ~/sysctl-demo/before.txt
wc -l ~/sysctl-demo/before.txt
grep -E '^(vm.swappiness|net.core.somaxconn|fs.inotify.max_user_watches|net.ipv4.ip_local_port_range) ' ~/sysctl-demo/before.txtsudo is there because a few keys are readable only by root. 2>/dev/null hides the handful of keys that refuse to be read at all.
Check it worked
cat /proc/sys/vm/swappiness and sysctl -n vm.swappiness print the same number. wc -l reports something like a thousand lines, and the grep prints four lines with the current values of the keys this tutorial looks at.
Step 2 · Find which file sets each value
At boot, systemd-sysctl.service reads drop-in files from four directories and writes their values into /proc/sys:
/etc/sysctl.d/for your own files/run/sysctl.d/for files created at run time/usr/local/lib/sysctl.d/for locally installed software/usr/lib/sysctl.d/for files that packages install
All files from all four are sorted together by file name, and when two files set the same key, the file whose name sorts last wins. A file in /etc/sysctl.d/ with the same name as one in /usr/lib/sysctl.d/ replaces it completely. Never edit files under /usr/lib/sysctl.d/: the next package upgrade overwrites them.
Ask systemd to print every file it will read, in the order it reads them:
systemd-analyze cat-config sysctl.d | grep '^# /'
ls /usr/lib/sysctl.d /etc/sysctl.dOn Ubuntu 26.04 the defaults live in /usr/lib/sysctl.d/: 50-default.conf from systemd and a set of 55-*.conf files from procps, such as 55-kernel-hardening.conf and 55-network-security.conf. /etc/sysctl.d/ holds only a README until you add something. There is no /etc/sysctl.conf on a fresh 26.04 install. If an older or upgraded server has one, look for it in the cat-config list: if it is not listed, boot does not apply it.
To find which file sets one key, search the directories for it:
grep -rn rp_filter /etc/sysctl.d /usr/lib/sysctl.dYou will see net.ipv4.conf.*.rp_filter = 2 in 50-default.conf and net.ipv4.conf.all.rp_filter=2 in 55-network-security.conf. Two details in that output appear in your own files later. A * in a key is a glob that matches every network interface. A line starting with - either means "do not fail if this key is missing" (-net.core.default_qdisc = fq_codel) or, with no =, "leave this key out of the glob above" (-net.ipv4.conf.all.rp_filter).
Check it worked
The cat-config list ends with Ubuntu's 50- and 55- files from /usr/lib/sysctl.d/ (other packages can add their own, such as a 50-pid-max.conf or a 99-*.conf) and nothing from /etc. You can name the file that sets kernel.kptr_restrict on your server (/usr/lib/sysctl.d/55-kernel-hardening.conf), and you know that any file you name 90-something.conf sorts after it and wins, as long as no file on the server sorts later and sets the same key.
Step 3 · Change a value for this boot only
sysctl -w writes straight into /proc/sys. The change takes effect at once and disappears at the next reboot, which makes it the safe way to try a value. Try it on vm.swappiness, which only changes how willing the kernel is to swap:
sudo sysctl -w vm.swappiness=30
sysctl vm.swappinessPut the original value back. Take it from your snapshot rather than from memory: if you followed /tutorials/add-swap-space-with-a-swap-file, it is 10, not the kernel default of 60.
grep '^vm.swappiness ' ~/sysctl-demo/before.txtsudo sysctl -w vm.swappiness=60Replace 60 with the number the grep printed. Two mistakes to avoid with -w: there must be no spaces around = (or quote the whole thing, as in sudo sysctl -w net.ipv4.ip_local_port_range="10240 65535"), and a misspelt key fails with cannot stat /proc/sys/... rather than creating anything.
Check it worked
After the first command, sysctl vm.swappiness prints vm.swappiness = 30. After the second, it prints the value from your snapshot again. Nothing under /etc changed, so a reboot would also have put it back.
Step 4 · Measure before you tune anything
Each of the four keys below is a common tuning target. For each one, the question is the same: does this server show the symptom? If not, leave the default alone.
vm.swappiness (0 to 200, default 60) sets how readily the kernel moves idle process memory to swap instead of dropping file cache. It matters only if the server has swap. The swap tutorial covers choosing a value; to see whether swapping is happening at all, watch the si and so columns (pages swapped in and out per second) and the running totals:
vmstat 1 3
grep -E '^pswp(in|out) ' /proc/vmstatnet.core.somaxconn caps the queue of connections that have finished the TCP handshake but that your app has not yet accepted. The default has been 4096 since Linux 5.4, which is enough for most servers. If the queue overflows, the kernel counts it:
nstat -az TcpExtListenOverflows TcpExtListenDrops
ss -ltnIn ss -ltn, the Send-Q column of a listening socket is its queue size and Recv-Q is how many connections are waiting right now. If the overflow counters climb during busy periods, the app is not accepting fast enough. Raising somaxconn only helps if the app also asks for a bigger queue (Nginx uses 511 unless you add backlog= to its listen line), because the kernel silently cuts the app's request down to somaxconn. Often the real fix is more worker processes.
fs.inotify.max_user_watches limits how many files and directories one user can watch for changes. File watchers in Node build tools, editors' remote servers and sync tools hit it, and fail with messages like ENOSPC: System limit for number of file watchers reached. Since Linux 5.11 the default is sized from RAM, between 8192 and 1048576, so a small VPS with 1 or 2 GB gets a much lower limit than a large machine. Count the watches in use across all processes:
sysctl fs.inotify.max_user_watches
sudo sh -c 'cat /proc/[0-9]*/fdinfo/* 2>/dev/null | awk "/^inotify/ {n++} END {print n+0}"'net.ipv4.ip_local_port_range (default 32768 60999, about 28,000 ports) is the pool of source ports for outgoing connections. A reverse proxy or app making many short connections to one upstream can run out, and fails with Cannot assign requested address. Look at how many connections sit in TIME-WAIT:
sysctl net.ipv4.ip_local_port_range
ss -sIf timewait in ss -s approaches the size of the range, widening it to 10240 65535 helps. Keep the low end above any port a service on the server listens on, and keep one end even and one odd, as the kernel documentation recommends.
Check it worked
You have a written note for each of the four keys, such as "swap in/out 0, no listen overflows, 140 inotify watches of 8192, 30 connections in TIME-WAIT". If every line looks like that, this server needs none of these changes, and that is the most common result.
Step 5 · Make a measured change permanent with a drop-in
Use a drop-in only for a key whose symptom you saw. The example is a 2 GB build server where a file watcher hit the inotify limit. First compare the value you plan to set with the current one: on a larger machine the default may already be higher than a number copied from a blog post, and writing that number would lower it.
sysctl fs.inotify.max_user_watchesIf the current value is lower than 524288, write a file of its own for this one change, with a comment saying why:
sudo tee /etc/sysctl.d/90-inotify.conf > /dev/null <<'EOF'
# File watchers in the build tool hit ENOSPC with the RAM-sized default.
fs.inotify.max_user_watches = 524288
EOFOne purpose per file makes each change easy to find, explain and remove. The 90- prefix sorts after Ubuntu's 50- and 55- defaults, so this file wins unless a package has installed a later file (such as a 99-*.conf) that sets the same key.
Check that every key in the file exists on this kernel before you apply it. A typo or an obsolete key is the usual reason a drop-in does nothing:
grep -Ev '^[[:space:]]*(#|$)' /etc/sysctl.d/90-inotify.conf | cut -d= -f1 | tr -d ' ' | while read -r key; do sysctl "$key" > /dev/null || echo "Unknown key: $key"; done
systemd-analyze cat-config sysctl.d | grep -E '^# /|max_user_watches'Apply all drop-ins now, in the same order boot uses:
sudo sysctl --system
sysctl fs.inotify.max_user_watchessysctl --system prints each file it applies, then each key and value. A line starting sysctl: cannot stat names a key that does not exist.
Check it worked
The key check prints nothing. cat-config lists /etc/sysctl.d/90-inotify.conf after Ubuntu's 50- and 55- files, with the new value under it (on a stock server it is usually last). After sysctl --system, sysctl fs.inotify.max_user_watches prints 524288, and the build tool's watcher starts without ENOSPC. If you had no measured problem and wrote the file only as practice, remove it in the last step.
Step 6 · Apply the hardening keys Lynis checks
Lynis test KRNL-6000 compares a list of sysctl keys with the values its profile expects. If you installed Lynis in /tutorials/audit-a-server-with-lynis, skip the install line below. Otherwise it installs Lynis 3.1.6 from the Ubuntu archive. Then run only this test, before you change anything, so you have a log to compare against later:
sudo apt-get install -y lynis
sudo lynis audit system --tests KRNL-6000 --no-colors > /dev/null
sudo grep 'different value than expected' /var/log/lynis.logOn Ubuntu 26.04 this lists more than a dozen keys, among them kernel.sysrq, kernel.modules_disabled, kernel.unprivileged_bpf_disabled, fs.protected_fifos, dev.tty.ldisc_autoload and the log_martians keys. This tutorial deals with three groups, chosen because each has a clear reason and a low risk on a single-interface server:
kernel.kptr_restrict: Ubuntu sets1, which hides kernel memory addresses in files such as/proc/kallsymsfrom users withoutCAP_SYSLOG.2hides them from root too, which makes it harder for an attacker who gains root to aim a kernel exploit. The cost is that root-run profiling tools such asperfcan no longer resolve kernel symbols.rp_filter: reverse path filtering drops packets whose source address could not be reached back through the interface they arrived on, which blocks many spoofed packets. Ubuntu sets loose mode (2); Lynis wants strict mode (1). The kernel uses the higher of theallvalue and the interface's own value, so strict mode needsall,defaultand every interface set to1.accept_redirectsandsend_redirects: ICMP redirects let a router on the network change your server's routes. A server with fixed routes has no use for them, and a server that is not a router has no reason to send them. Set both to0, onalland ondefault(for interfaces created later), and setaccept_redirectsto0for IPv6 as well.
The rest are left alone on purpose, because copying Lynis's value blindly can hurt. kernel.modules_disabled = 1 stops the kernel loading any further module until the next reboot, so plugging in a USB drive or starting a VPN that needs a new module fails. kernel.sysrq and the log_martians keys are judgement calls: SysRq is a recovery tool on a console you control, and logging martian packets can fill the journal on a busy network. Work through those one at a time, as in /tutorials/audit-a-server-with-lynis. If you run Docker, net.ipv4.conf.all.forwarding also shows up as different; leave it, as containers need forwarding.
Keep Ubuntu's loose rp_filter = 2 if the server has more than one network interface, uses policy routing, or runs a VPN or overlay network where replies can leave by a different interface than requests arrived on: strict mode silently drops that traffic. On a cloud server reached only over SSH, keep your provider's web console open while you apply this step, so a network mistake does not lock you out.
sudo tee /etc/sysctl.d/90-hardening.conf > /dev/null <<'EOF'
# Values expected by Lynis KRNL-6000. Review before copying to another server.
kernel.kptr_restrict = 2
# Strict reverse path filtering: one interface, symmetric routing only.
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.*.rp_filter = 1
# Ignore ICMP redirects, and send none (this server is not a router).
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
EOF
systemd-analyze cat-config sysctl.d | grep -E '^# /|kptr_restrict ='sudo sysctl --system
sysctl kernel.kptr_restrict net.ipv4.conf.all.rp_filter net.ipv4.conf.all.accept_redirects
sudo head -n 3 /proc/kallsymsRun the Lynis test again. Each run replaces /var/log/lynis.log, so this log shows only the after state:
sudo lynis audit system --tests KRNL-6000 --no-colors > /dev/null
sudo grep -E 'sysctl key .*(different value|equal expected)' /var/log/lynis.logCheck it worked
cat-config shows kptr_restrict = 1 under 55-kernel-hardening.conf and kptr_restrict = 2 under 90-hardening.conf, which sorts later and wins. After sysctl --system, the three values read 2, 1 and 0, and sudo head -n 3 /proc/kallsyms shows addresses of all zeros even as root. In the first Lynis run, the log had lines such as sysctl key kernel.kptr_restrict has a different value than expected in scan profile. Expected=2, Real=1. In the second, only the keys you set in 90-hardening.conf change to contains equal expected and current value; the other keys, such as kernel.sysrq and kernel.modules_disabled, still say different value on purpose. Finally, open a new SSH session to the server before you close the old one, to prove networking still works.
Step 7 · Avoid copied tuning lists and back out a change
Long sysctl lists copied between servers cause three kinds of harm:
- Keys that no longer exist.
net.ipv4.tcp_tw_recyclestill appears in many guides. It broke connections from clients behind NAT, which includes most mobile networks, and was removed in Linux 4.12. On current kernels the line fails to apply and hides real errors in the output. - Values below the current default. A list written for a 2015 kernel may set
net.core.somaxconn = 1024or a fixed inotify limit, both lower than what Ubuntu 26.04 already gives you. - Changes with side effects nobody measured.
vm.overcommit_memory = 2makes the kernel refuse memory allocations beyond a fixed limit, which crashes many programs that reserve more than they use. Huge network buffer sizes use memory on every connection.
See the first problem on your own server:
sysctl net.ipv4.tcp_tw_recycle || echo "This key does not exist on this kernel"To back out a drop-in, remove the file, then set the value back yourself: removing a file does not reset anything until the next reboot. Take the old value from your snapshot. The commands below remove the practice inotify file; skip them if you measured a real need and want to keep it.
grep '^fs.inotify.max_user_watches ' ~/sysctl-demo/before.txt
sudo rm /etc/sysctl.d/90-inotify.confsudo sysctl -w fs.inotify.max_user_watches=8192Replace 8192 with the value the grep printed. Then compare the live values with the snapshot to see everything you have changed since the first step:
sudo sysctl -a 2>/dev/null | sort > ~/sysctl-demo/after.txt
if diff ~/sysctl-demo/before.txt ~/sysctl-demo/after.txt; then echo "No differences"; fiA few counters, such as fs.dentry-state, fs.file-nr, fs.inode-state and kernel.ns_last_pid, change on their own, and kernel.random.uuid prints a new value on every read; ignore them. Every other line in the diff should be a change you made on purpose. When you are done, remove the snapshot folder:
rm -r ~/sysctl-demoCheck it worked
sysctl net.ipv4.tcp_tw_recycle prints cannot stat /proc/sys/net/ipv4/tcp_tw_recycle followed by the echo line. ls /etc/sysctl.d lists only README.sysctl and 90-hardening.conf, plus any drop-in you kept for a measured reason, each with a comment saying why. After a reboot, sysctl kernel.kptr_restrict still prints 2, which proves the drop-in loads at boot.
Next steps
- Choose a swappiness value that suits a swap file or zram in
/tutorials/add-swap-space-with-a-swap-file. - Run the full Lynis audit and work through the other findings with
/tutorials/audit-a-server-with-lynis. - Pair kernel network hardening with a deny-by-default firewall in
/tutorials/set-up-ufw-firewall-ubuntu-26-04.
Related tutorials
- Write safer Bash scripts with strict mode and trapsYou will build a small Bash release script that stops on the first error, says which line failed, survives file names with spaces and always removes its temporary files.
- Write least-privilege sudo rules with visudoYou will replace blanket sudo access with checked rule files in /etc/sudoers.d that let two operators restart one service and edit one file, give an automation account a password-free command list, and audit what every account can run.
- Upgrade a server from Ubuntu 24.04 LTS to 26.04 LTSYou will take a backed-up Ubuntu 24.04 server through do-release-upgrade to 26.04 LTS over SSH with a fallback login, then confirm services, repositories and language runtimes work on the new release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials