Blog
05 · Linux World & Server TerminalPart 0220 min read

Authoring Systemd Services, SSH Hardening, and Nginx Reverse Proxy Setup

Run your compiled .NET Web API or Node.js app as a self-healing 24/7 background daemon on Linux. Includes the complete production directory tree, /etc/systemd/system unit file, SSH Ed25519 hardening, and Nginx TLS 1.3 Reverse Proxy configuration.

Emirhan Uluksar
Emirhan Uluksar

Founder & Principal Software Architect · Digital HAT

0 views
Authoring Systemd Services, SSH Hardening, and Nginx Reverse Proxy Setup

Welcome back! In Part 1 of our Linux & Server Administration series, we explored the Linux Kernel, the root filesystem hierarchy (/etc, /var, /opt, /proc), and 25 essential terminal commands. Now we arrive at the milestone every software engineer faces when deploying to production for the first time: "I compiled my application and copied it to my Linux server; when I run dotnet DigitalHat.Api.dll in my SSH terminal it works, but the moment I close my terminal window, my entire website goes offline!"

In enterprise production environments, applications are never run manually inside an interactive shell. Instead, we engineer a three-pillar production stack that automatically boots on server startup, self-heals within 3 seconds if a process crashes, enforces strict memory limits, and terminates HTTPS traffic at the edge: Systemd + Nginx Reverse Proxy + Hardened SSH.

What We Will Build From Scratch in This Masterclass:
1. The exact production Linux directory and file tree showing where binaries, systemd units, environment secrets, and SSL certificates live.
2. Line-by-line authoring of /etc/systemd/system/digitalhat-api.service with non-root sandboxing and automatic crash recovery.
3. A complete Nginx Reverse Proxy virtual host (/etc/nginx/sites-available/dgtalhat.com.conf) forwarding external 443 (HTTPS / TLS 1.3) traffic to internal Kestrel (127.0.0.1:5000) and Next.js (127.0.0.1:3000) daemons.
4. SSH Ed25519 cryptographic hardening inside /etc/ssh/sshd_config to eliminate brute-force password attacks.
Linux Systemd Daemon, SSH Hardening and Nginx Reverse Proxy Architecture

1. The Complete Production Linux Directory Tree

A common beginner mistake is placing application binaries inside /root or /home/ubuntu and running them as root. On a clean Ubuntu 24.04 LTS production server, our files follow the Linux Filesystem Hierarchy Standard (FHS) with strict ownership:

/ (Linux Production Server Root)
├── etc/
│   ├── ssh/
│   │   └── sshd_config                          # Hardened SSH daemon configuration (Password auth disabled)
│   ├── systemd/
│   │   └── system/
│   │       ├── digitalhat-api.service           # .NET 9 Web API systemd service unit
│   │       └── digitalhat-web.service           # Next.js SSR frontend systemd service unit
│   ├── nginx/
│   │   ├── nginx.conf                           # Core Nginx worker processes, gzip, and buffer limits
│   │   ├── sites-available/
│   │   │   └── dgtalhat.com.conf                # Reverse Proxy & TLS 1.3 virtual host configuration
│   │   └── sites-enabled/
│   │       └── dgtalhat.com.conf -> ../sites-available/dgtalhat.com.conf
│   └── letsencrypt/
│       └── live/dgtalhat.com/
│           ├── fullchain.pem                    # Let's Encrypt TLS certificate chain
│           └── privkey.pem                      # TLS private key (chmod 600)
│
├── opt/
│   └── digitalhat/
│       ├── api/                                 # Published .NET 9 release binaries
│       │   ├── DigitalHat.Api.dll
│       │   └── appsettings.Production.json
│       ├── web/                                 # Next.js standalone build output
│       │   └── server.js
│       └── env/
│           └── api.env                          # Database credentials & JWT secrets (chmod 640, root:dhservice)
│
└── var/
    └── log/
        ├── nginx/
        │   ├── dgtalhat.access.log
        │   └── dgtalhat.error.log
        └── journal/                             # Persistent binary systemd logs queried via journalctl

2. Step 1: Creating an Isolated Non-Root Service User (dhservice)

Never execute a web-facing process as root. If an attacker discovers a vulnerability in a third-party dependency, running as root grants them instant control over the entire operating system. Instead, we provision a locked-down system account with no interactive login shell (/usr/sbin/nologin):

# 1. Create a dedicated system user with no home directory and no interactive shell
sudo useradd --system --no-create-home --shell /usr/sbin/nologin dhservice

# 2. Create the deployment directories and assign ownership to dhservice
sudo mkdir -p /opt/digitalhat/api /opt/digitalhat/env
sudo chown -R dhservice:dhservice /opt/digitalhat/api

# 3. Store production secrets in an isolated environment file readable ONLY by root and dhservice (chmod 640)
sudo tee /opt/digitalhat/env/api.env > /dev/null <<'EOF'
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_URLS=http://127.0.0.1:5000
ConnectionStrings__PostgreSQL=Host=127.0.0.1;Port=5432;Database=dh_prod;Username=dh_user;Password=StrongProdSecret_2026!
JwtOptions__SecretKey=Cryptographic64CharProductionSigningKey_9f8e7d6c5b4a3f2e1d0c
EOF

sudo chown root:dhservice /opt/digitalhat/env/api.env
sudo chmod 640 /opt/digitalhat/env/api.env

3. Step 2: Authoring the Systemd Unit File (digitalhat-api.service)

Now we instruct Systemd how to launch our .NET 9 Web API, where to load its environment variables from, how to automatically restart it on failure, and which kernel sandboxing flags to enforce:

# File Path: /etc/systemd/system/digitalhat-api.service
[Unit]
Description=Digital HAT Enterprise .NET 9 Web API Daemon
Documentation=https://dgtalhat.com
# Wait until networking and local PostgreSQL are fully online before starting:
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
Type=notify
# Execute under our unprivileged system user, NEVER root:
User=dhservice
Group=dhservice
WorkingDirectory=/opt/digitalhat/api
ExecStart=/usr/bin/dotnet /opt/digitalhat/api/DigitalHat.Api.dll

# Load secrets from our chmod 640 environment file:
EnvironmentFile=/opt/digitalhat/env/api.env
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
Environment=DOTNET_gcServer=1

# SELF-HEALING: Automatically restart within 3 seconds if the process exits or crashes
Restart=always
RestartSec=3
KillSignal=SIGINT
TimeoutStopSec=30

# RESOURCE & KERNEL SANDBOXING:
LimitNOFILE=65535
MemoryMax=1536M
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true

SyslogIdentifier=digitalhat-api

[Install]
WantedBy=multi-user.target

Activate and verify the daemon using these four commands:

sudo systemctl daemon-reload                  # Reload unit definitions from disk
sudo systemctl enable digitalhat-api.service  # Enable automatic startup on server boot
sudo systemctl start digitalhat-api.service   # Start the daemon immediately
sudo systemctl status digitalhat-api.service  # Inspect live PID, memory footprint, and health

4. Step 3: Why We Place Nginx in Front of Kestrel (Reverse Proxy Architecture)

Notice that we bound Kestrel to http://127.0.0.1:5000 (the local loopback interface). No external packet can reach port 5000 directly. All public traffic enters through Nginx on ports 80 and 443:

Responsibility Nginx Reverse Proxy Edge (Ports 80 / 443) Application Server (Kestrel / Node on 127.0.0.1)
TLS 1.3 Termination Handles SSL handshakes, OCSP stapling, and HTTP/2 multiplexing in native C. Communicates over zero-overhead local HTTP loopback.
Path & Host Routing Routes /api/* to 127.0.0.1:5000 (.NET) and /* to 127.0.0.1:3000 (Next.js). Focuses strictly on domain execution.
Slowloris & Buffer Defense Buffers slow client uploads before handing complete requests to Kestrel. Thread pool is never starved by slow mobile connections.

Production Nginx Virtual Host (/etc/nginx/sites-available/dgtalhat.com.conf)

# 1. Permanently redirect all HTTP (Port 80) traffic to HTTPS (Port 443)
server {
    listen 80;
    listen [::]:80;
    server_name dgtalhat.com www.dgtalhat.com;
    return 301 https://dgtalhat.com$request_uri;
}

# 2. Primary HTTPS (Port 443) Reverse Proxy Server
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name dgtalhat.com;

    ssl_certificate     /etc/letsencrypt/live/dgtalhat.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/dgtalhat.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    # Enterprise Security Response Headers
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    client_max_body_size 10M;

    # Proxy /api/ traffic to .NET 9 Kestrel (127.0.0.1:5000)
    location /api/ {
        proxy_pass         http://127.0.0.1:5000/api/;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        # Forward the real client IP so ASP.NET Core RateLimiter partitions accurately:
        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_cache_bypass $http_upgrade;
    }

    # Proxy all other traffic to Next.js SSR (127.0.0.1:3000)
    location / {
        proxy_pass         http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection 'upgrade';
        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;
    }
}

Always validate syntax with sudo nginx -t before applying changes seamlessly via sudo systemctl reload nginx.

5. Step 4: Cryptographic SSH Hardening (/etc/ssh/sshd_config)

Every public IP on port 22 receives thousands of automated dictionary attacks daily. Generate an Ed25519 key pair on your workstation, copy the public key to the server, and disable password authentication completely:

# On your local workstation:
ssh-keygen -t ed25519 -C "emirhan@dgtalhat.com"
ssh-copy-id -i ~/.ssh/id_ed25519.pub dhadmin@81.214.126.122

# Six golden rules in /etc/ssh/sshd_config on the server:
Port 52329                              # Move SSH off port 22 to drop 99% of automated scanner noise
PermitRootLogin no                      # Forbid direct root SSH login
PasswordAuthentication no               # Disable cleartext password authentication completely
PubkeyAuthentication yes                # Require Ed25519/RSA cryptographic key authentication
MaxAuthTries 3                          # Disconnect after 3 failed handshakes
AllowUsers dhadmin                      # Explicitly whitelist authorized administrative accounts

6. Summary

You now have a hardened, self-healing Linux production environment running your applications under isolated system accounts via Systemd, fronted by Nginx Reverse Proxy with TLS 1.3, and secured with Ed25519 SSH keys.

Did you find this engineering guide helpful?

Give it a like or share it with your team and network.

0 views
Share This Guide: