How to obtain container id base on docker image name via command line ? - bash

If I ran sudo doccker ps I got this
[user#vm1 ~]$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e8ff73dec1d5 portal-mhn:latest "nginx -g 'daemon of…" 43 minutes ago Up 43 minutes portal-mhn_portal-mhn.1.4rsfv94wy97gb333q3kfyxz32
62a7cf09d7bf portal-admin:latest "nginx -g 'daemon of…" 43 minutes ago Up 43 minutes portal-admin_portal-admin.1.s62iep4gl5g5oj2hrap14kz1t
I'm trying to grab the container ID base on ImageName.
Ex. Is there away to grab the container id of portal-mhn:latest via a command line ? which is e8ff73dec1d5

If you want to get the container id based on the image name this should work:
$ docker ps | grep '<image_name>' | awk '{ print $1 }'
Or even:
$ docker ps | awk '/<image_name>/ { print $1 }'
As others have suggested you can also directly filter by the image name using the ancestor filter:
$ docker ps -aqf "ancestor=<image_name>"
Thanks to #kevin-cui and #yu-chen.

The accepted answer works, but you might possibly have a misnamed container name that has postgres in its name but is actually running a totally different image, since the answer only uses grep to look for matching lines.
You can use Docker's built in filter flag:
docker ps --filter "ancestor=postgres" -q
as an alternative. The -q flag indicates to only return the container ID (quiet mode).

I needed only to obtain the latest running container id by image name, including stopped containers:
docker ps -a | grep 'django-content-services:' -m 1 | awk '{ print $1 }'
In docker -a to include all containers (even stopped). In grep, -m so grep only matches the first case. Cheers!

Related

Docker restarting specific service of multiple docker-compose process tags

I have multiple sets two of Docker services running simultaneously, so my docker ps logs look something like this:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0a8e26682915 image_name:latest "bash -c 'pip instal…" About a minute ago Up About a minute process_name_1_actions_1
ed8b56ff29b1 image_name:latest "bash -c 'cd live-bo…" About a minute ago Up About a minute 0.0.0.0:5005->5005/tcp, :::5005->5005/tcp process_name_1_model_1
6d8016412d12 image_name:latest "bash -c 'pip instal…" About a minute ago Up About a minute process_name_2_actions_1
128d3605297a image_name:latest "bash -c 'cd live-bo…" About a minute ago Up About a minute 0.0.0.0:5006->5005/tcp, :::5006->5005/tcp process_name_2_model_1
Note that the names of these services have tags. I would like to create a shell script which can loop through these sets of processes by their tags, and restart the actions_1 service. Something like:
declare -a arr=("process_1" "process_2")
for i in "${arr[#]}"
do
# here, restart only the 'actions_1' service of process i.
done
Justification for this is that the processes titled _model_1 takes a long time to spawn. The process titled _actions_1 needs to be restarted often, and does not take a long time to spawn. For this reason, running docker-compose down followed by docker-compose up is a very tedious process.
Use this command
docker ps --format '{{.Names}} {{.ID}}' | awk '{if ($1 ~ "_actions_1") print $2;}' | xargs -P 10 docker restart
Description ::
docker ps --format '{{.Names}} {{.ID}}: Lists current containers running with only 2 fields - name & id
awk: Checks $1 i.e. image name via regex, if matches, then prints corresponding $2 i.e. container id
xargs Executes specified command one by one upon the output. -P 10 executes 10 restarts in parallel at most, to speed things up.

Issue in executing docker command in bash script

I have following bash script code try to run a docker container through bash script but I am retreiving error.
#!/bin/bash
name=sudo docker ps | grep 'test' | awk '{print
$1}'
sudo docker exec -it $name bash
error:
docker exec requires at least two arguments
Assuming that you have a docker container actually called test running, the way the id is attained is incorrect. In order to expand a command into a variable, it needs to be contained within $() and so:
#!/bin/bash
name=$(docker ps | grep 'test' | awk '{print $1}')
sudo docker exec -it $name bash
A further note is the fact that you don't need sudo permissions to run docker ps ...
Additionally, you never need to pipe grep into awk as awk can do this for you:
name=$(docker ps | awk '/test/ {print $1}')
Further more, there is no need to pipe at all given the native capabilities built into docker-ps and so:
name=$(docker ps -q -f name=test)
This will print only the container id of a container named test. I'm assuming that the name is test here but it could be something else i.e. the label that is named test, in which case the filter would need to change:
-f, --filter=[]
Filter output based on these conditions:
- exited=<int> an exit code of <int>
- label=<key> or label=<key>=<value>
- status=(created|restarting|running|paused|exited|dead)
- name=<string> a container's name
- id=<ID> a container's ID
- before=(<container-name>|<container-id>)
- since=(<container-name>|<container-id>)
- ancestor=(<image-name>[:tag]|<image-id>| â¨image#digestâ©) - conâ
tainers created from an image or a descendant.
- volume=(<volume-name>|<mount-point-destination>)
- network=(<network-name>|<network-id>) - containers connected to
the provided network

How to compress the latest docker image?

I want to compress (and later send with rsync to other server) my last backup Docker images for automated.
I try this:
sudo docker save -o dockdebian.tar.gz | sudo docker images | awk 'NR==2{ print $3 }'
Select the the first ID of the image list.
But gave me this error:
"docker save" requires at least 1 argument.
See 'docker save --help'.
Usage: docker save [OPTIONS] IMAGE [IMAGE...]
Save one or more images to a tar archive (streamed to STDOUT by default)
xxxxxxxxxxxx
With regards to the compression part, you can omit the -o so docker save writes to stdout then pipe that into the compressor of your choice. Eg:
docker save my-image:latest | xz > my-image.tar.xz
I'm not sure the intent with your sudo docker images | awk 'NR==2{ print $3 }' bit, for me (as an SRE) that ID could be any number of images as I'm constantly shuffling between projects. Even if you only ever build one image you should probably specify the image tag intentionally to prevent issues down the line. Also, if you're finding you need sudo with docker, you may want to peruse this page: https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user
You have to use command substitution in shell. More info here: https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html
docker save -o dockdebian.tar $(sudo docker images | awk 'NR==2{ print $3 }')
or
docker save -o dockdebian.tar `sudo docker images | awk 'NR==2{ print $3 }'`

Dynamically get docker image id from its name

I need to dynamically delete all docker images in a server, except for the postgres image and container.
Now I need a dynamic way to get the id of that docker image so i will know to avoid it, using:
docker rmi $(docker images -q | grep -v $<id_of_postgres_container>)
For the container part, i managed to find this:
docker ps -aqf "name=postgres"
which returns only the id of the postgres container. Is there any way to do the same with images without getting too deep into bash scripting?
or any better suggestions?
docker images --format="{{.Repository}} {{.ID}}" |
grep "^postgres " |
cut -d' ' -f2
Get docker images in the format repository<space>id, then filter lines starting with postgres<space>, then leave only id.
docker images --format="{{.Repository}} {{.ID}}" |
grep "^postgres " |
cut -d' ' -f2 |
xargs docker rmi
But, if the postgres container and image is currently running or used, you can just:
docker system prune --force --all
You can just use:
$ docker images -q [image_name]
Where image_name can contain tags (appended after :), registry username with / (if applicable), etc.
The image has to be downloaded for this to work, for example:
$ docker pull hello-world
...
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest
$ docker images -q hello-world
d1165f221234
$ docker images -q hello-world:latest
d1165f221234
If the image is not locally available, the only alternative I can think of is to manually query the registry, e.g. like this.
docker rmi will never delete an image that corresponds to a running container. So if you have a container based on postgres running, and you want to delete every other image on your system, the age-old incantations will do what you want; I’m too old-school for docker system but the “get all of the image IDs, then try to delete them all” I know is
docker images -q | xargs docker rmi
Which will print out some errors, but will delete all of the images it can.

Shell : How to get a container's name containing some string

I have a list of containers where names are like following :
container 1: myApp_ihm.dfgdfgdfgdfvdfdfbvdfvdfv
container 2: myApp_back.uirthjhiliszfhjuioomlui
...
container 3: myApp_database.piyrjfhjyukyujfkgft
I have to execute some string on the container where the name contains ihm (the first one in my example)
In order to exec my commands , I'm used to do:
docker exec -it ihm bash
so ihm should by replaced by some test to get the first one name :
myApp_ihm.dfgdfgdfgdfvdfdfbvdfvdfv
Suggestions?
docker exec -it $(docker ps | grep myApp_ihm | awk '{print $1}') /bin/bash
docker exec -it $(docker ps --format "{{.Names}}" | grep "ihm") bash
This worked for me, added that to a bash script and saved myself 30-60 seconds of typing/copy-pasting every time I want to go into my container.
docker exec -it $(docker ps --format "{{.ID}} {{.Command}}" | grep /home/app/ | awk '{print $1}') /bin/bash

Resources