Skip to content

Latest commit

 

History

History

Container

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

Container Host Setup Script

1. Purpose

This script should be run on a fresh Ubuntu server installation (20.04 or newer), it sets up a secure, production-ready container host with the following features:

  • Container platform: k3s (default) or Docker CE + Swarm

  • Nginx as a reverse proxy / container router

  • SSH hardening (disables root login, enforces key auth, custom port)

  • Brute-force protection: SSHGuard and Fail2Ban

  • UFW firewall with minimal open ports

  • Certbot (optional) for automatic HTTPS via Nginx

  • Unattended upgrades and basic system hardening

At the end of the run a detailed report is generated with access details, custom ports, and service statuses.

2. Quick Start

# Download and make executable
chmod +x ubuntu-server-setup.sh

# Interactive setup (recommended)
sudo ./ubuntu-server-setup.sh

# Non-interactive setup with admin user
sudo ./ubuntu-server-setup.sh --yes --admin-user containeruser --admin-password "mypassword" --admin-key "ssh-ed25519 AAAA..."

# Preview what would be installed
sudo ./ubuntu-server-setup.sh --dry-run

3. Important Options

  • -y, --yes : Auto-confirm prompts (requires --admin-user, --admin-password, and --admin-key).

  • -n, --dry-run : Show planned actions without applying changes.

  • -r, --report-only : Generate the saved installation report.

  • --admin-user <username> : Non-root admin account to create.

  • --admin-password <password> : Password for the admin user (required for sudo).

  • --admin-key <ssh-public-key> : SSH public key for the admin user.

  • --recovery-key <ssh-public-key> : Optional recovery admin key.

4. Key Warnings (Read Carefully)

  • The script DISABLES direct root SSH login and also disables password authentication. You MUST ensure an admin user with a working SSH public key AND password is configured before the final SSH hardening step or you will be locked out.

  • In automatic mode (--yes) --admin-user, --admin-password, and --admin-key are required.

  • Keep the generated report (saved under /root/server-setup-*.report) — it contains custom ports and access details.

5. Files and Outputs

  • Script: ubuntu-server-setup.sh

  • Saved port configuration: /etc/server-ports.conf (SSH and k3s API ports)

  • Log file: /var/log/ubuntu-server-setup.log

  • Generated reports: /root/server-setup-<timestamp>.report

  • Error/debug artifacts (on failure): .ubuntu-server-setup.error and .ubuntu-server-setup.debug in the script directory

6. Features

6.1. Core Services

6.1.1. 1. Container Runtime

  • Docker CE - Latest Docker Community Edition

  • Automatic daemon configuration

  • User group management

  • Service auto-start configuration

6.1.2. 2. Container Platform (Choose One)

  • k3s - Lightweight Kubernetes with containerd runtime

  • Docker Swarm - Docker CE with Swarm orchestration

  • Security Hardening:

    • Pod Security Admission (PSA) for k3s (replaces deprecated PodSecurityPolicy)

    • Network Security Policies

    • Admission Controllers (NodeRestriction, ResourceQuota)

    • RBAC enforcement

    • Encrypted secrets at rest

6.1.3. 3. Web Server & Reverse Proxy

  • Nginx - High-performance web server

  • Container routing and load balancing

  • Reverse proxy for container services

  • SSL/TLS termination for Certbot

  • Ready for container orchestration

6.1.4. 4. Intrusion Prevention

  • Fail2Ban - Advanced intrusion prevention system

    • SSH brute-force protection

    • HTTP/HTTPS attack mitigation

    • Custom jail configurations

    • Email notifications

  • SSHGuard - Real-time SSH attack detection

    • UFW firewall integration

    • Automatic IP blocking

    • Whitelist support

6.1.5. 5. SSL Certificate Management

  • Certbot - Let’s Encrypt SSL certificates

  • Automatic certificate renewal via Nginx plugin

  • Multiple domain support

  • Automatic Nginx HTTPS configuration

  • Note: Domain must resolve to server IP and port 80 must be accessible

6.1.6. 6. System Security

  • UFW (Uncomplicated Firewall) - Simplified iptables management

  • SSH Hardening - Industry-standard security practices

  • Unattended Upgrades - Automatic security updates

6.2. Security Features

6.2.1. Port Obfuscation

  • Custom port assignment for all services

  • Non-standard ports to reduce attack surface

  • Configurable port ranges

  • Automatic conflict detection

6.2.2. SSH Hardening

  • Key-only authentication (password auth disabled)

  • Root SSH login DISABLED (PermitRootLogin no)

  • Non-root admin user with sudo access required

  • Optional recovery admin account for failsafe access

  • Custom SSH port assignment

  • Protocol version enforcement

  • Connection rate limiting

6.2.3. Firewall Configuration

  • Minimal attack surface (only required ports open)

  • Service-specific rule sets

  • Geographic IP blocking capabilities

  • DDoS protection rules

6.2.4. System Hardening

  • Kernel parameter tuning

  • File system permissions

  • Service isolation

  • Resource limitations

6.3. Monitoring and Logging

6.3.1. Comprehensive Logging

  • Centralized log management (/var/log/ubuntu-server-setup.log)

  • Structured error reporting

  • System state validation

  • Installation progress tracking

6.3.2. Error Handling

  • Detailed error reports (.ubuntu-server-setup.error)

  • Debug information collection (.ubuntu-server-setup.debug)

  • Automatic cleanup on failures

  • System state restoration

6.3.3. Reporting

  • Post-installation system reports

  • Service status validation

  • Security configuration summary

  • Port mapping documentation

7. Installation

7.1. Prerequisites

  • Ubuntu 20.04 LTS or newer

  • Minimum 2GB RAM (4GB recommended)

  • Minimum 10GB free disk space

  • Active internet connection

  • Root/sudo access

7.2. System Requirements

Component Minimum Recommended

Memory

2GB

4GB+

Disk Space

10GB free

20GB+ free

CPU Cores

1

2+

Network

100Mbps

1Gbps+

7.3. Download and Setup

# Clone the repository
git clone https://github.com/JCTRoth/Shell_Script_Utilities.git
cd Shell_Script_Utilities/Container

# Make script executable
chmod +x ubuntu-server-setup.sh

# Verify script integrity
bash -n ubuntu-server-setup.sh

8. Usage

8.1. Command Line Options

ubuntu-server-setup.sh [OPTIONS]

8.1.1. Available Options

Option Type Description

-h, --help

Flag

Show help message and exit

-v, --version

Flag

Display script version

-y, --yes

Flag

Auto-confirm all prompts (non-interactive mode)

-n, --dry-run

Flag

Preview changes without making modifications

-r, --report-only

Flag

Generate system report without installing

--verbose

Flag

Enable detailed output logging

--admin-user <username>

Parameter

Admin username for SSH access (required in auto mode)

--admin-key <key>

Parameter

SSH public key for admin user (required in auto mode)

--recovery-key <key>

Parameter

SSH public key for recovery admin (optional)

--ssh-key <key>

Parameter

DEPRECATED: Use --admin-key instead

8.2. Usage Examples

8.2.1. Interactive Installation

sudo ./ubuntu-server-setup.sh

The script will guide you through:

  1. Admin User Setup - Create non-root admin with sudo access

  2. Orchestrator Choice - Select k3s Kubernetes or Docker Swarm

  3. Port Configuration - Custom port assignment for services

  4. SSL Setup - Domain and email configuration for certificates

  5. SSH Key Management - Public key installation for admin user

  6. Recovery Admin - Optional failsafe admin account

8.2.2. Non-Interactive Installation

sudo ./ubuntu-server-setup.sh --yes --admin-user containeruser --admin-key "ssh-ed25519 AAAA..."

Uses default settings but requires admin user and SSH key.

8.2.3. Full Automated Setup with Recovery Admin

sudo ./ubuntu-server-setup.sh --yes \
    --admin-user containeruser \
    --admin-key "ssh-ed25519 AAAA... primary@host" \
    --recovery-key "ssh-rsa BBBB... recovery@vault"

8.2.4. Preview Mode (Dry Run)

sudo ./ubuntu-server-setup.sh --dry-run

Shows what would be installed/configured without making changes.

8.2.5. Report Generation

sudo ./ubuntu-server-setup.sh --report-only

Generates comprehensive system report (requires previous installation).

8.3. Installation Wizard

The interactive wizard guides you through:

  1. Welcome and System Check

    • Root permission verification

    • Ubuntu version validation

    • System requirements check

  2. Admin User Configuration

    • Username selection (non-root)

    • SSH key installation

    • Optional recovery admin setup

  3. Orchestrator Selection

    • k3s (Lightweight Kubernetes) - Recommended

    • Docker Swarm - Simpler multi-node clustering

  4. Port Configuration

    • SSH port assignment (default: 2222)

    • k3s API port (default: 6443)

    • Custom port ranges

    • Conflict detection

  5. SSL Certificate Setup

    • Domain name configuration

    • Email for Let’s Encrypt notifications

    • Certificate type selection

  6. Service Configuration Review

    • Component selection confirmation

    • Configuration summary

    • Final installation approval

9. Configuration

9.1. Port Configuration

The script uses a configuration file (/etc/server-ports.conf) to manage port assignments:

# Server Port Configuration
SSH_PORT=2222
K3S_API_PORT=6443
DOCKER_PORT=2376
CERTBOT_HTTP_PORT=80
CERTBOT_HTTPS_PORT=443

9.1.1. Port Ranges

  • SSH: 1024-65535 (avoiding well-known ports)

  • k3s API: 6443-6453 (Kubernetes standard range)

  • Docker: 2376-2386 (Docker TLS range)

9.2. Service Configuration

9.2.1. Nginx Configuration

Location: /etc/nginx/sites-available/container-router

server {
    listen 80 default_server;
    server_name _;

    # Default landing page
    location / {
        root /var/www/html;
        index index.html;
    }

    # Example: Route to container service
    location /myapp {
        proxy_pass http://localhost:8080;
        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;
    }

    # Health check endpoint
    location /health {
        return 200 "healthy\n";
    }
}

Nginx Features:

  • Reverse proxy for container services

  • Load balancing capabilities

  • SSL/TLS termination (configured automatically by Certbot)

  • HTTP/2 support

  • Container routing template ready for customization

Adding Container Routes:

# Edit the Nginx configuration
sudo nano /etc/nginx/sites-available/container-router

# Test configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx

9.2.2. Docker Configuration

Location: /etc/docker/daemon.json

{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2",
  "exec-opts": ["native.cgroupdriver=systemd"]
}

9.2.3. k3s Configuration

Location: /etc/systemd/system/k3s.service.d/override.conf

[Service]
ExecStart=
ExecStart=/usr/local/bin/k3s server \
  --kube-apiserver-arg=audit-log-path=/var/log/k3s-audit.log \
  --kube-apiserver-arg=audit-policy-file=/var/lib/rancher/k3s/server/audit-policy.yaml \
  --kube-apiserver-arg=enable-admission-plugins=NodeRestriction,ResourceQuota \
  --https-listen-port=${K3S_API_PORT}

9.2.4. Fail2Ban Configuration

Location: /etc/fail2ban/jail.local

[sshd]
enabled = true
port = ${SSH_PORT}
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600

9.3. Environment Variables

Variable Default Description

SCRIPT_NAME

ubuntu-server-setup.sh

Script filename

SCRIPT_VERSION

1.0

Current script version

LOG_FILE

/var/log/ubuntu-server-setup.log

Primary log file location

ERROR_FILE

.ubuntu-server-setup.error

Error report file

DEBUG_FILE

.ubuntu-server-setup.debug

Debug information file

10. Security

10.1. Security Model

The script implements a defense-in-depth security model with multiple layers:

  1. Root Access Isolation (No direct root SSH - sudo elevation only)

  2. Network Security (UFW Firewall + Port Obfuscation)

  3. Access Control (SSH Hardening + Key-based Auth)

  4. Intrusion Prevention (Fail2Ban + SSHGuard)

  5. Container Security (k3s Hardening + PSP)

  6. System Security (Kernel Hardening + Updates)

10.2. Root Access Security

Important
Direct root SSH login is DISABLED (PermitRootLogin no).

10.2.1. Security Model

┌──────────────────────────────────────────────────────────┐
│                    SSH CONNECTION                        │
│                    (Key-based only)                      │
└────────────────────────┬─────────────────────────────────┘
                         │
                         ▼
┌──────────────────────────────────────────────────────────┐
│                    ADMIN USER                            │
│                 (e.g., containeruser)                    │
│              - Container management                      │
│              - System monitoring                         │
│              - Limited user operations                   │
└────────────────────────┬─────────────────────────────────┘
                         │
                         ▼ sudo -i / sudo <command>
┌──────────────────────────────────────────────────────────┐
│                    ROOT ACCESS                           │
│              (Via sudo elevation only)                   │
│              - System administration                     │
│              - Security configuration                    │
│              - Service management                        │
└──────────────────────────────────────────────────────────┘

10.2.2. Access Methods

# Connect as admin user
ssh -p <SSH_PORT> admin_username@server_ip

# Run single command as root
sudo apt update

# Get full root shell
sudo -i

# Switch to root (alternative)
sudo su -

10.2.3. Recovery Admin Account

An optional secondary admin account provides failsafe access if the primary admin account is compromised or SSH key is lost.

  • Uses a different SSH key stored securely offline

  • Same sudo privileges as primary admin

  • Should only be used for recovery scenarios

10.3. SSH Hardening Checklist

Item Configuration Status

Password Authentication

Disabled

✓

Root Login

Disabled (PermitRootLogin no)

✓

Protocol Version

SSH-2 Only

✓

Port

Custom (Non-22)

✓

Key Authentication

RSA/ED25519

✓

Connection Rate Limiting

MaxAuthTries=3

✓

10.4. Firewall Rules

10.4.1. Default Policy

  • Incoming: DENY (whitelist approach)

  • Outgoing: ALLOW (with monitoring)

  • Routed: DENY

10.4.2. Open Ports

Port Service Access

Custom SSH

SSH Server

Admin only

80

HTTP (Certbot)

Public (temporary)

443

HTTPS

Public

Custom k3s

Kubernetes API

Cluster only

10.5. Certificate Management

10.5.1. Let’s Encrypt Integration

  • Automatic certificate generation

  • 90-day renewal automation

  • Multi-domain support (SAN certificates)

  • HTTP-01 and DNS-01 challenge support

10.5.2. Certificate Storage

  • Location: /etc/letsencrypt/live/

  • Backup: Automatic to /etc/letsencrypt/archive/

  • Permissions: Root only (600)

10.6. Monitoring and Alerting

10.6.1. Log Monitoring

  • Auth Logs: /var/log/auth.log (SSH attempts)

  • System Logs: /var/log/syslog (system events)

  • Application Logs: /var/log/ubuntu-server-setup.log (script events)

10.6.2. Fail2Ban Monitoring

  • Real-time IP blocking

  • Email notifications (configurable)

  • Whitelist management

  • Automatic unban after timeout

11. Troubleshooting

11.1. Common Issues

11.1.1. Script Fails to Start

# Check script permissions
ls -la ubuntu-server-setup.sh

# Verify syntax
bash -n ubuntu-server-setup.sh

# Check system requirements
df -h /
free -h

11.1.2. Port Conflicts

# Check port usage
ss -tuln | grep :2222

# Find process using port
lsof -i :2222

# Kill conflicting process
sudo systemctl stop <service>

11.1.3. k3s Installation Failures

Port Conflict with SSH:

If k3s fails to start with "service did not take the steps required", check for port conflicts:

# Check k3s service status
sudo systemctl status k3s
sudo journalctl -xeu k3s.service

# Check port configuration
cat /etc/server-ports.conf

# If k3s port conflicts with SSH port, fix it:
sudo nano /etc/server-ports.conf
# Change: K3S_API_PORT=4444 (wrong - conflicts with SSH)
# To:     K3S_API_PORT=6443 (correct - default k3s port)

# Uninstall failed k3s installation
sudo /usr/local/bin/k3s-uninstall.sh

# Re-run the setup script
sudo ./ubuntu-server-setup.sh

Common k3s Issues:

  • Port 6443 already in use → Change K3S_API_PORT in config

  • Insufficient memory → Need at least 2GB RAM for k3s

  • Network issues → Check firewall allows k3s ports

  • SELinux blocking → Usually not an issue on Ubuntu

11.1.4. Service Startup Issues

# Check service status
systemctl status docker k3s sshguard fail2ban

# View service logs
journalctl -u docker -f
journalctl -u k3s -f

11.1.5. SSL Certificate Issues

Why certificates might not be obtained during setup:

  • DNS not configured: Domain must resolve to your server IP before certificates can be obtained

  • Port 80 blocked: Certificate validation requires port 80 to be accessible from the internet

  • Timing: DNS changes can take time to propagate (up to 24-48 hours)

# Check if domain resolves to your server
dig +short yourdomain.com

# Test certificate obtaining manually
sudo certbot certonly --standalone -d yourdomain.com

# Test certificate renewal
sudo certbot renew --dry-run

# Check certificate status
sudo certbot certificates

11.2. Error Recovery

11.2.1. SSH Service Failure Recovery

If the setup report shows "SSH service is not running", your server may be inaccessible:

# Access server via console/VNC/KVM/cloud console
sudo -i

# Check SSH service status
systemctl status sshd
systemctl status ssh

# Try to start SSH service
systemctl start sshd
# or
systemctl start ssh

# If that fails, check configuration
sshd -t  # Test SSH config syntax

# Check logs for errors
journalctl -u sshd -n 50
journalctl -u ssh -n 50

# Fix common issues:
# 1. Port conflict (check if port is in use)
netstat -tlnp | grep :${SSH_PORT}
# 2. Configuration error (restore backup)
cp /etc/ssh/sshd_config.backup.* /etc/ssh/sshd_config
systemctl restart sshd

11.2.2. SSH Lockout Recovery

IMPORTANT: If you lose SSH access, use one of these recovery methods:

Option 1: Recovery Admin Account

# If recovery admin was configured during setup
ssh -p <SSH_PORT> recovery_admin@server_ip
sudo -i

Option 2: Console Access

# Access server via physical console, KVM, or cloud provider console
# Then temporarily re-enable root login:

sudo nano /etc/ssh/sshd_config
# Change: PermitRootLogin no
# To:     PermitRootLogin yes
sudo systemctl restart sshd

# After fixing the issue, disable root login again:
sudo nano /etc/ssh/sshd_config
# Change: PermitRootLogin yes
# To:     PermitRootLogin no
sudo systemctl restart sshd

Option 3: Single User Mode (Physical Access)

# Boot into recovery mode
# Mount filesystem read-write
mount -o remount,rw /
# Edit sshd_config as needed
nano /etc/ssh/sshd_config
# Reboot
reboot

11.2.3. Automatic Recovery

The script includes comprehensive error handling:

  • Error Detection: Traps all errors with detailed reporting

  • State Validation: Pre and post-installation checks

  • Automatic Cleanup: Removes partial installations on failure

  • Service Recovery: Restores services to known-good states

11.2.4. Manual Recovery

If automatic recovery fails:

# Check error files
cat .ubuntu-server-setup.error
cat .ubuntu-server-setup.debug

# Reset services
sudo systemctl stop docker k3s sshguard fail2ban
sudo systemctl reset-failed

# Reset firewall
sudo ufw --force reset
sudo ufw enable

# Remove k3s completely
sudo /usr/local/bin/k3s-uninstall.sh

11.3. Debug Mode

Enable verbose logging for troubleshooting:

sudo ./ubuntu-server-setup.sh --verbose --dry-run

This provides: * Detailed command execution logs * System state information * Configuration file contents * Service status details

11.4. Log Analysis

11.4.1. Primary Log File

# View installation log
tail -f /var/log/ubuntu-server-setup.log

# Search for errors
grep "ERROR" /var/log/ubuntu-server-setup.log

# Filter by timestamp
grep "2025-12-14" /var/log/ubuntu-server-setup.log

11.4.2. Error Report Analysis

# View latest error report
cat .ubuntu-server-setup.error

# Check system state at time of error
cat .ubuntu-server-setup.debug
11.4.2.1. Installed Services
Service Port Purpose Dependencies

Docker CE

2376

Container Runtime

containerd, runc

k3s

6443

Kubernetes

containerd, CNI plugins

Fail2Ban

N/A

Intrusion Prevention

iptables, systemd

SSHGuard

N/A

SSH Protection

ufw, iptables

UFW

N/A

Firewall

iptables, netfilter

Certbot

80/443

SSL Certificates

python3, nginx/apache

12.1. Container Management Scripts

The Container/ directory includes additional Docker and Kubernetes management utilities:

12.1.1. Docker Utilities

  • Docker/remove_dengling_images.sh - Cleanup unused Docker images

  • Docker/stop_and_remove_all.sh - Complete Docker environment reset

12.1.2. Kubernetes Utilities

  • Kubernetes/delete_all_pods.sh - Emergency pod cleanup for k3s

12.2. System Administration Scripts

12.2.1. Backup and Restore

  • Backup_Tools/Backup_and_Restore_Sources/ - Package source management

  • Backup_Tools/Backup_Folder/ - Filesystem backup utilities

12.2.2. Package Management

  • List_Installation/ - Advanced package list management system

  • Program_Setups/ - Automated program installation scripts

12.2.3. System Monitoring

  • Generate_System_Logs/ - Comprehensive system reporting

  • System_Configurations/ - System optimization scripts

12.2.4. Security Tools

  • Other_Systems/Android/adb_bloatware_remover/ - Android device security

  • rulesD_Problems/ - udev rules and hardware access fixes

12.3. Integration Examples

12.3.1. Backup Before Installation

# Backup package sources
cd ../Backup_Tools/Backup_and_Restore_Sources
sudo ./Backup_Source_and_Key.sh

# Run server setup
cd ../../Container
sudo ./ubuntu-server-setup.sh

12.3.2. Post-Installation Package Management

# Install additional development tools
cd ../List_Installation
sudo ./install_list.sh lists/developer.list

# Add custom packages
sudo ./add_pack.sh lists/server.list

12.3.3. System Monitoring Setup

# Generate baseline system report
cd ../Generate_System_Logs
sudo ./Generate_Compact_System_Status.sh

# Configure system optimizations
cd ../System_Configurations
sudo ./configure-unattended-upgrades/configure-unattended-upgrades.sh