加油
努力

在腾讯云的Ubuntu服务器上如何正确安装Docker?

在腾讯云的 Ubuntu 服务器上正确安装 Docker,可以按照以下步骤操作。这些步骤适用于大多数 Ubuntu 版本(如 20.04、22.04 等),并推荐使用官方 Docker 安装方式。


✅ 步骤 1:更新系统包

sudo apt update && sudo apt upgrade -y

✅ 步骤 2:安装依赖包

确保系统可以使用 HTTPS 安装仓库:

sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release

✅ 步骤 3:添加 Docker 的 GPG 公钥

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

⚠️ 注意:如果你使用的是 Debian 系统,请将 ubuntu 改为 debian


✅ 步骤 4:添加 Docker 官方 APT 仓库

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" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

$(lsb_release -cs) 会自动获取你的 Ubuntu 版本代号(如 focal、jammy)。


✅ 步骤 5:更新 APT 包索引

sudo apt update

✅ 步骤 6:安装 Docker Engine

sudo apt install -y docker-ce docker-ce-cli containerd.io

这会安装最新稳定版的 Docker。


✅ 步骤 7:验证安装是否成功

sudo docker --version

输出示例:

Docker version 24.0.7, build afdd53b

测试运行一个 hello-world 容器:

sudo docker run hello-world

如果看到欢迎信息,说明 Docker 安装成功。


✅ 步骤 8(可选):允许非 root 用户使用 Docker

将当前用户加入 docker 组,避免每次使用 sudo

sudo usermod -aG docker $USER

⚠️ 执行后需要 重新登录 或重启 shell 才能生效。

验证(无需 sudo):

docker run hello-world

✅ 步骤 9(可选):设置 Docker 开机自启

Docker 通常默认已启用,但仍可确认:

sudo systemctl enable docker
sudo systemctl start docker

🔒 腾讯云安全组注意事项

  • 如果你要通过网络访问容器服务(如 Web 应用),请在腾讯云控制台的 安全组规则 中放行对应端口(如 80、443、8080 等)。
  • 默认情况下,Docker 会使用 iptables,但不会影响云服务器的安全组配置,需手动开放端口。

❌ 常见问题排查

  1. 报错:E: Package 'docker-ce' has no installation candidate

    • 检查系统架构和版本是否支持。
    • 确保 sources.list.d/docker.list 中的 Ubuntu 版本代号正确(如 jammy、focal)。
    • 可尝试手动替换 $(lsb_release -cs) 为实际代号。
  2. 权限错误:Got permission denied while trying to connect...

    • 确认用户已加入 docker 组,并重新登录。
  3. 国内下载慢?

    • 可使用国内镜像源提速:

      # 编辑或创建 daemon.json
      sudo mkdir -p /etc/docker
      sudo tee /etc/docker/daemon.json <<EOF
      {
        "registry-mirrors": [
          "https://mirror.ccs.tencentyun.com"
        ]
      }
      EOF

      腾讯云提供镜像提速器:https://mirror.ccs.tencentyun.com

      然后重启 Docker:

      sudo systemctl restart docker

✅ 完成!你现在已在腾讯云 Ubuntu 服务器上成功安装并配置了 Docker。

如有进一步需求(如部署 Nginx、MySQL 容器等),可继续使用 docker rundocker-compose

云服务器