docker commands | use Docker | Actually delete everything | Search

This code checks for a running Docker container by name and, if found, stops and removes it.

Run example

npm run import -- "Restart the docker service"

Restart the docker service

if docker ps | grep "{name}" then; \
    docker stop {name}; \
    docker rm {name}; \
fi

What the code could have been:

bash
#!/bin/bash

# Define a function to stop and remove a container by name
stop_container() {
    local name="$1"

    # Check if the container exists
    if docker ps --format '{{.Names}}' | grep -q "^$name\$"; then
        # Stop the container
        docker stop "$name"

        # Remove the container
        docker rm "$name"
    else
        # TODO: Add logging to notify about non-existent container
        echo "Container '$name' not found"
    fi
}

# Call the function with the desired container name
stop_container "{name}"

This code snippet checks if a Docker container with a specific name ("{name}") is running and, if so, stops and removes it.

Here's a breakdown:

  1. docker ps | grep "{name}":

  2. then;:

  3. docker stop {name};:

  4. docker rm {name};:

  5. fi:

In essence, this code provides a concise way to stop and remove a Docker container if it is currently running.