英文:
check if docker container is running before removing or deleting it via script
问题
我有一个部署名为enhanced-app
的应用程序的Bash脚本。预期在构建新镜像之前首先清理所有正在运行的容器。我的当前代码已经实现了这一点,但在容器不存在或未运行的情况下,我会收到错误消息。
我希望只在enhanced-app
正在运行时运行清理命令。请问如何实现这一点?
#!/bin/bash
echo "Stopping App2..."
docker container stop enhanced-app
docker container rm enhanced-app
CURPATH=$(dirname "${BASH_SOURCE[0]}")
docker build . -t enhanced-app
docker run -d -p 5000:5000 --name enhanced-app enhanced-app
英文:
I have a bash script that deploys an application called enhanced-app
. It is expected to clean up all running containers first before building a new image. My current code does that, but in cases where the container doesn't exist or isn't running, I get an error.
I want to only run the cleanup command if enhanced-app
is running. Please how can I achieve this?
!/bin/bash
echo "Stopping App2..."
docker container stop enhanced-app
docker container rm enhanced-app
CURPATH=$(dirname "${BASH_SOURCE[0]}")
docker build . -t enhanced-app
docker run -d -p 5000:5000 --name enhanced-app enhanced-app
答案1
得分: 0
以下是代码部分的翻译:
#!/bin/bash
IS_RUNNING=$(docker ps --filter name=enhanced-app --format '{{.ID}}')
if [ -n "${IS_RUNNING}" ]; then
echo "enhanced-app is running. Stopping App2 and removing container..."
docker container stop enhanced-app
docker container rm enhanced-app
else
IS_STOPPED=$(docker ps -a --filter name=enhanced-app --format '{{.ID}}')
if [ -n "${IS_STOPPED}" ]; then
echo "enhanced-app is stopped. Removing container..."
docker container rm enhanced-app
else
fi
CURPATH=$(dirname "${BASH_SOURCE[0]}")
docker build . -t enhanced-app
docker run -d -p 5000:5000 --name enhanced-app enhanced-app
英文:
I believe you can use the output of docker ps
for that:
#!/bin/bash
IS_RUNNING=$(docker ps --filter name=enhanced-app --format '{{.ID}}')
if [ -n "${IS_RUNNING}" ]; then
echo "enhanced-app is running. Stopping App2 and removing container..."
docker container stop enhanced-app
docker container rm enhanced-app
else
IS_STOPPED=$(docker ps -a --filter name=enhanced-app --format '{{.ID}}')
if [ -n "${IS_STOPPED}" ]; then
echo "enhanced-app is stopped. Removing container..."
docker container rm enhanced-app
else
fi
CURPATH=$(dirname "${BASH_SOURCE[0]}")
docker build . -t enhanced-app
docker run -d -p 5000:5000 --name enhanced-app enhanced-app
答案2
得分: 0
你可以使用 docker container inspect
的退出状态。
if docker inspect -f '容器存在并且状态为{{.State.Status}}' enhanced-app; then
docker container stop enhanced-app
docker container rm enhanced-app
fi
英文:
You can use the exit status for docker container inspect
if docker inspect -f 'Container exists and is {{.State.Status}}' enhanced-app; then
docker container stop enhanced-app
docker container rm enhanced-app
fi
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论