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)