Ubuntu安装Docker并支持使用GPU

# 前言

因为Docker官方的网站无法访问,这里提供阿里镜像安装方式,并提供支持英伟达GPU方式。

安装Docker

  1. 安装前准备
# 安装必要的一些系统工具
sudo apt-get update
sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
# 添加密钥:
install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# 创建源地址
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://mirrors.aliyun.com/docker-ce/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
  1. 安装Docker
# 再次更新apt源 
sudo apt update
# 开始安装docker 
sudo apt install -y docker-ce
# 加载docker 
sudo apt-cache madison docker-ce

要配置 Docker 国内镜像源,可以按照以下步骤进行: 1. 打开 Docker 配置文件/etc/docker/daemon.json

sudo vim /etc/docker/daemon.json
  1. 在该配置文件中添加以下内容:
{
  "registry-mirrors": ["https://ccr.ccs.tencentyun.com"]
}

如果要使用多个镜像源,可以在registry-mirrors数组中添加多个镜像源地址,以英文逗号分隔。

  1. 保存配置文件,并重启 Docker 服务,以使配置生效。可以使用以下命令重启 Docker 服务:
sudo systemctl restart docker

测试:

# 验证docker是否安装成功
sudo docker run hello-world

正常情况下输出如下图所示:

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://cloud.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/

支持英伟达显卡

安装nvidia-container-toolkit即可实现Docker使用GPU。安装之前要确认本地有独立显卡并安装的显卡驱动。

# 配置生产存储库
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \
  && curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
    sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
    sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list

# 更新软件包清单后
sudo apt-get update

# 安装软件包
sudo apt-get install -y nvidia-container-toolkit

# 配置docker
sudo nvidia-ctk runtime configure --runtime=docker

# 设置默认运行时后,重新启动Docker守护程序以完成安装:
sudo systemctl restart docker

# 测试
sudo docker run --rm --runtime=nvidia --gpus all ubuntu nvidia-smi

执行测试之后,正常情况下会输出显卡信息。