Linux 服务器初始化完整指南

拿到一台全新的 Linux 服务器后,如何快速且安全地进行初始化配置?本文将为你提供一个完整的服务器上手指南,涵盖从基础配置到安全加固的各个方面。

本文基于 Ubuntu 22.04 进行演示。

0 约定

  • $name 代表变量,需要替换成你自己的参数。
  • NOTE 是一些提示。

1 使用 ssh 登陆服务器

NOTE:

ssh 是一种网络加密协议,全名为 Secure Shell。 当我们这种协议从本地计算机登录另一台远程计算机时,即使信息的传输过程中被截获,也无法破解。

详见:SSH原理与运用(一):远程登录

打开电脑的终端,输入👇命令:

1
ssh root@$your_server_ip

然后输入密码即可登录。如果登录成功,你会看到如下欢迎语:

1
2
3
4
5
6
Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 5.15.0-97-generic x86_64)

* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/pro
Last login: Sat Mar 2 16:23:35 2024 from ***.***.***.***

1.1 SSH 安全配置

修改默认 ssh 端口 22 -> 1122,这个端口容易被攻击。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
vim /etc/ssh/sshd_config

# 修改端口
Port 1122

# 限制登录尝试次数
MaxAuthTries 3

# 设置登录超时时间
LoginGraceTime 60

# 禁用空密码登录
PermitEmptyPasswords no

# 重启 sshd 服务
systemctl restart sshd

1.2 配置 SSH 密钥认证

为了提高安全性,建议使用密钥认证替代密码认证。

在本地机器上生成密钥对:

1
2
# 生成更安全的 Ed25519 密钥对
ssh-keygen -t ed25519 -C "your_email@example.com"

将公钥复制到服务器:

1
2
# 使用 ssh-copy-id
ssh-copy-id -p 1122 root@$your_server_ip

在服务器上设置正确的权限:

1
2
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

配置完成后,可以禁用密码登录:

1
2
3
4
5
6
7
vim /etc/ssh/sshd_config

# 禁用密码登录
PasswordAuthentication no

# 重启服务
systemctl restart sshd

以后登录就需要添加 -p 选项,指定 Port:

1
ssh root@$your_server_ip -p 1122

2 系统信息查看

在开始配置之前,先了解服务器的基本信息是很重要的。

2.1 查看系统基本信息

1
2
3
4
5
6
7
8
9
# 查看系统版本
cat /etc/os-release
lsb_release -a

# 查看内核版本
uname -a

# 查看系统架构
arch

2.2 查看硬件配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 查看CPU信息
lscpu
cat /proc/cpuinfo

# 查看内存信息
free -h
cat /proc/meminfo

# 查看磁盘信息
df -h
lsblk
fdisk -l

# 查看网络接口
ip addr show
ifconfig

2.3 查看系统状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 查看系统负载
uptime
top
htop # 需要先安装: apt install htop

# 查看进程信息
ps aux
systemctl status

# 查看网络连接
netstat -tulpn
ss -tulpn

# 查看系统日志
journalctl -f
tail -f /var/log/syslog

3 修改 hostname

先说个不那么重要的 hostname,一般情况下系统会默认给一个 instance-kk9n95zj 之类的。这样名字会导致你有多个服务器同时操作时,很难区分服务器。通常我会第一时间把它改掉。

1
2
3
4
hostnamectl hostname new-server

# in ubuntu 20.04
hostnamectl set-hostname new-server

上面的修改操作需要重启才能生效,不过先别急,等下面语言环境修改后一起重启。

4 设置语言环境

接着设置语言环境,如果你没有设置中文,有些程序输出中文就会报错。

1
2
3
4
5
6
7
8
9
10
11
locale-gen zh_CN.UTF-8

vim /etc/default/locale
LANG="zh_CN.UTF-8"
LANGUAGE="zh_CN:zh"
LC_ALL="zh_CN.UTF-8"
# 使部分配置生效
source /etc/default/locale

# 重启使所有配置生效
reboot

5 更新软件

1
2
3
4
5
6
7
8
# update 命令可以同步 /etc/apt/sources.list 和 /etc/apt/sources.list.d 中列出的源的索引,然后使用获取到最新的软件包。
apt update

# upgrade 是升级已安装的所有软件包,升级之后的版本就是本地索引里的,因此,在执行 upgrade 之前一定要执行 update, 这样才能是最新的。
apt upgrade

# 自动移除没用的包
apt autoremove

如果遇到更新问题,可以试试更换成阿里云的源。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
vim /etc/apt/sources.list

## Note, this file is written by cloud-init on first boot of an instance
## modifications made here will not survive a re-bundle.
## if you wish to make changes you can:
## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg
## or do the same in user-data
## b.) add sources in /etc/apt/sources.list.d
## c.) make changes to template file /etc/cloud/templates/sources.list.tmpl

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy main restricted
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates main restricted
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy universe
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy universe
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates universe
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy multiverse
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy multiverse
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates multiverse
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy-backports main restricted universe multiverse
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy-backports main restricted universe multiverse

deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security main restricted
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security main restricted
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security universe
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security universe
deb http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security multiverse
# deb-src http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security multiverse

6 添加运维用户(可选)

添加新的用户,这里以 op 为例。

1
2
3
4
5
6
7
8
9
# useradd 命令参数
# -s 指定所使用的 shell
# -g 添加到 sudo 组, 保证可以安装软件。
# -d 指定 home 目录 -m 如果不存在该目录就创建。
useradd -s /bin/bash -g sudo -d /home/op -m op

# 添加密码
passwd op
# 然后输入两遍相同的密码

切换到 op 用户

1
2
3
4
5
su -l op

# 输入pwd查看当前命令目录
pwd
# 输出为 /home/op

7 安装必备工具

安装一些常用的系统工具和开发工具。

7.1 系统工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 更新包列表
apt update

# 安装基础工具
apt install -y \
vim \
git \
curl \
wget \
unzip \
tree \
htop \
iotop \
nethogs \
ncdu \
tmux \
screen \
build-essential \
software-properties-common \
apt-transport-https \
ca-certificates \
gnupg \
lsb-release

7.2 配置 Git

1
2
3
4
5
6
# 配置 Git 用户信息
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# 配置 Git 默认编辑器
git config --global core.editor vim

7.3 配置 Vim

创建基本的 Vim 配置:

1
2
3
4
5
6
7
8
9
10
11
12
vim ~/.vimrc

# 添加以下内容
set number
set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
set smartindent
set hlsearch
set incsearch
syntax on

7.4 配置 Zsh(可选)

安装和配置 Zsh 以获得更好的命令行体验:

1
2
3
4
5
6
7
8
# 安装 Zsh
apt install -y zsh

# 安装 Oh My Zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

# 切换默认 shell 为 zsh
chsh -s $(which zsh)

8 服务器安全配置

安全配置是服务器初始化的重要环节,以下是一些基本的安全措施。

8.1 配置防火墙 (UFW)

Ubuntu 默认使用 UFW (Uncomplicated Firewall) 作为防火墙管理工具。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 启用 UFW
ufw enable

# 设置默认策略
ufw default deny incoming
ufw default allow outgoing

# 允许 SSH 连接(使用你修改后的端口)
ufw allow 1122/tcp

# 允许 HTTP 和 HTTPS
ufw allow 80/tcp
ufw allow 443/tcp

# 查看防火墙状态
ufw status verbose

# 查看防火墙规则编号
ufw status numbered

# 删除规则(按编号)
# ufw delete 2

8.2 安装和配置 Fail2Ban

Fail2Ban 可以监控日志文件并自动封禁恶意IP地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
# 安装 Fail2Ban
apt install -y fail2ban

# 创建本地配置文件
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# 启动并启用 Fail2Ban
systemctl enable fail2ban
systemctl start fail2ban

# 查看状态
fail2ban-client status
fail2ban-client status sshd

8.3 系统更新和自动安全更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 安装自动更新工具
apt install -y unattended-upgrades

# 配置自动安全更新
dpkg-reconfigure -plow unattended-upgrades

# 编辑配置文件
vim /etc/apt/apt.conf.d/50unattended-upgrades

# 确保以下行未被注释
"${distro_id}:${distro_codename}-security";

# 启用自动更新
vim /etc/apt/apt.conf.d/20auto-upgrades

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";

8.4 禁用不必要的服务

1
2
3
4
5
6
7
8
9
10
11
# 查看所有运行的服务
systemctl list-units --type=service --state=running

# 禁用不必要的服务(示例)
systemctl disable bluetooth
systemctl disable cups
systemctl disable avahi-daemon

# 查看网络端口使用情况
netstat -tulpn
ss -tulpn

8.5 设置系统资源限制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 编辑系统限制配置
vim /etc/security/limits.conf

# 添加以下内容(根据需要调整)
* soft nofile 65536
* hard nofile 65536
* soft nproc 32768
* hard nproc 32768

# 编辑系统配置
vim /etc/sysctl.conf

# 添加网络安全相关配置(可选)
net.ipv4.conf.default.rp_filter=1
net.ipv4.conf.all.rp_filter=1
net.ipv4.tcp_syncookies=1
net.ipv4.conf.all.accept_redirects=0
net.ipv6.conf.all.accept_redirects=0
net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.all.accept_source_route=0
net.ipv6.conf.all.accept_source_route=0

# 应用配置
sysctl -p

9 Docker 安装和配置

Docker 是现代应用部署的重要工具。

9.1 安装 Docker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 卸载旧版本
apt remove -y docker docker-engine docker.io containerd runc

# 安装依赖
apt install -y apt-transport-https ca-certificates curl gnupg lsb-release

# 添加 Docker 官方 GPG 密钥
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# 添加 Docker 仓库
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

# 更新包索引
apt update

# 安装 Docker
apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

# 启动并启用 Docker
systemctl enable docker
systemctl start docker

# 将用户添加到 docker 组(避免每次使用 sudo)
usermod -aG docker $USER

9.2 Docker 基本配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 创建 Docker 配置目录
mkdir -p /etc/docker

# 配置 Docker daemon
vim /etc/docker/daemon.json

{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "3"
},
"storage-driver": "overlay2"
}

# 重启 Docker
systemctl restart docker

10 系统监控和日志管理

10.1 系统监控工具

1
2
3
4
5
6
7
8
# 安装监控工具
apt install -y htop iotop nethogs ncdu

# 实时监控系统资源
htop # 进程监控
iotop # IO 监控
nethogs # 网络监控
ncdu / # 磁盘使用分析

10.2 日志管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 查看系统日志
journalctl -f # 实时查看所有日志
journalctl -u ssh # 查看SSH服务日志
journalctl --since "1 hour ago" # 查看最近1小时的日志

# 配置日志轮转
vim /etc/logrotate.d/custom

/var/log/custom/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
copytruncate
}

# 清理旧日志
journalctl --vacuum-time=30d # 保留30天的日志
journalctl --vacuum-size=1G # 限制日志大小为1GB

11 备份策略

11.1 系统配置备份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 创建备份目录
mkdir -p /backup/system

# 备份重要配置文件
tar -czf /backup/system/config-$(date +%Y%m%d).tar.gz \
/etc/ssh/ \
/etc/nginx/ \
/etc/apache2/ \
/etc/mysql/ \
/etc/fail2ban/ \
/etc/ufw/ \
/etc/crontab \
/etc/fstab \
/etc/hosts

# 创建备份脚本
vim /usr/local/bin/system-backup.sh

#!/bin/bash
BACKUP_DIR="/backup/system"
DATE=$(date +%Y%m%d_%H%M%S)

# 创建备份目录
mkdir -p $BACKUP_DIR

# 备份系统配置
tar -czf $BACKUP_DIR/config-$DATE.tar.gz \
/etc/ssh/ \
/etc/nginx/ \
/etc/apache2/ \
/etc/mysql/ \
/etc/fail2ban/ \
/etc/ufw/ \
/etc/crontab \
/etc/fstab \
/etc/hosts

# 删除30天前的备份
find $BACKUP_DIR -name "config-*.tar.gz" -mtime +30 -delete

echo "Backup completed: config-$DATE.tar.gz"

# 添加执行权限
chmod +x /usr/local/bin/system-backup.sh

11.2 自动备份计划

1
2
3
4
5
# 编辑 crontab
crontab -e

# 添加自动备份任务(每天凌晨2点执行)
0 2 * * * /usr/local/bin/system-backup.sh >> /var/log/backup.log 2>&1

12 性能优化

12.1 系统参数优化(可选)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 编辑系统配置
vim /etc/sysctl.conf

# 网络优化
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 65536 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.core.netdev_max_backlog = 5000

# 文件系统优化
fs.file-max = 2097152
vm.swappiness = 10

# 应用配置
sysctl -p

12.2 磁盘优化(可选)

1
2
3
4
5
6
# 查看磁盘IO情况
iotop

# 优化磁盘挂载选项(编辑 /etc/fstab)
# 添加 noatime 选项减少磁盘写入
/dev/sda1 / ext4 defaults,noatime 0 1

13 总结

通过以上步骤,你已经完成了一台 Linux 服务器的基本初始化配置。这个过程包括:

  1. 基础配置:SSH安全配置、系统信息查看、主机名修改
  2. 系统优化:语言环境设置、软件更新、必备工具安装
  3. 安全加固:防火墙配置、Fail2Ban部署、自动更新设置
  4. 容器化支持:Docker和Docker Compose安装
  5. 运维保障:监控工具部署、日志管理、备份策略
  6. 性能调优:系统参数优化、资源限制设置

记住,服务器安全是一个持续的过程,需要定期检查和更新。建议定期执行以下维护任务:

  • 检查系统更新和安全补丁
  • 监控系统资源使用情况
  • 检查防火墙和Fail2Ban日志
  • 验证备份的完整性
  • 审查用户权限和访问日志

14 参考资料

官方文档

安全相关

系统优化

监控和日志

容器化

备份和恢复

作者

Ailln

发布于

2025-09-13

更新于

2025-09-13

许可协议

评论