Ubuntu 设置日期和时间

一、设置时区

方法1

bash
echo "Asia/Shanghai" > /etc/timezone && \
apt-get install -y tzdata && \
rm /etc/localtime && \
ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
dpkg-reconfigure -f noninteractive tzdata

Docker 容器中,设置时区

bash
-v /etc/localtime:/etc/localtime

在 dockerfile 中

bash
FROM ubuntu:latest

ENV TZ Asia/Shanghai

RUN echo $TZ > /etc/timezone && \
    apt-get update && apt-get install -y tzdata && \
    rm /etc/localtime && \
    ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && \
    dpkg-reconfigure -f noninteractive tzdata && \
    apt-get clean

方法2

bash
timedatectl set-timezone Asia/Shanghai

二、时间同步

方法1

shell
apt-get -y install ntpdate && \
ntpdate -d cn.pool.ntp.org

方法2

shell
# 安装
apt -y install ntp

# 配置
mv /etc/ntp.conf /etc/ntp.conf.bak

cat >/etc/ntp.conf <<-EOF
server 0.cn.pool.ntp.org
server 1.cn.pool.ntp.org
server 2.cn.pool.ntp.org
server 3.cn.pool.ntp.org
EOF

# 同步
service ntp restart
ps -ef | grep ntpd
ntpq -p

方法3

shell
timedatectl set-ntp yes
ESC