Okay, here’s a comprehensive article on Ubuntu Server Basics, aiming for approximately 5000 words:
Ubuntu Server Basics: A Complete Introduction
Ubuntu Server is one of the most popular Linux distributions for servers, powering everything from small home servers to massive cloud deployments. Its popularity stems from its ease of use, strong community support, extensive software repositories, and the backing of Canonical, a company dedicated to its development and maintenance. This article provides a complete introduction to the basics of Ubuntu Server, covering everything you need to get started.
1. What is Ubuntu Server?
Ubuntu Server is a variant of the Ubuntu operating system, specifically designed for server environments. Unlike the desktop version, it doesn’t include a graphical user interface (GUI) by default. This is intentional, as a GUI consumes valuable system resources (CPU, RAM, and disk space) that are better utilized for server tasks. Instead, Ubuntu Server is managed primarily through the command-line interface (CLI), also known as the terminal or shell.
Key Differences from Ubuntu Desktop:
- No GUI: The most significant difference. This reduces overhead and improves performance.
- Optimized for Server Tasks: The default installation includes packages and configurations tailored for server roles, such as web servers, database servers, and file servers.
- Long-Term Support (LTS) Releases: Ubuntu offers LTS releases, which receive security updates and bug fixes for five years (or even ten years with Extended Security Maintenance – ESM), making them ideal for stable, long-running server deployments.
- Focus on Security: Ubuntu Server emphasizes security by default, with features like AppArmor (a mandatory access control system) and regular security updates.
- Minimal Installation: The default installation is minimal, allowing you to add only the necessary packages, reducing the attack surface and improving resource utilization.
Why Choose Ubuntu Server?
- Open Source and Free: Ubuntu Server is free to use and distribute, reducing licensing costs. The open-source nature allows for transparency and community contributions.
- Large Community and Extensive Documentation: A vast and active community provides support forums, tutorials, and readily available solutions to common problems. The official Ubuntu documentation is comprehensive and well-maintained.
- Vast Software Repositories: Ubuntu’s package management system (APT) provides access to a massive repository of pre-built software packages, making it easy to install and manage applications.
- Easy to Learn and Use: While command-line proficiency is essential, Ubuntu’s package management and configuration are relatively straightforward, making it accessible to beginners.
- Scalability: Ubuntu Server can scale from small single-server deployments to large, complex cloud infrastructures.
- Regular Updates and Security Patches: Canonical provides regular updates and security patches, ensuring your server remains secure and up-to-date.
- Support for Virtualization and Containerization: Ubuntu Server works seamlessly with virtualization technologies like KVM, Xen, and VMware, and containerization platforms like Docker and LXD.
2. Installation
There are several ways to install Ubuntu Server:
- Downloadable ISO Image: The most common method. You download an ISO image from the official Ubuntu website (ubuntu.com/download/server) and create a bootable USB drive or DVD.
- Cloud Images: Major cloud providers (AWS, Azure, Google Cloud, etc.) offer pre-built Ubuntu Server images, making it easy to launch instances in the cloud.
- Network Installation (PXE Boot): For deploying multiple servers, you can set up a PXE boot server to install Ubuntu Server over the network.
- MAAS (Metal as a Service): For bare-metal provisioning.
Step-by-Step Installation (using ISO Image):
- Download the ISO: Download the latest LTS release of Ubuntu Server from the official website.
- Create Bootable Media: Use a tool like Rufus (Windows), Etcher (cross-platform), or
dd
(Linux) to create a bootable USB drive or burn the ISO to a DVD. - Boot from Media: Insert the USB drive or DVD into the server and boot from it. You may need to adjust the BIOS/UEFI settings to change the boot order.
- Select Installation Language: Choose your preferred language.
- Choose “Install Ubuntu Server”: Select this option from the boot menu.
- Configure Keyboard Layout: Select your keyboard layout.
- Network Configuration:
- DHCP (Automatic): If your network has a DHCP server, the installer will automatically obtain an IP address, subnet mask, gateway, and DNS server settings.
- Static IP: If you need to assign a static IP address, you’ll need to manually enter the IP address, subnet mask, gateway, and DNS server addresses. It’s generally recommended to use static IPs for servers.
- Proxy Configuration (Optional): If you need to use a proxy server to access the internet, enter the proxy details.
- Configure Ubuntu Archive Mirror: Choose a mirror close to your location for faster downloads.
- Storage Configuration: This is a crucial step. You have several options:
- Use Entire Disk: The installer will erase the entire disk and create a default partition layout. This is the simplest option for beginners.
- Manual Partitioning: Allows you to create custom partitions and filesystems. This is recommended for advanced users who have specific requirements. You can choose between different filesystem types like ext4 (default), XFS, Btrfs, and ZFS.
- LVM (Logical Volume Manager): Provides flexibility for managing storage. LVM allows you to create logical volumes that can be resized, moved, and snapshotted without affecting the underlying physical disks. Recommended for more complex setups.
- Profile Setup:
- Username: Create a username for your primary user account. This user will have
sudo
privileges (explained later). - Password: Choose a strong password.
- Hostname: Enter a hostname for your server (e.g.,
myserver
,webserver1
). - Import SSH Identity (Optional): You can import you SSH key from Github or Launchpad.
- Username: Create a username for your primary user account. This user will have
- Featured Server Snaps: Select any featured server snap to be installed. Common options include, Docker, AWS CLI, Nextcloud.
- Installation Process: The installer will now copy files and install the system. This may take some time.
- Reboot: Once the installation is complete, the system will prompt you to reboot. Remove the installation media before rebooting.
- Login: After rebooting, you’ll be presented with a login prompt. Enter the username and password you created during the installation.
3. Basic Command-Line Interface (CLI) Usage
Once you’ve logged in, you’ll be interacting with the server primarily through the command-line interface. Here are some fundamental concepts and commands:
- Shell: The shell is a program that interprets your commands and interacts with the operating system. The default shell in Ubuntu Server is Bash (Bourne Again SHell).
- Prompt: The prompt is a line of text that indicates the shell is ready to accept commands. It typically includes your username, hostname, and current working directory (e.g.,
user@hostname:~$
). - Commands: Commands are instructions you give to the shell. They consist of the command name followed by optional arguments and options.
- Arguments: Arguments provide additional information to the command, specifying what to operate on (e.g., a filename).
- Options: Options modify the behavior of the command. They typically start with a hyphen (
-
) or double hyphen (--
). - Case Sensitivity: The Linux command line is case-sensitive.
ls
is different fromLS
. - Tab Completion: Press the Tab key to auto-complete commands, filenames, and directory names. This saves typing and reduces errors.
- Command History: Use the up and down arrow keys to cycle through previously executed commands.
- Man Pages: Use the
man
command to access the manual pages for a command (e.g.,man ls
). Man pages provide detailed information about the command’s usage, options, and arguments. Pressq
to exit the man page.
Essential Commands:
ls
(list): Lists the contents of a directory.ls -l
: Lists files in long format, showing permissions, ownership, size, and modification date.ls -a
: Lists all files, including hidden files (files starting with a dot).ls -lh
: Lists files in long format with human-readable sizes (e.g., 1K, 234M, 2G).
cd
(change directory): Changes the current working directory.cd /path/to/directory
: Changes to the specified directory.cd ..
: Moves up one directory level.cd ~
: Changes to your home directory.cd -
: Changes to the previous directory.
pwd
(print working directory): Displays the current working directory.mkdir
(make directory): Creates a new directory.mkdir new_directory
: Creates a directory named “new_directory”.
rmdir
(remove directory): Removes an empty directory.rmdir empty_directory
: Removes the directory named “empty_directory”.
rm
(remove): Removes files or directories.rm filename
: Removes the specified file.rm -r directory
: Recursively removes a directory and its contents (use with caution!).rm -f filename
: Forces removal without prompting for confirmation (use with caution!).rm -rf directory
: Recursively and forcefully removes a directory and its contents (use with extreme caution!).
cp
(copy): Copies files or directories.cp source_file destination_file
: Copies “source_file” to “destination_file”.cp -r source_directory destination_directory
: Recursively copies a directory.
mv
(move): Moves or renames files or directories.mv source_file destination_file
: Moves “source_file” to “destination_file” (or renames it if the destination is in the same directory).mv source_directory destination_directory
: Moves a directory.
touch
: Creates an empty file or updates the modification time of an existing file.touch new_file
: Creates an empty file named “new_file”.
cat
(concatenate): Displays the contents of a file.cat filename
: Displays the contents of “filename”.
less
: Displays the contents of a file one page at a time (useful for large files).less filename
: Displays “filename” one page at a time. Use arrow keys, Page Up/Down, andq
to quit.
head
: Displays the first few lines of a file.head filename
: Displays the first 10 lines of “filename”.head -n 20 filename
: Displays the first 20 lines.
tail
: Displays the last few lines of a file.tail filename
: Displays the last 10 lines of “filename”.tail -n 20 filename
: Displays the last 20 lines.tail -f filename
: Continuously displays new lines as they are added to the file (useful for monitoring log files).
grep
(global regular expression print): Searches for lines in a file that match a pattern.grep "search_term" filename
: Searches for “search_term” in “filename”.grep -i "search_term" filename
: Performs a case-insensitive search.grep -v "search_term" filename
: Displays lines that do not match “search_term”.
find
: Searches for files and directories based on various criteria.find /path/to/search -name "*.txt"
: Finds all files ending in “.txt” within the specified path.
sudo
(superuser do): Executes a command with root (administrator) privileges. This is crucial for many administrative tasks.sudo apt update
: Updates the package lists (requires root privileges).
apt
(Advanced Package Tool): Ubuntu’s package manager. Used to install, remove, and update software packages.sudo apt update
: Updates the local package lists. Always run this before installing or upgrading packages.sudo apt upgrade
: Upgrades all installed packages to their latest versions.sudo apt install package_name
: Installs the specified package.sudo apt remove package_name
: Removes the specified package.sudo apt autoremove
: Removes packages that were automatically installed as dependencies and are no longer needed.sudo apt search package_name
: Searches for packages matching the given name.
systemctl
: Manages system services (daemons).sudo systemctl start service_name
: Starts a service.sudo systemctl stop service_name
: Stops a service.sudo systemctl restart service_name
: Restarts a service.sudo systemctl enable service_name
: Enables a service to start automatically at boot.sudo systemctl disable service_name
: Disables a service from starting automatically at boot.sudo systemctl status service_name
: Checks the status of a service.
shutdown
: Shuts down or reboots the system.
*sudo shutdown now
: Shutdown the system immediately.sudo shutdown -r now
: Reboot the system immediately.sudo shutdown -h +60
: Shutdown in 60 minutes.
reboot
: Reboots the server immediately.sudo reboot
whoami
: Displays the currently logged in user.uname
: Print system information.uname -a
: print all information.
df
: Report file system disk space usage.df -h
: Display sizes in human-readable form.
du
: Estimate file space usage.du -sh /path/to/dir
: Summarize disk usage of a directory in human-readable form.
free
: Display amount of free and used memory in the system.free -h
: Show memory amount in human readable format.
top
: Display dynamic real-time view of running processes.ps
: Report a snapshot of current processes.ps aux
: Display all processes for all users in a user-oriented format.
clear
: Clears the terminal screen.
4. User Management
Ubuntu Server, like all Linux systems, is a multi-user operating system. Proper user management is essential for security and organization.
root
User: The root user is the superuser with unrestricted access to the system. It’s crucial to use the root user sparingly and only when necessary. Direct root login is often disabled for security reasons.sudo
: Thesudo
command allows authorized users to execute commands with root privileges. This is the preferred way to perform administrative tasks. Users are typically added to thesudo
group to grant them these privileges.adduser
: Creates a new user account.sudo adduser newuser
: Creates a new user named “newuser” and prompts for password and other information.
usermod
: Modifies an existing user account.sudo usermod -aG sudo newuser
: Adds “newuser” to thesudo
group.-aG
means “append to group”.sudo usermod -l newlogin oldlogin
: Changes the login name of a user.sudo usermod -d /new/home/dir -m username
: Change a user home directory and move its content.
deluser
: Deletes a user account.sudo deluser olduser
: Deletes the user “olduser”.sudo deluser --remove-home olduser
: Deletes the user and their home directory.
passwd
: Changes a user’s password.sudo passwd username
: Changes the password for the specified user.passwd
: Changes your own password.
groups
: Displays the groups a user belongs to.groups username
: Shows the groups “username” belongs to.groups
: Shows the groups for the currently logged in user.
groupadd
: Creates a new group.sudo groupadd newgroup
: Creates a group named “newgroup”.
groupdel
: Deletes a group.sudo groupdel oldgroup
: Deletes the group “oldgroup”.
id
: Display user and group information.id username
: Return user and group information for the specified user.
5. File Permissions and Ownership
Linux uses a system of file permissions and ownership to control access to files and directories. Understanding this system is critical for security and proper operation.
- Ownership: Each file and directory has an owner (user) and a group.
- Permissions: There are three types of permissions:
- Read (r): Allows viewing the contents of a file or listing the contents of a directory.
- Write (w): Allows modifying a file or creating/deleting files within a directory.
- Execute (x): Allows executing a file (if it’s a program or script) or accessing a directory (entering it with
cd
).
- Permission Categories: Permissions are applied to three categories of users:
- Owner (u): The user who owns the file.
- Group (g): The group associated with the file.
- Others (o): All other users on the system.
- Symbolic Notation: Permissions are represented using symbolic notation:
rwxr-xr--
: This represents the permissions for a file.rwx
: The owner has read, write, and execute permissions.r-x
: The group has read and execute permissions.r--
: Others have read permission.- The first character indicates the file type:
-
for regular file,d
for directory,l
for symbolic link and others.
- Numeric Notation: Permissions can also be represented using numeric notation:
- Read (r) = 4
- Write (w) = 2
- Execute (x) = 1
- The numeric value for each category is the sum of its permissions. For example:
rwxr-xr--
is equivalent to754
(7 = 4+2+1, 5 = 4+1, 4 = 4).
chmod
(change mode): Changes the permissions of a file or directory.chmod u+x filename
: Gives the owner execute permission.chmod go-w filename
: Removes write permission from the group and others.chmod 755 filename
: Sets permissions torwxr-xr-x
(numeric notation).chmod -R 755 directory
: Recursively sets permissions on a directory and its contents.
chown
(change owner): Changes the owner and/or group of a file or directory.sudo chown newuser filename
: Changes the owner of “filename” to “newuser”.sudo chown newuser:newgroup filename
: Changes the owner to “newuser” and the group to “newgroup”.sudo chown -R newuser:newgroup directory
: Recursively changes ownership of a directory and its contents.
chgrp
: Change group ownership.sudo chgrp newgroup filename
: Changes the group of “filename” to “newgroup”.
6. Networking
Networking is fundamental to server administration. Ubuntu Server uses the netplan
utility for network configuration.
- Network Interfaces: Network interfaces are the hardware or software components that connect the server to the network (e.g.,
eth0
,enp0s3
,wlan0
). - IP Address: A unique numerical address that identifies the server on the network.
- Subnet Mask: Defines the network portion of the IP address.
- Gateway: The IP address of the router that connects the server to other networks (including the internet).
- DNS Servers: Domain Name System (DNS) servers translate domain names (e.g.,
google.com
) into IP addresses. ip
command: Used to show / manipulate routing, network devices, interfaces and tunnels.ip addr show
: Display IP addresses and interface information.ip link set dev eth0 up
: Bring interfaceeth0
up.ip route show
: Show routing table.
netplan
: The network configuration utility in Ubuntu Server. Configuration files are located in/etc/netplan/
.- YAML Format:
netplan
uses YAML (YAML Ain’t Markup Language) for configuration files. Indentation is crucial in YAML. - Example Configuration (
/etc/netplan/01-netcfg.yaml
):
- YAML Format:
yaml
network:
version: 2
renderer: networkd
ethernets:
enp0s3: # Replace with your interface name
dhcp4: no # Use 'yes' for DHCP
addresses: [192.168.1.10/24] # Static IP and subnet mask
gateway4: 192.168.1.1 # Gateway IP address
nameservers:
addresses: [8.8.8.8, 8.8.4.4] # DNS server addresses
* Apply Configuration:
bash
sudo netplan apply
* Generate Configuration:
bash
sudo netplan generate
ping
: Test network connectivity by sending ICMP echo requests.
bash
ping google.com
ping 8.8.8.8traceroute
: Trace the route packets take to reach a destination.
traceroute google.com
ss
(socket statistics): A utility for investigating network sockets. It’s a more modern replacement fornetstat
.
ss -tulnp # Show listening TCP/UDP ports with process information.
ufw
(Uncomplicated Firewall): A user-friendly front-end foriptables
. Used to configure the firewall.sudo ufw enable
: Enables the firewall.sudo ufw disable
: Disables the firewall.sudo ufw status
: Shows the firewall status and rules.sudo ufw allow 22/tcp
: Allows incoming connections on port 22 (SSH).sudo ufw deny 80/tcp
: Denies incoming connections on port 80 (HTTP).sudo ufw allow from 192.168.1.0/24 to any port 22
: Allows SSH from a specific subnet.
7. SSH (Secure Shell)
SSH is a secure protocol for remotely accessing and managing servers. It provides encrypted communication and authentication.
sshd
: The SSH server daemon. It listens for incoming SSH connections. Ubuntu Server typically hassshd
installed and running by default.- SSH Client: Used to connect to an SSH server. Most Linux distributions and macOS include an SSH client. Windows users can use PuTTY, MobaXterm, or the built-in OpenSSH client in recent versions of Windows.
- Connecting to a Server:
ssh username@server_ip_address
: Connects to the server using the specified username and IP address. You’ll be prompted for the user’s password.ssh username@hostname
: If DNS is configured correctly.
- Key-Based Authentication: A more secure alternative to password authentication. You generate a public/private key pair. The public key is placed on the server, and the private key is kept on your local machine.
- Generate a Key Pair:
bash
ssh-keygen -t rsa -b 4096 # Generates a 4096-bit RSA key. - Copy the Public Key to the Server:
bash
ssh-copy-id username@server_ip_address
- Generate a Key Pair:
.ssh/config
file: used to define SSH connection settings.
Example:
Host myserver
HostName 192.168.1.100
User ubuntu
IdentityFile ~/.ssh/id_rsa- Disable Root Login: For security, it’s recommended to disable direct root login over SSH.
- Edit
/etc/ssh/sshd_config
:
bash
sudo nano /etc/ssh/sshd_config - Change
PermitRootLogin
tono
:
PermitRootLogin no
- Restart the SSH service:
bash
sudo systemctl restart sshd
- Edit
- Change SSH Port: Changing the default SSH port (22) can help reduce automated attacks.
- Edit
/etc/ssh/sshd_config
:
bash
sudo nano /etc/ssh/sshd_config - Change
Port
to a different port number (e.g., 2222):
Port 2222
- Update ufw to allow the new port
sudo ufw allow 2222/tcp
- Restart the SSH service:
bash
sudo systemctl restart sshd
- Edit
8. Text Editors
You’ll frequently need to edit text files on the server (configuration files, scripts, etc.). Ubuntu Server includes several command-line text editors.
nano
: A simple and user-friendly text editor. Good for beginners.nano filename
: Opens “filename” in nano.- Ctrl+O: Save the file.
- Ctrl+X: Exit nano.
- Ctrl+G: Get help
vim
(Vi IMproved): A powerful and highly configurable text editor. It has a steeper learning curve but is very efficient once mastered.vim filename
: Opens “filename” in vim.i
: Enter insert mode (to start typing).- Esc: Exit insert mode.
:w
: Save the file.:q
: Quit vim.:wq
: Save and quit.:q!
: Quit without saving.
emacs
: Another powerful and extensible text editor. It’s also known for its extensive features and customization options.
9. System Monitoring and Logs
Monitoring your server’s performance and checking logs are crucial for troubleshooting and maintaining system health.
top
: dynamic real-time view of running processes.htop
: an interactive process viewer (more user-friendly thantop
). You’ll likely need to install it:sudo apt install htop
.free
: Display amount of free and used memory.df
: Reports file system disk space usage.df -h
(human-readable output).du
: Estimate file space usage.iotop
: simple top-like I/O monitor. You’ll likely need to install it.vmstat
: Report virtual memory statistics.iostat
: Report CPU statistics and input/output statistics for devices and partitions.uptime
: Shows how long the system has been running, the number of users, and the load average.- Log Files: Most system logs are located in
/var/log/
. Important log files include:/var/log/syslog
: General system log messages./var/log/auth.log
: Authentication-related messages (login attempts, sudo usage)./var/log/kern.log
: Kernel messages./var/log/dmesg
: Kernel ring buffer messages (hardware and driver information). Can also be accessed using thedmesg
command.- Application-specific logs: Many applications have their own log files (e.g.,
/var/log/apache2/
for Apache web server logs).
journalctl
: Query the systemd journal. systemd’s logging service.journalctl -u service_name
: Show logs for a specific service.journalctl -f
: Follow the journal log in real time.journalctl -b
: Show logs from the current boot.journalctl -p err
: Show only error messages.journalctl --since "2023-10-26 09:00:00"
: Show logs since a specific time.
10. Package Management (APT)
apt
is Ubuntu’s powerful package management system.
sudo apt update
: Update package list.sudo apt upgrade
: Upgrades all installed packages.sudo apt install package_name
: Installs a package.sudo apt remove package_name
: Removes a package.sudo apt autoremove
: Removes packages that were automatically installed and are no longer needed.sudo apt search package_name
: Searches for packages.sudo apt show package_name
: Displays detailed information about a package.sudo apt list --installed
: Lists all installed packages.dpkg
: The low-level package management tool underlying APT.sudo dpkg -i package_file.deb
: Installs a .deb package file.sudo dpkg -l
: Lists all installed packages (similar toapt list --installed
).sudo dpkg -r package_name
: Removes a package (similar toapt remove
).
11. Working with Services (systemd)
systemd
is the init system and service manager used by Ubuntu Server.
systemctl
: The main command for managing services.sudo systemctl start service_name
: Starts a service.sudo systemctl stop service_name
: Stops a service.sudo systemctl restart service_name
: Restarts a service.sudo systemctl enable service_name
: Enables a service to start on boot.sudo systemctl disable service_name
: Disables a service from starting on boot.sudo systemctl status service_name
: Checks the status of a service.sudo systemctl list-units --type=service
: Lists all service units.sudo systemctl list-unit-files --type=service
: List all service unit files and their state (enabled, disabled, static, etc.).
12. Scheduling Tasks (Cron)
cron
is a time-based job scheduler in Linux. It allows you to schedule commands or scripts to run automatically at specific times or intervals.
crontab
: The command used to manage cron jobs.crontab -e
: Edits your user’s crontab file. The first time you run this, you may be asked to choose a text editor.crontab -l
: Lists your user’s cron jobs.crontab -r
: Removes your user’s crontab file (use with caution!).
- Crontab File Format: Each line in a crontab file represents a cron job and has the following format:
* * * * * command_to_execute
- Fields:
- Minute (0-59)
- Hour (0-23)
- Day of month (1-31)
- Month (1-12)
- Day of week (0-7, where 0 and 7 are Sunday)
- Special Characters:
*
: Matches all values (e.g., every minute, every hour).,
: Specifies a list of values (e.g.,1,3,5
for minutes 1, 3, and 5).-
: Specifies a range of values (e.g.,1-5
for hours 1 through 5)./
: Specifies a step value (e.g.,*/15
for every 15 minutes).
- Examples:
0 * * * * /path/to/script.sh
: Runsscript.sh
every hour at the start of the hour.30 2 * * * /path/to/backup.sh
: Runsbackup.sh
every day at 2:30 AM.0 0 1 * * /path/to/monthly_task.sh
: Runsmonthly_task.sh
on the 1st of every month at midnight.*/5 * * * * /path/to/check_status.sh
: Runscheck_status.sh
every 5 minutes.0 22 * * 1-5 /path/to/weekday_task.sh
: Runweekday_task.sh
every weekday (Monday to Friday) at 10 PM.
- System Crontab: The system-wide crontab file is located at
/etc/crontab
. It’s generally used for system tasks, and you should avoid modifying it directly. /etc/cron.d/
: This directory is used for placing separate crontab files, often used by packages./etc/cron.{hourly,daily,weekly,monthly}/
: These directories contain scripts that are executed hourly, daily, weekly, and monthly, respectively.
13. Shell Scripting Basics
Shell scripting allows you to automate tasks by writing sequences of commands in