Ubuntu 系统配置技巧
Ubuntu 系统日常运维中的一些常用配置技巧。
更改主机名
在 Ubuntu 系统中,可以通过以下步骤更改主机名:
方法一:修改配置文件
- 编辑 hostname 文件:
sudo vi /etc/hostname
- 编辑 hosts 文件:
sudo vi /etc/hosts
在 hosts 文件中修改或添加:
127.0.1.1 [hostname]
方法二:使用 hostnamectl 命令
sudo hostnamectl set-hostname [hostname]
使用 hostnamectl 命令是最简单和推荐的方法,它会自动更新所有相关的配置文件。
验证更改
重启系统后,可以使用以下命令验证主机名是否更改成功:
hostname
# 或
hostnamectl
时钟同步设置
方法一:使用 timedatectl
查看同步状态:
timedatectl status
启用 NTP 同步:
sudo timedatectl set-ntp true
这会启用 systemd-timesyncd 服务,自动与外部 NTP 服务器同步时间。
方法二:安装 NTP 服务
适用于需要更精细控制的场景。
1. 安装 NTP
sudo apt-get update
sudo apt-get install ntp
2. 配置 NTP 服务器
编辑配置文件:
sudo nano /etc/ntp.conf
添加或修改 NTP 服务器:
server 0.ubuntu.pool.ntp.org
server 1.ubuntu.pool.ntp.org
server 2.ubuntu.pool.ntp.org
server 3.ubuntu.pool.ntp.org
3. 重启服务
sudo systemctl restart ntp
4. 查看同步状态
ntpq -p
两种方法对比
| 方法 | 优点 | 缺点 |
|---|---|---|
| timedatectl | 系统自带,简单快速 | 功能相对简单 |
| NTP 服务 | 功能强大,可精细配置 | 需要额外安装 |
注意事项
- 确保防火墙允许 UDP 123 端口(NTP 端口)
- 受限网络环境需配置特定 NTP 服务器
- 两种方法不要同时使用,选择其一即可