Ubuntu Server系统初始化配置

8 阅读2分钟

一、基础系统优化

1、更新系统

sudo apt update && sudo apt upgrade -y

2、安装常用软件包

sudo apt install -y Vim curl git wget unzip net-tools lsof

3、清理系统

删除不需要的软件包缓存 sudo apt clean

删除旧版本的软件包 sudo apt autoremove

4、时间同步(NTP)

sudo apt install chrony

sudo systemctl enable chrony

sudo timedatectl set-timezone Asia/Shanghai

验证时区是否生效: timedatectl

5、配置SSH

ssh配置文件/etc/ssh/sshd_config

#修改端口
Port 2222  # 取消注释并替换为自定义端口(建议 1024-65535)
#允许Root登录
PermitRootLogin yes  # 允许 Root 登录
# 禁用 DNS 反向解析(加速登录)
UseDNS no

重启ssh服务: systemctl restart ssh

关闭防火墙: systemctl stop ufw && systemctl disable ufw

6、创建管理用户并赋予sudo权限

sudo adduser admin

sudo usermod -aG sudo admin

7、IP地址配置

Ubuntu 的 Netplan 配置文件通常位于 /etc/netplan/,文件名可能是:

00-installer-config.yaml(Ubuntu Server 安装时生成)

50-cloud-init.yaml(云服务器)

01-netcfg.yaml(手动配置)

network:
  version: 2
  ethernets:
    ens33:
      dhcp4: no
      addresses:
        - 192.168.1.90/24
      routes:
        - to: default
          via: 192.168.1.1
      nameservers:
        addresses: [114.114.114.114, 8.8.8.8]

应用生效: sudo netplan apply

二、性能优化

8、内核参数调优

编辑文件/etc/sysctl.conf

# 网络优化
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_syncookies = 1

# 文件系统
fs.file-max = 1000000

生效命令: sudo sysctl -p

作用:

  • somaxconn:定义系统全局的 全连接队列(Accept Queue)  最大长度。高并发服务(如Web服务器)需增大此值,防止连接被丢弃。
  • tcp_max_syn_backlog:控制 半连接队列(SYN Queue)  大小,用于存放未完成三次握手的请求。

建议值:生产环境建议 4096 或更高,需配合应用层的 listen(backlog) 参数使用(如Nginx的 backlog 参数)。

  • tcp_tw_reuse:允许复用 TIME-WAIT 状态的连接端口,缓解短连接服务的端口耗尽问题。
  • tcp_fin_timeout:控制 FIN-WAIT-2 状态的超时时间(秒)。

注意:若启用 tcp_tw_recycle(已弃用)可能导致NAT环境问题,现代内核推荐仅用 tcp_tw_reuse

  • tcp_syncookies:启用 SYN Cookie 机制,防止半连接队列溢出导致的拒绝服务攻击。

  • file-max: 系统全局的 最大文件描述符数。高连接数服务(如Nginx、MySQL)需增大此值。需同步修改 /etc/security/limits.conf 中的用户级限制。

9、资源限制提升

编辑文件/etc/security/limits.conf,行尾新增

* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535