更换 docker 容器镜像、删除镜像

Docker 根据关键字删除容器

使用方法: chmod +x delete_containers.sh ./delete_containers.sh <keyword>

delete_containers.sh脚本如下:

#!/bin/bash

# 检查是否传入关键词参数
if [ $# -eq 0 ]; then
    echo "Usage: $0 <keyword>"
    exit 1
fi

# 关键词
keyword=$1

# 获取所有匹配关键词的容器ID,是一个列表,是以回车符进行分割的。
container_ids=$(docker ps -a --filter "name=$keyword" --format "{{.ID}}")

# 检查是否有匹配的容器
if [ -z "$container_ids" ]; then
    echo "No containers found with the keyword '$keyword'."
    exit 0
fi

# 删除匹配的容器,for id in 可以遍历以空格或者回车符分割的字符
echo "Deleting containers with keyword '$keyword':"
for id in $container_ids; do
    echo "Deleting container ID: $id"
    docker stop "$id" && docker rm "$id"
done

echo "All matching containers have been deleted."

Docker 更换镜像(没有容器运行的话,直接该镜像运行)

使用方法: ./replace_or_run_docker.sh my_app_container my_image:latest
第一个参数my_app_container 为要替换镜像的容器,第二个参数为要更换的镜像my_image:latest

replace_or_run_docker.sh脚本如下:

#!/bin/bash

# 检查参数
if [ $# -ne 2 ]; then
    echo "Usage: $0 <container_name> <new_image>"
    exit 1
fi

# 获取参数
container_name=$1
new_image=$2

# 检查 Docker 是否可用
if ! command -v docker &> /dev/null; then
    echo "Error: Docker is not installed or not in the PATH."
    exit 1
fi

# 检查容器是否存在
container_exists=$(docker ps -a --filter "name=$container_name" --format "{{.ID}}")

if [ -n "$container_exists" ]; then
    echo "Container '$container_name' exists. Updating the container..."

    # 停止容器
    echo "Stopping container '$container_name'..."
    if ! docker stop "$container_name"; then
        echo "Error: Failed to stop the container '$container_name'."
        exit 1
    fi
    echo "Container '$container_name' stopped."

    # 删除容器
    echo "Removing container '$container_name'..."
    if ! docker rm "$container_name"; then
        echo "Error: Failed to remove the container '$container_name'."
        exit 1
    fi
    echo "Container '$container_name' removed."
else
    echo "Container '$container_name' does not exist. Running a new container with image '$new_image'..."
fi

# 拉取新镜像
echo "Pulling new image '$new_image'..."
if ! docker pull "$new_image"; then
    echo "Error: Failed to pull the image '$new_image'."
    exit 1
fi
echo "Successfully pulled the image '$new_image'."

# 重新创建并启动容器
echo "Running container '$container_name' with new image '$new_image'..."
if ! docker run -d --name "$container_name" "$new_image"; then
    echo "Error: Failed to create the container '$container_name' with image '$new_image'."
    exit 1
fi

echo "Container '$container_name' is now running with the new image."

删除所有容器(运行和不运行的都包括)

方式一

# 首先,需要停止所有正在运行的容器,然后删除所有容器
docker stop $(docker ps -q) && docker rm $(docker ps -a -q)

方式二

docker rm -f $(docker ps -a -q)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值