How to Harden a Linux Server in 2025 – Practical Steps for Sysadmins to protect against hackers and bots


December 11th, 2025

linux_server-hardening-practical-steps-for-sysadmins-protecting-machine-vs-hackers-and-bots-good-practices

Securing a Linux server has never been more importan than ever these days..
With automated attacks, AI-driven exploits, and increasingly complex infrastructure, even a small misconfiguration can lead to a serious breach.
But wait, you don't have to wait to get bumped by a random script kiddie. Good news is you can mitigate a bit attacks with just a few practical and pretty much standard steps, that can can drastically increase your server’s security.

Below is a straightforward, battle-tested hardening guide suitable for Debian, Ubuntu, CentOS, AlmaLinux, and most modern distributions.

1. Keep the System Updated (But Safely)

Outdated packages remain the #1 cause of server compromises.
On Debian/Ubuntu:

# apt update && apt upgrade -y

# apt install unattended-upgrades

On RHEL-based systems:
 

# dnf update -y

# dnf install dnf-automatic

Enable security-only auto-updates where possible. Full auto-updates may break production apps, so use them carefully.

2. Create a Non-Root User and Disable Direct Root Login
 

Attackers constantly brute-force “root”. Avoid letting them.
 

# adduser sysadmin

# usermod -aG sudo sysadmin

Then edit SSH:

# vim /etc/ssh/sshd_config

Set:

PermitRootLogin no

PasswordAuthentication no

And restart:

# systemctl restart sshd


Use SSH keys only.

3. Install a Firewall and Block Everything by Default

UFW (Debian/Ubuntu):

# ufw default deny incoming

# ufw default allow outgoing

#ufw allow ssh

# ufw enable

Firewalld (RHEL/AlmaLinux):

# systemctl enable firewalld –now

# firewall-cmd –permanent –add-service=ssh

# firewall-cmd –reload

Turn off any unneeded ports immediately.

4. Protect SSH with Fail2Ban

Fail2Ban watches log files for suspicious authentication attempts and blocks offenders.

# apt install fail2ban -y

or

# dnf install fail2ban -y

Enable:

# systemctl enable –now fail2ban

To harden SSH jail:

[sshd]

enabled = true

maxretry = 5

bantime = 1h

findtime = 10m

5. Enable Kernel Hardening

Install sysctl rules that protect against common attacks:

Create /etc/sysctl.d/99-hardening.conf:

kernel.kptr_restrict = 2

kernel.sysrq = 0

net.ipv4.conf.all.rp_filter = 1

net.ipv4.tcp_synack_retries = 2

net.ipv4.conf.all.accept_redirects = 0

net.ipv4.conf.all.send_redirects = 0

net.ipv4.conf.all.log_martians = 1

Apply:

# sysctl –system

6. Install and Configure AppArmor or SELinux

Mandatory Access Control significantly limits damage if a service gets compromised.

  • Ubuntu / Debian uses AppArmor by default — ensure it's enabled.
  • RHEL, AlmaLinux, Rocky use SELinux — keep it in enforcing mode unless absolutely necessary.

Check SELinux:

# getenforce

You want:

Enforcing but hopefully you will have to configure all your machine services to venerate and work correctly with selinux enabled.

7. Scan the System with Lynis

Lynis is the best open-source Linux security auditing tool.

# apt install lynis

# lynis audit system

It provides a security score and actionable suggestions.

8. Use 2FA for SSH (Optional but Highly Recommended)

Use Two Factor Authentication:

a. Freely with Oath toolkityou can read how in my previous article how to set up 2fa free software authentication on Linux

or

b. Install Google Authenticator:

# apt install libpam-google-authenticator

# google-authenticator

Enable in /etc/pam.d/sshd:

auth required pam_google_authenticator.so

And in SSH config:

ChallengeResponseAuthentication yes

Restart SSH.

9. Separate Services Using Containers or Systemd Isolation

Even simple servers can benefit from isolation.

Systemd sandbox options:

ProtectSystem=full

ProtectHome=true

ProtectKernelTunables=true

PrivateTmp=true

Add these inside a service file under:

/etc/systemd/system/yourservice.service

It prevents processes from touching parts of the system they shouldn’t.

10. Regular Backups Are Part of Security

A secure server with no backups is a disaster waiting to happen.

Use:

  • rsync
  • borgbackup
  • restic
  • Cloud object storage with versioning

Always encrypt backups and test restore procedures.

Conclusion

Hardening a Linux server in 2025 requires vigilance, good practices, and layered security. No single tool will protect your system — but when you combine SSH security, firewalls, Fail2Ban, kernel hardening, and backups, you eliminate the majority of attack vectors.

 

Speed Up Linux: 10 Underrated Hacks for Faster Workstations and Servers


December 9th, 2025

make-linux-faster-underrated-hacks-cute-tux-penguin-toolbox-logo

 

Most Linux “performance tuning guides” recycle the same tips: disable services, add RAM, install a lighter desktop … and then you end up with a machine that feels basically not too much quicker.

Below is a collection of practical, field-tested, sysadmin-grade hacks that actually change how responsive your system feels—on desktops, laptops, and even small VPS servers.

Most of these are rarely mentioned (or uknown) by novice sys admins / sys ops / system engineers / dev ops but time has proved them extremely effective.

1. Enable zram (compressed RAM) instead of traditional swap

Most distros ship with a slow swap partition on disk. Enabling zram keeps swap in memory and compresses it on the fly. On low/mid RAM systems, the difference is night and day.

On Debian/Ubuntu:

# apt install zram-tools

# systemctl enable –now zramswap.service

Expect snappier multitasking, fewer freezes, and far less disk thrashing.

2. Speed up SSH connections with ControlMaster multiplexing

If you SSH multiple times into the same server, you can cut connection time to almost zero using SSH socket multiplexing:

Add to ~/.ssh/config:

Host *

    ControlMaster auto

    ControlPath ~/.ssh/cm-%r@%h:%p

    ControlPersist 10m

Your next ssh/scp commands will feel instant.

 

3. Replace grep, find, and ls with faster modern tools

 

The classic GNU tools are fine—until you try the modern replacements:

  • ripgrep (rg) → insanely faster grep
  • fd → user-friendly, colored alternative to find
  • exa or lsd → modern ls with icons, colors, Git info

# apt install ripgrep fd-find exa

You’ll be surprised how often you use them.

4. Improve boot time via systemd-analyze

Run cmd:

# systemd-analyze blame

This shows what’s delaying your boot. Disable useless services like:
 

# systemctl disable bluetooth.service

# systemctl disable ModemManager

# systemctl disable cups

Great for lightweight servers and old laptops.

5. Make your terminal 2–3× faster with GPU rendering (Kitty/Alacritty)

Gnome Terminal and xterm are CPU-bound and choke when printing thousands of lines.

Switch to a GPU-rendered terminal:

  • Kitty
  • Alacritty

They scroll like butter – even on old ThinkPads.

6. Use eatmydata when installing packages

APT and DPKG spend a lot of time syncing packages safely to disk. If you're working in a Docker container, VM, or test machine where safety is less critical, use:

# apt install eatmydata

# eatmydata apt install PACKAGE

It cuts install time by 30–70% !

7. Enable TCP BBR congestion control (massive network speed boost)

Google’s BBR can double upload throughput on many servers.

Check if supported:

sysctl net.ipv4.tcp_available_congestion_control

Enable:

# echo "net.core.default_qdisc=fq" | sudo tee -a /etc/sysctl.conf

# echo "net.ipv4.tcp_congestion_control=bbr" | sudo tee -a /etc/sysctl.conf

# sysctl -p

On VPS hosts with slow TCP stacks, this is a cheat code.

8. Reduce SSD wear and speed up disk with noatime

Every time a file is read, Linux updates its “access time.” Useless on most systems.

Edit /etc/fstab and change:

defaults

to:

defaults,noatime

Fewer writes + slightly better I/O performance.

9. Use htop + iotop + dstat to diagnose “mystery lag”

When a Linux system hangs, it’s rarely the CPU. It’s almost always:

  • I/O wait
  • swap usage
  • blocked processes
  • misbehaving snaps or flatpaks

Install the golden server stats trio:

# apt install htop iotop dstat

Check:

  • htop → load, processes, swap
  • iotop → who’s killing your disk
  • dstat -cdlmn → real-time performance overview

Using them can solve you 90% of slowdowns in minutes.

10. Speed up your shell prompt dramatically

Fancy PS1 prompts (Git branches, Python envs, emojis) look nice but slow down your shell launch.

Fix it by using async Git status tools:

  • starship prompt
  • powerlevel10k for zsh

Both load instantly even in large repos.

11. Another underrated improvement (if not already done), 
/home directory storage location

Put your $HOME on a separate partition or disk.

Why?

  • faster reinstalls
  • easier backups
  • safer experiments
  • fewer “oops I nuked my system” moments by me or someone else who has account doing stuff on the system

Experienced sysadmins and a good corporate server still does this for a reason.

Final Thoughts

Performance isn’t just about raw hardware—it's about removing the subtle bottlenecks Linux accumulates over time. With the changes above, even a 10-year-old laptop or low-tier VPS feels like a new machine.

How to keep your Linux server Healthy for Years: Hard learned lessons


November 28th, 2025

how-to-keep-your-linux-servers-healthy-every-year-doctor_tux

I’ve been running Linux servers long enough to watch hardware die, kernels panic, filesystems fill up at midnight hours, and network cards slowly burn out like old light bulbs.

Over time, you learn that keeping a server alive is less about “perfect architecture” and more about steady discipline – the small habits built to manage the machines, helps prevent big disasters.

Here are some practical, battle-tested lessons that keep my boxes running for years with minimal downtime. Most of them were learned the hard way.

1. Monitor Before You Fix – and Fix Before It Breaks

Most Linux disasters come from things we should have noticed earlier. The lack of monitoring, there is modern day saying that should become your favourite if you are a sysadmin or Dev Ops engineer.

"Monitoring everything !"

  • The disk that was at 89% yesterday will be at 100% tonight.
  • The log file that grew by 500 MB last week will explode this week.
  • The swap usage creeping from 1% → 5% → 20% means your next heavy task will choke.
  • The unseen failing BIOS CMOS battery
  • The RAID disks degradation etc.

You don’t need enterprise monitoring to prevent this. And even simple tools like monit or a simple zabbix-agent -> zabbix-server or any other simplistic scripted  monitoring gives you a basic issues pre-warning.

Even a simple cronjob shell one liner can save you hours of further sh!t :

#!/bin/bash

df -h / | awk 'NR==2 { if($5+0 > 85) print "Disk Alert: / is at " $5 }' \
| mail -s "Disk Warning on $(hostname)" admin@example.com

2. Treat /etc directory as Sacred – Treat It Like an expensive gem

Every sysadmin eventually faces the nightmare of a broken config overwritten by a package update or a hasty command at 2 AM.

To avoid crying later, archive /etc automatically:

# tar czf /root/etc-$(date +%Y-%m-%d).tar.gz /etc


If you prefer the backup to be more sophisticated you can use my clone of the dirs_backup.sh (an old script I wrote for easifying backup of specific directories on the filesystem ) the etc_backup.sh you can get here.
Run it weekly via cron.
This little trick has saved me more times than I can count — especially when migrating between Debian releases or recovering from accidental edits.

3. Automate everything what you have to repeatevely do

If you find yourself doing something manually more than twice, script it and forget it.

Examples:

  • rotating logs for misbehaving apps
  • restarting services that occasionally get “stuck”
  • syncing backups between machines
  • cleaning temp directories

Here’s a small example I still use today:

#!/bin/bash

# Kill zombie PHP-FPM children that keep leaking memory

ps aux | grep php-fpm | awk '{if($6 > 300000) print $2}' | xargs -r kill -9

Dirty way to get rid of misfunctioning php-fpm ?
Yes. But it works.

4. Backups Don’t Exist Unless You Test Them

It’s easy to feel proud when you write a backup script.
It’s harder – and far more important – to test the restore.

Once a month  or at least once in a few months, try restore a random backup to a dummy VM.
Sometimes backup might fails, or you might get something different from what you originally expected and by doing so
you can guarantee you will not cry later helplessly.

A broken backup doesn’t fail quietly – it fails on the day you need it most.

5. Don’t Ignore Hardware – It Ages like Everything Else

Linux might run forever, but hardware doesn’t.

Signs of impending doom:

  • dmesg spam with I/O errors
  • slow SSD response
  • increasing SMART reallocated sectors
  • random freezes without logs
  • sudden network flakiness

Run this monthly:

6. Document Everything (Future You Will Thank Past You)

There are moments when you ask yourself:

“Why did I configure this machine like this?”

If you don’t document your decisions, you’ll have no idea one year later.

A simple markdown file inside /root/notes.txt or /root/README.md is enough.

Document:

  • installed software
  • custom scripts
  • non-standard configs
  • firewall rules
  • weird hacks you probably forgot already

This turns chaos into something you can actually maintain.

7. Keep Things Simple – Complexity Is the Enemy of Uptime

The longer I work with servers, the more I strip away:

  • fewer moving parts
  • fewer services
  • fewer custom patches
  • fewer “temporary” hacks that become permanent

A simple system is a reliable system.
A complex one dies at the worst possible moment.

8. Accept That Failure Will Still Happen

No matter how careful you are, servers will surely:

  • crash
  • corrupt filesystems
  • lose network connectivity
  • inexplicably freeze
  • reboot after a kernel panic

Don’t aim for perfection.Aim for resilience.

If you can restore the machine in under an hour, you're winning and in the white.

Final Thoughts

Linux is powerful – but it rewards those who treat it with respect and perseverance.
Over many years, I’ve realized that maintaining servers is less about brilliance and more about humble, consistent care and hard work persistence.

I hope this article helps some sysamdmin to rethink and rebundle servers maintenance strategy in a way that will avoid a server meltdown at  night hours like 3 AM.

Cheers ! 

 

How I Stopped My AWS workspace Linux Desktop From Going to Sleep… Without Root Access


November 20th, 2025

keeping-session-alive-stop-aws-workspace-to-auto-suspend-with-systemd-inhibit-or-a-simple-loop-scriptcover

If you've spent enough time around Linux servers and desktops, you already know one universal truth:

Linux never does exactly what you expect… especially when you don’t have root.

A few weeks ago, I found myself in a situation that’s probably familiar to anyone who works on shared servers, university machines, or restricted corporate environments:

My session kept going to sleep, killing long-running scripts, dropping SSH tunnels, freezing terminals—for absolutely no good reason.

To make things worse, I didn’t have sudo on this box.
No changing systemd settings, no tweaking /etc/systemd/logind.conf, and definitely no masking sleep targets.

So I went down the rabbit hole of how to keep a Linux machine awake without any superuser privileges.
Here’s the write-up of that journey—and yes, the final solution is surprisingly elegant.

The Problem: When the System Sleeps, Your Work Dies

My main issue: every 15 minutes of inactivity, the system would suspend the session.
Not the entire PC — just my user session. It didn't matter if I had background jobs running or SSH tunnels open; if I wasn’t interacting, the session was toast.

The machines were managed centrally, so root was a luxury I simply didn’t have.

What followed was a typical sysadmin debugging sequence:

  1. Angry at the stupidity
  2. Google.
  3. Try things that shouldn’t work.
  4. Try things that definitely shouldn't work.
  5. Accidentally discover the correct solution while reading some random docs if point 3 doesn’t already solve it

The Trick: systemd-inhibit (Works Without Root!)

While digging through the systemd documentation, I discovered something beautiful:

Non-root users can create inhibitor locks.

This means your normal user account can ask systemd:
Please don’t put this session to sleep while this program is running.”

And systemd says:
“Okay. I respect that.”

All it takes is:

systemd-inhibit –what=handle-lid-switch:sleep –mode=block sleep infinity

This command runs a never-ending sleep process—
and while it runs, the system is forbidden to suspend.

You can even run it in the background:

$ nohup systemd-inhibit sleep infinity &

Want to verify it’s working?

$ systemd-inhibit –list

You’ll see your inhibitor lock listed like a VIP pass at a nightclub.

If You Have caffeinate, Even Better

Some Linux distros ship with a utility called caffeinate (similar to macOS).
It’s almost poetic:

$ caffeinate -di sleep infinity

This one also blocks sleep while the command runs.
Just leave it running as a background job and your session stays alive.

The Primitive but Always-Working Hack: Keepalive Script

If neither systemd-inhibit nor caffeinate exist, you can fall back to a caveman approach and still have the basic functionality of the Move Mouse Windows tool on Linux :):
 

#!/bin/bash

while true; do

    echo "Still here: $(date)"

    sleep 60

done

This prevents session idleness by emitting activity every minute.
Not elegant, but reliable.

Sometimes the caveman wins.

Why This Matters

Keeping a session awake might sound trivial, but for sysadmins, developers, pentesters, researchers, or anyone running long processes on managed machines, it’s a lifesaver.

You avoid:

  • broken SSH tunnels
  • silent failure of long-running scripts
  • GUI sessions locking themselves
  • losing tmux/screen sessions
  • interrupted compiles or renders
  • VPN disconnects

And you don’t need to bug IT or break policy.

Final Thoughts

What surprised me most is how simple the final solution was:

  • No root
  • No configuration changes
  • No hacks
  • No kernel tweaks

Just one systemd command used properly.

Sometimes Linux feels like an inscrutable labyrinth… and sometimes it gives you a quiet, elegant tool hiding in plain sight.

If you ever find yourself fighting unwanted auto-suspend on a machine you don’t control –
give systemd-inhibit a try.

Generate and Use WiFi passwords via QR code on Linux


November 17th, 2025

If you’re running a WiFi network for a guest house / AirBNB, a small hotel or an office / home network and you’re tired of telling / dictating guests your long, complicated Wi-Fi password every time they visit, there’s a simple and secure way to share the WiFi name and password by putting the info in a WiFi authentication QR code. With a simple scan from their phone via a QR reader (which iPhones and all modern smartphones have), they can join your network instantly with zero typing.

In short — Why use a QR Code for Wi-Fi?

  • Convenience for guests: No more reading or spelling out your SSID and password.
  • Better security practice: Keep a strong password while still making access easy.
  • Works on most devices: Android and iOS both support Wi-Fi QR codes.

The Wi-Fi QR Code Standard Format

Smartphones understand Wi-Fi QR codes using this format:

WIFI:S:;T:;P:;;

  • S: your Wi-Fi network name (SSID)
  • T: encryption type (WPA, WEP, or nopass)
  • P: your Wi-Fi password
  • Everything ends with ;;

If your SSID or password contains special characters such as ; or \, they must be escaped using a backslash \.

Example:

SSID = WifiNetworkName
Password = @ss;word45123P4?#$!
Type = WPA

The final string becomes:

WIFI:S:WifiNetworkName;T:WPA;P:@ss\;word45123P4?#$!;;

How to Generate the QR Code Locally on Linux

You can generate the QR code locally using qrencode instead of uploading credentials online.

  1. Install qrencode (Debian/Ubuntu):

    # apt update # apt install qrencode

  2. Generate the QR code:

    # qrencode -o wifi-qr.png 'WIFI:S:WifiNetwork;T:WPA;P:P@ss\;word!;;'

    Example with colors and SVG output:

    # qrencode -t svg –foreground=FFFFFF –background=000000 \ -o qr-code.svg –inline –rle -s 10 \ "WIFI:S:MyWiFI;T:WPA;P:<Secret_Pass>;;"

    Use -s to increase size, e.g. -s 10.

  3. Print or share the generated wifi-qr.png.

Alternative: GUI / Desktop Approach

On GNOME-based systems (Ubuntu, Fedora), install the WiFi QR Code GNOME extension.

  • Open quick settings → Wi-Fi → “Show QR Code”
  • Right-click to copy or save for printing

Advanced: Using wifi-qr Tool

The wifi-qr tool provides CLI and GUI Wi-Fi QR generation.

# terminal interface to generate QR
# wifi-qr -t

wifi-qr screenshot

This command prints your current Wi-Fi SSID, encryption type, and password in clear text.

Security Tips

  • Limit where you display the QR
  • Rotate the password when needed
  • Use a guest network instead of your main one
  • Prefer WPA2/WPA3
  • Store QR images safely

How Guests Use the QR Code

  1. Open the phone camera (iOS/Android)
  2. Point it at the QR
  3. Tap “Join” when the Wi-Fi prompt appears

Final Thoughts

Generating a Wi-Fi QR code blends security with usability. Whether using qrencode, a GUI extension, or a website, guests connect instantly with a quick scan – no typing required.

Migrating Server environments to Docker Containers a brief step-by-step guide


November 12th, 2025

migrating-server--applications-environment-to-docker-containers

In modern IT environments, containerization has become an essential strategy for improving application portability, scalability, and consistency. Docker, as a containerization platform, allows you to package applications and their dependencies into isolated containers that can be easily deployed across different environments. Migrating an existing server environment into Docker containers is a common scenario, and this guide will walk you through the key steps of doing so.

Why Migrate to Docker?

Before we dive into the specifics, let’s briefly understand why you might want to migrate your server environment to Docker:

  • Portability: Containers encapsulate applications and all their dependencies, making them portable across any system running Docker.
  • Scalability: Containers are lightweight and can be scaled up or down easily, offering flexibility to handle varying loads.
  • Consistency: With Docker, you can ensure that your application behaves the same in development, testing, and production.
  • Isolation: Docker containers run in isolation from the host system, minimizing the risk of configuration conflicts.
     

Steps to Migrate a Server Environment into Docker

Migrating an environment of servers into Docker typically involves several steps: evaluating the current setup, containerizing applications, managing dependencies, and orchestrating deployment. Here’s a breakdown:

1. Evaluate the Existing Server Environment

Before migrating, it's essential to inventory the current server environment to understand the following:

  • The applications running on the servers
  • Dependencies (e.g., databases, third-party services, libraries, etc.)
  • Networking setup (e.g., exposed ports, communication between services)
  • Storage requirements (e.g., persistent data, volumes)
  • Security concerns (e.g., user permissions, firewalls)
     

For example, if you're running a web server with a backend database and some caching layers, you'll need to break down these services into their constituent parts so they can be containerized.

2. Containerize the Application

The next step is to convert the services running on your server into Docker containers. Docker containers require a Dockerfile, which is a blueprint for how to build and run the container. Let's walk through an example of containerizing a simple web application.

Example: Migrating a Simple Node.js Web Application

Assume you have a Node.js application running on your server. To containerize it, you need to:

  • Create a Dockerfile
  • Build the Docker image
  • Run the containerized application

2.1. Write a Dockerfile

A Dockerfile defines how your application will be built within a Docker container. Here’s an example for a Node.js application:

# Step 1: Use the official Node.js image as a base image FROM node:16

# Step 2: Set the working directory inside the container WORKDIR /usr/src/app # Step 3: Copy package.json and package-lock.json to the container COPY package*.json ./

# Step 4: Install dependencies inside the container RUN npm install

# Step 5: Copy the rest of the application code to the container COPY . .

# Step 6: Expose the port that the application will listen on EXPOSE 3000

# Step 7: Start the application CMD ["npm", "start"]

This Dockerfile:

  1. Uses the official node:16 image as a base.
  2. Sets the working directory inside the container to /usr/src/app.
  3. Copies the package.json and package-lock.json files to the container and runs npm install to install dependencies.
  4. Copies the rest of the application code into the container.
  5. Exposes port 3000 (assuming that’s the port your app runs on).
  6. Defines the command to start the application.

2.2: Build the Docker Image

Once the Dockerfile is ready, build the Docker image using the following command:

# docker build -t my-node-app .

This command tells Docker to build the image using the current directory (.) and tag it as my-node-app.

2.3: Run the Docker Container

After building the image, you can run the application as a Docker container:

# docker run -p 3000:3000 -d my-node-app

This command:

  • Maps port 3000 from the container to port 3000 on the host machine.
  • Runs the container in detached mode (-d).

3. Handling Dependencies and Services

If your server environment includes multiple services (e.g., a database, caching layer, or message queue), you'll need to containerize those as well. Docker Compose can help you define and run multi-container applications.

Example: Dockerizing a Node.js Application with MongoDB

To run both the Node.js application and a MongoDB database, you’ll need a docker-compose.yml file.

Create a docker-compose.yml file in your project directory:

    version: '3'

    services:
      web:
        build: .
        ports:
          – "3000:3000"
        depends_on:
          – db
      db:
        image: mongo:latest
        volumes:
          – db-data:/data/db
        networks:
          – app-network

    volumes:
      db-data:

    networks:
      app-network:
        driver: bridge

This docker-compose.yml file:

  1. Defines two services: web (the Node.js app) and db (the MongoDB container).
  2. The depends_on directive ensures the database service starts before the web application.
  3. Uses a named volume (db-data) for persistent data storage for MongoDB.
  4. Defines a custom network (app-network) for communication between the two containers.

3.1. Start Services with Docker Compose

To start the services defined in docker-compose.yml, use the following command:

# docker-compose up -d

This command will build the web service (Node.js app), pull the MongoDB image, create the necessary containers, and run them in the background.

4. Manage Data Persistence

Containers are ephemeral by design, meaning data stored inside a container is lost when it stops or is removed. To persist data across container restarts, you’ll need to use volumes.

In the example above, the MongoDB service uses a named volume (db-data) to persist the database data. Docker volumes allow you to:

  • Persist data on the host machine outside of the container.
  • Share data between containers.

To check if the volume is created and inspect its usage, use:

# docker volume ls # docker volume inspect db-data

5. Networking Between Containers

In Docker, containers communicate with each other over a network. By default, Docker Compose creates a network for each application defined in a docker-compose.yml file. Containers within the same network can communicate with each other using container names as hostnames.

For example, in the docker-compose.yml above:

  • The web container can access the db container using db:27017 as the database URL (MongoDB's default port).

6. Scaling and Orchestrating with Docker Swarm or Kubernetes

If you need to scale your application to multiple instances or require orchestration, Docker Swarm and Kubernetes are the two most popular container orchestration platforms.

Docker Swarm:

Built into Docker, Swarm allows you to easily manage a cluster of Docker nodes and scale your containers across multiple machines. To initialize a swarm:

# docker swarm init

Kubernetes:

Kubernetes is a powerful container orchestration tool that provides high availability, automatic scaling, and management of containerized applications. If you’re migrating a more complex server environment, Kubernetes will offer additional features like rolling updates, automatic recovery, and more sophisticated networking options.

7. Security and Permissions

When migrating to Docker, it's important to pay attention to security best practices, such as:

 

  • Running containers with the least privileges (using the USER directive in the Dockerfile).
  • Using multi-stage builds to keep the image size small and reduce the attack surface.
  • Regularly scanning Docker images for known vulnerabilities using tools like Anchore, Trivy, or Clair.
  • Configuring network isolation for sensitive services.

Conclusion

Migrating a server environment into Docker containers involves more than just running an application in isolation. It requires thoughtful planning around dependencies, data persistence, networking, scaling, and security. By containerizing services with Docker, you can create portable, scalable, and consistent environments that streamline both development and production workflows.

By following the steps outlined in this guide—writing Dockerfiles, using Docker Compose for multi-container applications, and ensuring data persistence—you can successfully migrate your existing server environment into a Dockerized architecture. For larger-scale environments, consider leveraging orchestration tools like Docker Swarm or Kubernetes to manage multiple containerized services across a cluster.

How to Set Up SSH Two-Factor Authentication (2FA) on Linux Without Google Authenticator with OATH Toolkit


November 5th, 2025

install-2-factor-free-authentication-google-authentication-alternative-with-oath-toolkit-linux-logo

Most tutorials online on how to secure your SSH server with a 2 Factor Authentication 2FA will tell you to use Google Authenticator to secure SSH logins.

But what if you don’t want to depend on Google software – maybe for privacy, security, or ideological reasons ?

Luckily, you have a choice thanks to free oath toolkit.
The free and self-hosted alternative: OATH Toolkit has its own PAM module  libpam-oath to make the 2FA work  the openssh server.

OATH-Toolkit is a free software toolkit for (OTP) One-Time Password authentication using HOTP/TOTP algorithms. The software ships a small set of command line utilities covering most OTP operation related tasks.

In this guide, I’ll show you how to implement 2-Factor Authentication (TOTP) for SSH on any Linux system using OATH Toolkit, compatible with privacy-friendly authenticator apps like FreeOTP, Aegis, or and OTP.

It is worthy to check out OATH Toolkit author original post here, that will give you a bit of more insight on the tool.

1. Install the Required Packages

For Debian / Ubuntu systems:

# apt update
# apt install libpam-oath oathtool qrencode
...

For RHEL / CentOS / AlmaLinux:
 

# dnf install pam_oath oathtool

The oathtool command lets you test or generate one-time passwords (OTPs) directly from the command line.

2. Create a User Secret File

libpam-oath uses a file to store each user’s secret key (shared between your server and your phone app).

By default, it reads from:

/etc/users.oath

Let’s create it securely and set proper permissions to secure it:
 

# touch /etc/users.oath
# chmod 600 /etc/users.oath

Now, generate a new secret key for your user (replace hipo with your actual username):
 

# head -10 /dev/urandom | sha1sum | cut -c1-32

This generates a random 32-character key.
Example:

9b0e4e9fdf33cce9c76431dc8e7369fe

Add this to /etc/users.oath in the following format:

HOTP/T30 hipo - 9b0e4e9fdf33cce9c76431dc8e7369fe

HOTP/T30 means Time-based OTP with 30-second validity (standard TOTP).

Replace hipo with the Linux username you want to protect.

3. Add the Key to Your Authenticator App

Now we need to add that secret to your preferred authenticator app.

You can create a TOTP URI manually (to generate a QR code):

$ echo "otpauth://totp/hipo@jericho?secret=\
$(echo 9b0e4e9fdf33cce9c76431dc8e7369fe \
| xxd -r -p | base32)"

You can paste this URI into a QR code generator (e.g., https://qr-code-generator.com) and scan it using FreeOTP , Aegis, or any open TOTP app.
The FreeOTP Free Ap is my preferred App to use, you can install it via Apple AppStore or Google Play Store.

Alternatively, enter the Base32-encoded secret manually into your app:

# echo 9b0e4e9fdf33cce9c76431dc8e7369fe | xxd -r -p | base32

You can also use qrencode nice nifty tool to generate out of your TOTP code in ASCII mode and scan it with your Phone FreeOTP / Aegis App and add make it ready for use:

# qrencode –type=ANSIUTF8 otpauth://totp/hipo@jericho?secret=$( oathtool –verbose –totp 9b0e4e9fdf33cce9c76431dc8e7369fe –digits=6 -w 1 | grep Base32 | cut -d ' ' -f 3 )\&digits=6\&issuer=pc-freak.net\&period=30

qrencode-generation-of-scannable-QR-code-for-freeotp-or-other-TOTP-auth

qrencode will generate the code. We set the type to ANSI-UTF8 terminal graphics so you can generate this in an ssh login. It can also generate other formats if you were to incorporate this into a web interface. See the man page for qrencode for more options.
The rest of the line is the being encoded into the QR code, and is a URL of the type otpauth, with time based one-time passwords (totp). The user is “hipo@jericho“, though PAM will ignore the @jericho if you are not joined to a domain (I have not tested this with domains yet).

The parameters follow the ‘?‘, and are separated by ‘&‘.

otpauth uses a base32 hash of the secret password you created earlier. oathtool will generate the appropriate hash inside the block:

 $( oathtool –verbose –totp 9b0e4e9fdf33cce9c76431dc8e7369fe | grep Base32 | cut -d ' ' -f 3 )

We put the secret from earlier, and search for “Base32”. This line will contain the Base32 hash that we need from the output:

Hex secret: 9b0e4e9fdf33cce9c76431dc8e7369fe
Base32 secret: E24ABZ2CTW3CH3YIN5HZ2RXP
Digits: 6
Window size: 0
Step size (seconds): 30
Start time: 1970-01-01 00:00:00 UTC (0)
Current time: 2022-03-03 00:09:08 UTC (1646266148)
Counter: 0x3455592 (54875538)

368784 
From there we cut out the third field, “E24ABZ2CTW3CH3YIN5HZ2RXP“, and place it in the line.

Next, we set the number of digits for the codes to be 6 digits (valid values are 6, 7, and 8). 6 is sufficient for most people, and easier to remember.

The issuer is optional, but useful to differentiate where the code came from.

We set the time period (in seconds) for how long a code is valid to 30 seconds.

Note that: Google authenticator ignores this and uses 30 seconds whether you like it or not.

4. Configure PAM to Use libpam-oath

Edit the PAM configuration for SSH:

# vim /etc/pam.d/sshd

At the top of the file, add:

auth required pam_oath.so usersfile=/etc/users.oath window=30 digits=6

This tells PAM to check OTP codes against /etc/users.oath.

5. Configure SSH Daemon to Ask for OTP

Edit the SSH daemon configuration file:
 

# vim /etc/ssh/sshd_config

Ensure these lines are set:
 

UsePAM yes
challengeresponseauthentication yes
ChallengeResponseAuthentication yes
AuthenticationMethods publickey keyboard-interactive
##KbdInteractiveAuthentication no
KbdInteractiveAuthentication yes

N.B.! The KbdInteractiveAuthentication yes variable is necessery on OpenSSH servers with version > of version 8.2_ .

In short This setup means:
1. The user must first authenticate with their SSH key (or local / LDAP password),
2. Then enter a valid one-time code generated from TOTP App from their phone.

You can also use  Match  directives to enforce 2FA under certain conditions, but not under others.
For example, if you didn’t want to be bothered with it while you are logging in on your LAN,
but do from any other network, you could add something like:

Match Address 127.0.0.1,10.10.10.0/8,192.168.5.0/24
Authenticationmethods publickey

6. Restart SSH and Test It

Apply your configuration:
 

# systemctl restart ssh

Now, open a new terminal window and try logging in (don’t close your existing one yet, in case you get locked out):

$ ssh hipo@your-server-ip

You should see something like:

Verification code:

Enter the 6-digit code displayed in your FreeOTP (or similar) app.
If it’s correct, you’re logged in! Hooray ! 🙂

7. Test Locally and Secure the Secrets

If you want to test OTPs manually with a base32 encrypted output of hex string:

# oathtool --totp -b \
9b0e4e9fdf33cce9c76431dc8e7369fe

As above might be a bit confusing for starters, i recommend to use below few lines instead:

$ secret_hex="9b0e4e9fdf33cce9c76431dc8e7369fe"
$ secret_base32=$(echo $secret_hex | xxd -r -p | base32)
$ oathtool –totp -b "$secret_base32"
156874

You’ll get the same 6-digit code your authenticator shows – useful for debugging.

If you rerun the oathtool again you will get a difffefrent TOTP code, e.g. :

$ oathtool –totp -b "$secret_base32"
258158


Use this code as a 2FA TOTP auth code together with local user password (2FA + pass pair),  when prompted for a TOTP code, once you entered your user password first.

To not let anyone who has a local account on the system to be able to breach the 2FA additional password protection,
Ensure the secrets file is protected well, i.e.:

# chown root:root /etc/users.oath
# chmod 600 /etc/users.oath

How to Enable 2FA Only for Certain Users

If you want to force OTP only for admins, create a group ssh2fa:

# groupadd ssh2fa
# usermod -aG ssh2fa hipo

Then modify /etc/pam.d/sshd:

auth [success=1 default=ignore] pam_succeed_if.so \
user notingroup ssh2fa
auth required pam_oath.so usersfile=/etc/users.oath \
window=30 digits=6

Only users in ssh2fa will be asked for a one-time code.

Troubleshooting

Problem: SSH rejects OTP
Check /var/log/auth.log or /var/log/secure for more details.
Make sure your phone’s time is in sync (TOTP depends on accurate time).

Problem: Locked out after restart
Always keep one root session open until you confirm login works.

Problem: Everything seems configured fine but still the TOTP is not accepted by remote OpenSSHD.
– Check out the time on the Phone / Device where the TOTP code is generated is properly synched to an Internet Time Server
– Check the computer system clock is properly synchornized to the Internet Time server (via ntpd / chronyd etc.), below is sample:

  • hipo@jeremiah:~$ timedatectl status
                   Local time: Wed 2025-11-05 00:39:17 EET
               Universal time: Tue 2025-11-04 22:39:17 UTC
                     RTC time: Tue 2025-11-04 22:39:17
                    Time zone: Europe/Sofia (EET, +0200)
    System clock synchronized: yes
                  NTP service: n/a
              RTC in local TZ: no

Why Choose libpam-oath?

  • 100% Free Software (GPL)
  • Works completely offline / self-hosted
  • Compatible with any standard TOTP app (FreeOTP, Aegis, andOTP, etc.)
  • Doesn’t depend on Google APIs or cloud services
  • Lightweight (just one PAM module and a text file)

Conclusion

Two-Factor Authentication doesn’t have to rely on Google’s ecosystem.
With OATH Toolkit and libpam-oath, you get a simple, private, and completely open-source way to harden your SSH server against brute-force and stolen-key attacks.

Once configured, even if an attacker somehow steals your SSH key or password, they can’t log in without your phone’s one-time code – making your system dramatically safer.

How to Install and Use Netdata on Debian / Ubuntu Linux for Real-Time Server Monitoring


October 29th, 2025

netdata-server-monitoring-simple-tool-for-linux-bsd-windows

Monitoring system performance is one of the most overlooked aspects of server administration – until something breaks. That is absolutely true for beginners and home brew labs for learnings on how to manage servers and do basic system administration. For novice monitoring servers and infrastructure is not a big deal as usually testing machines are OK to break things. But still if you happen to host yourself some own brew websites a blog or Video streaming servers a torrent server, a tor server, some kind of public proxy or whatever of community advantageous solution for free at home, then monitoring will become important topic at some time when your small thing becomes big.

 While many sysadmins reach for Prometheus or Zabbix, using those comes with much of a complexity and effort to put in installing + setting up the overall server and agent clients as well as configure different monitoring checks.

Anyways sometimes you just need a lightweight, zero-configuration server monitoring tool that gives you instant visibility and you don’t want to learn much to have the basic and a bit of heuristic monitoring in the house.

That’s where Netdata shines.

What is Netdata?

Netdata is an open-source, real-time performance monitoring tool that visualizes CPU, memory, disk, network, and process metrics directly in your browser. It’s written in C and optimized for minimal overhead, making it perfect for both old hardware and modern VPS setups.

Netdata is built to primarly monitor different Linux OS distributions such as CentOS / RHEL / AlmaLinux / Rocky Linux / OpenSuse / Arch Linux / Amazon Linux and Oracle Linux it also has support for Windows OS as well as partially supports Mac OS and FreeBSD / OpenBSD / Dragonfly BSD and some other BSDs but some of its Linux features are not available on those.

1. Install Netdata real time performance monitoring tool


root@pcfreak:~# apt-cache show netdata|grep -i description -A3

Description-en: real-time performance monitoring (metapackage)

 Netdata is distributed, real-time, performance and health monitoring for

 systems and applications. It provides insights of everything happening on the

 systems it runs using interactive web dashboards.

Description-md5: 6843dd310958e94a27dd618821504b8e

Homepage: https://github.com/netdata/netdata

Section: net

Priority: optional

Netdata runs on most Linux distributions. On Debian or Ubuntu, installation is dead simple:

# apt update

# apt install curl -y


To be with the latest version since the default repositories provide usually older release you can use for install directly the kickstart installer from netdata.

# bash <(curl -Ss https://my-netdata.io/kickstart.sh)

This script automatically installs dependencies, sets up the Netdata daemon, and enables it as a systemd service.

Once installed, Netdata starts immediately. You can verify with:

# systemctl status netdata

2. Access the Web Dashboard


Open your browser and navigate to:

http://your-server-ip:19999/

You’ll be greeted by an intuitive dashboard showing real-time graphs of every aspect of your system — CPU load, memory usage, disk I/O, network bandwidth, and more.

If you’re running this on a public server, make sure to secure access with a firewall or reverse proxy, since by default Netdata is open to all IPs.

Example (UFW):

# ufw allow from YOUR.IP.ADDRESS.HERE to any port 19999

# ufw enable

3. Enable Persistent Storage

By default, Netdata stores only live data in memory. To retain historical data:
 

# vim /etc/netdata/netdata.conf

Find the [global] section and modify:

[global]

  history = 86400

  update every = 1

This keeps 24 hours of data at one-second resolution. You can also connect Netdata to a database backend for long-term archiving.

4. Secure with Basic Auth (Optional)

If you want simple password protection:

# apt install apache2-utils

# htpasswd -c /etc/netdata/.htpasswd admin

Then edit /etc/netdata/netdata.conf to include:

[web]

  mode = static-threaded

  default port = 19999

  allow connections from = localhost 192.168.1.*

  basic auth users file = /etc/netdata/.htpasswd

Restart Netdata:

# systemctl restart netdata

Why Netdata is Awesome 

Unlike Prometheus or Grafana, Netdata gives you instant insights without heavy setup. It’s ideal for:

  • Debugging high load or memory leaks in real time
  • Monitoring multiple VPS or embedded devices
  • Visualizing system resource usage with minimal CPU cost

And because it’s written in C, it’s insanely fast — often using less than 1% CPU on idle systems.

Final Thoughts

If you’re running any Linux server – whether for personal projects, web hosting, or experiments – Netdata is one of the easiest ways to visualize what’s happening under the hood.

You can even integrate it into your homelab or connect multiple nodes to the Netdata Cloud for centralized monitoring. And of course the full featured use and all the features of the tool are available just in the cloud version but that is absolutely normal. As the developers of netdata seems to have adopted the usual business model of providing things for free and same time selling another great things to make cash.

Netdata is really cool solution without cloud for people who needs to be able to quickly monitor like 20 or 50 servers without putting too much effort. You can simply install it across the machines and you will get a plenty of monitoring, just open each of the machines inside a separate browser tabs and take a look at what is going on once or 2 times a day. It is very old fashioned way to do monitoring but still can make sense if you don't want to bother too much with developing the monitoring or put any effort in it but still have a kind of obeservability on your mid size computer infrastructure.

So, next time your VPS feels sluggish or your load average spikes, fire up Netdata — your CPU will tell you exactly what’s wrong.

How to Install and Troubleshoot Grafana Server on Linux: Complete Step-by-Step Tutorial


October 25th, 2025

install-grafana-on-linux-logo

If you’ve ever set up monitoring for your servers or applications, you’ve probably heard about Grafana.
It’s the de facto open-source visualization and dashboard tool for time-series data — capable of turning raw metrics into beautiful and insightful charts.

In this article, I’ll walk you through how to install Grafana on Linux, configure it properly, and deal with common problems that many sysadmins hit along the way.
This guide is written with real-world experience, blending tips from the official documentation and years of self-hosting tinkering.

1. Prerequisites

You’ll need:

  • A Linux machine — Ubuntu 22.04 LTS, Debian 11+, or CentOS 8 / Rocky Linux 9.
  • A superuser or user with sudo privileges.
  • At least 512 MB of RAM and 1 CPU core (Grafana is lightweight).
  • Internet access to fetch the repository and packages.

Optionally:

  • A domain name (for example: grafana.yourdomain.com)
  • Nginx/Apache if you want to enable HTTPS later.

2. Update Your System

Before any installation, ensure your system packages are up to date:

# Debian/Ubuntu
# apt update && sudo apt upgrade -y

# or

# dnf update -y # CentOS/RHEL/Rocky

3. Install Grafana (from the Official Repository)

Grafana provides an official APT and YUM repository. Always use it to get security and feature updates.

For Debian / Ubuntu:
 

# apt install -y software-properties-common apt-transport-https wget
# wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
# echo "deb https://packages.grafana.com/oss/deb stable main" | \
# tee /etc/apt/sources.list.d/grafana.list
# apt update
# apt install grafana -y 


For CentOS / Rocky / RHEL:

# tee /etc/yum.repos.d/grafana.repo <<EOF
[grafana]
name=Grafana OSS
baseurl=https://packages.grafana.com/oss/rpm
repo_gpgcheck=1
enabled=1
gpgcheck=1
gpgkey=https://packages.grafana.com/gpg.key
EOF
# dnf install grafana -y

 

4. Start and Enable the Service

Once installation completes, start and enable Grafana to run on boot:
 

# systemctl daemon-reload
# systemctl enable grafana-server
# systemctl start grafana-server

Check status:

# systemctl status grafana-server


You should see Active: running.

5. Access the Grafana Web Interface

Grafana listens on port 3000 by default.

Open your browser and visit:

http://<your_server_ip>:3000

Login with the default credentials:

Username: admin
Password: admin

You’ll be asked to change the password — do it immediately for security.

6. Configure Grafana Basics

Configuration file location:

/etc/grafana/grafana.ini

Common settings to edit:

  • Port:

http_port = 8080

  • Root URL (for reverse proxy):

root_url = https://grafana.yourdomain.com/

  • Database: (change from SQLite to MySQL/PostgreSQL if desired)
[database]
type = mysql
host = 127.0.0.1:3306
name = grafana
user = grafana
password = supersecret_password582?255!#

Restart Grafana after making changes:

# systemctl restart grafana-server


7. Optional – Secure Grafana with HTTPS and Reverse Proxy

If Grafana is public-facing, always use HTTPS.

Install Nginx and Certbot:

# apt install nginx certbot python3-certbot-nginx -y
# certbot --nginx -d grafana.yourdomain.com

This automatically sets up SSL certificates and redirects traffic from HTTP → HTTPS.

8. Add a Data Source

Once logged in:

  1. Go to Connections → Data Sources → Add data source

  2. Choose Prometheus, InfluxDB, Loki, or your preferred backend

  3. Enter the connection URL (e.g., http://localhost:9090)

  4. Click “Save & Test”

If successful, you can start creating dashboards!

9. Troubleshooting Common Grafana Installation Issues

Even the smoothest installs sometimes go wrong.
Here are real-world fixes for typical problems sysadmins face:

Problem

Likely Cause

Fix

Service won’t start

Misconfigured grafana.ini or port in use

Run # journalctl -u grafana-server -xe to see logs. Correct syntax, change port, restart.

Port 3000 already in use

Another app (maybe NodeJS app or Jenkins)

sudo lsof -i :3000 → stop or reassign the conflicting service.

Blank login page / dashboard not loading

Browser cache or reverse proxy misconfig

Clear cache, check Nginx proxy settings (proxy_pass should point to http://localhost:3000).

APT key errors (Ubuntu 22.04+)

apt-key deprecated

Use signed-by=/usr/share/keyrings/grafana.gpg method as Grafana docs suggest.

“Bad Gateway” via proxy

Missing header forwarding

In Nginx config, ensure:

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;


“` |
| **Can’t access Grafana from LAN**

Most common reason Firewall blocking port

# ufw allow 3000/tcp


 (or adjust firewalld). 

 

10. Maintenance and Backup Tips
 

– Backup your dashboard database frequently: 
– SQLite: `/var/lib/grafana/grafana.db`
– MySQL/PostgreSQL: use your normal DB backup methods

– Watch logs regularly, e.g.: 

# journalctl -u grafana-server -f

  • Upgrade grafana safely:

# apt update && apt install grafana -y

(Always back up before upgrading!)

Conclusion

Grafana is a powerful, elegant way to visualize your system metrics, application logs, and alerts.
Installing it on Linux is straightforward — but knowing where it can fail and how to fix it is what separates a beginner from a seasoned sysadmin.

By following this guide, you not only get Grafana up and running, but also understand the moving parts behind the scenes — a perfect fit for any DIY server admin or DevOps engineer who loves keeping full control.