A couple of very helpful scripts for those of you who use docker with Home Assistant

I wish I wrote these months ago. Create the file, paste in the code, make sure you chmod +x <script name> and paste the script somewhere in your path

id.sh – will return the hash ID of the container you pass in on the command line.

#!/bin/bash

CNAME=$1

ID=$(docker container ls | awk /$CNAME/ | awk '{print $1;}')

echo $ID

killc.sh – will stop and remove the container with the ID passed in on the command line.

#!/bin/bash

CNAME=$1

ID=$(docker container ls | awk /$CNAME/ | awk '{print $1;}')

echo $CNAME : $ID


if  [ -z $ID ]
then
  echo "Could not find container matching: $CNAME"
  exit
fi


docker container kill $ID
docker container rm $ID

USAGE: (seriously, put these scripts in your path so you can call them from anywhere)

#get the ID of the homeassistant container (you can also use a partial name, eg homeass (get it, home ass?)
FutureTense@docker:~/stacks/misc/scripts$ id.sh homeassistant
dd41305d6c96

#kill the the container with ID 9dda588f224d
killc.sh 9dda588f224d

#Or use them together. Let’s kill and remove the homeassistant container
FutureTense@docker:~$ killc.sh $(id.sh homeass)
9dda588f224d : 9dda588f224d
9dda588f224d
9dda588f224d

This has made my life a lot easier with respect to managing docker containers.

I use this one a lot. Instead of restating HA with the GUI, for some reason it’s much much faster to restart the container. This script requires id.sh to be installed. Passing in no argument restarts the home assistant container.

restart.sh

GNU nano 2.9.3                                                                                       
#!/bin/bash

name=$1
if [[ -z $name ]]; then
name="homeassistant"
echo "defaulting to" $name
fi

id=$(id.sh $name)

if [[ -z $id ]]; then
echo "container" $name "not found"
exit 1
fi

fullname=$(docker ps -a | grep $id | awk '{print $NF}')
echo "restarting" $fullname
docker container restart $id

Why not just use the named instance?

My home assistant container is named home-assistant, but it could be named anything I like.
docker restart ha

Not sure why I would need a script to handle a single line like that.

If you use docker-compose it doesn’t create a named instance by default.

Yeah, you have to name it.

 homeassistant:
    container_name: home-assistant
    restart: unless-stopped
    image: homeassistant/home-assistant
    depends_on:
      - "influxdb"
      - "postdb1"
    volumes:
      - /srv/docker/hass-config:/config
      - /etc/localtime:/etc/localtime:ro
      - /srv/docker/hass_media:/media
    network_mode: host
    privileged: true

If you’re using docker-compose YOU have control of the name.

Ah, you’re correct. I forgot what I needed it for, but at some point I needed to get the id from a container name.