skip to Main Content

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search