使用shell脚本一键安装docker并配置国内镜像,直接拉到底部查看完整脚本。
1.创建一个install-docker.sh文件
touch install-docker.sh # 创建文件
chmod +x ./install-docker.sh # 添加可执行权限
2.粘贴如下命令至install-docker.sh
#!/bin/bash
apt-get update
apt-get install ca-certificates curl
curl -fsSL http://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] http://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
apt -y install docker-ce docker-ce-cli containerd.io
如果遇到权限问题请切换到root用户,或者在命令前面加上sudo
。
3.运行命令
./install-docker.sh
4.测试docker是否安装成功
docker -v
docker run hello-world
hello-world 容器可能因为网络原因拉取不到对应的镜像,需要设置一些国内镜像
5.设置国内镜像
下面使用阿里云镜像加速器
设置完成之后再次运行 docker run hello-world
查看镜像是否设置成功
完整脚本
请使用root用户进行操作,包含安装docker、设置阿里云镜像、验证docker
#!/bin/bash
#安装docker
apt-get update
apt-get install ca-certificates curl
curl -fsSL http://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] http://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
apt -y install docker-ce docker-ce-cli containerd.io
# 创建 /etc/docker 目录
mkdir -p /etc/docker
# 获取传入的第一个参数
image_url=$1
# 检查是否提供了 image_url 参数
if [ -z "$image_url" ]; then
echo "Usage: $0 <image_url>"
exit 1
fi
# 将配置写入 /etc/docker/daemon.json,替换变量
tee /etc/docker/daemon.json <<EOF
{
"registry-mirrors": ["$image_url"]
}
EOF
# 重启docker
systemctl daemon-reload
systemctl restart docker
# 测试docker
docker run hello-world
docker rm $(docker ps -a -q)
docker rmi hello-world
使用方式
./install-docker.sh 你的国内镜像地址
# example 镜像地址可查看 https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors
./install-docker.sh https://o*****1.mirror.aliyuncs.com