How to get container id of running container programmatically (on Docker)? - ruby-on-rails

I have an app in a docker setup. I would like to run a script on the host that would run some commands in an existing (running container).
If I know the container id, say ... it's 50250e572090 ... then I can run the script like this
For example ...
#!/usr/bin/env bash
docker exec 50250e572090 example_command_1_here
docker exec 50250e572090 example_command_2_here
docker exec 50250e572090 example_command_3_here
docker exec 50250e572090 example_command_4_here
It's working great! ... but the thing here is that I only know the image name ... not the container id. To find the container id ... I use docker ps ... where I get something like this ...
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
50250e572090 aws_beanstalk/staging-app:latest "/sbin/my_init" 29 hours ago Up 29 hours 80/tcp, 443/tcp drunk_bardeen
It's output isn't something that I can use (pipe through). Which command can I run to get the container id as the output which can then be piped into the script? Or now that it's clear what I'm trying to achieve ... is there a better way?
Ps: My context is that I'm on elastic beanstalk ... but I don't see how this changes anything. Might as well be on the local host ... the problem is the same.

I was able to achieve this using the -q flag. Like so ...
#!/usr/bin/env bash
docker exec `docker ps -q` example_command_1_here
docker exec `docker ps -q` example_command_2_here
docker exec `docker ps -q` example_command_3_here
docker exec `docker ps -q` example_command_4_here

What you're requesting is not that easy. Multiple containers can use the same image.
You can use docker ps with a filter to only see containers derived from a specific image:
$ docker ps -q --filter "ancestor=aws_beanstalk/staging-app:latest"
Please note that this will return all running containers using the aws_beanstalk/staging-app:latest image which might be more than one.

You can run docker inspect command and get the Id of the container;
viswesn#viswesn-PC1:~$ docker inspect My_First_Docker | grep Id | awk '{print $2}'
"e3824f0121f24dded9792f133344a2d68b46ea13065481c30caf35d0ac6be40e",

I know this question is old, but I wanted a better answer than was given here, and I figured it out:
docker ps -q --no-trunc --format="{{.ID}}" --filter "ancestor=image/repo/and:tag"
You can leave off :tag if you want, or you can filter on something else entirely. The output will be the full, un-truncated ID of each matching container. No column headers or anything else extraneous.
If you only need the short version (first twelve hex digits) of the ID, leave off --no-trunc.

Related

docker, container is not running

docker ps shows instances, but when I try to log in to the instance, it says it's not running?
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
eaa62ff2df11 monitor_kibana "/usr/local/bin/dumb…" 4 months ago Up 9 days kibana
613dc901f2e1 monitor_elasticsearch-search "/usr/local/bin/dock…" 4 months ago Up 9 days elasticsearch-search
$ docker exec -it eaa62 bash
Error response from daemon: Container eaa62ff2df11547744c5f7cf82cad16bf576820d2a209c4f19f173cca68f5511 is not running
$
Could it be that the container only runs for a very short time? If you use the -a flag in your statement to get only active containers, like so:
docker ps -a
Does it still show up? It could be that it runs and just uses something like ECHO. In that case, because the program run succesfully the container is immediately terminated.
Is this an official image? If so, try to run the container without the -d (for deamon) flag. This should output the run information to terminal and give you some information on what is going on.
sudo docker exec -it eaa62 bash

How to delete specific running docker containers in batch

I need to run more than 70 docker containers at once. Later, these containers need to be stopped.
At the moment I can docker stop all of them with the shell command docker stop $(docker ps -f since=<last docker before>). It works OK, but if there are any containers started after mine, I have a problem as the above code will stop them too.
Is there any way I can close all of running containers with some kind of specific search?
I know there is an docker ps -f label=<some label>, but I just haven't figured out on how to use it yet.
If you're launching many containers at the same time, launch them all with
docker run --label=anyname other-docker-args-of-yours image:tag
And when you want to delete all your containers just do
docker stop $(docker ps -f label=anyname | awk 'NR>1 {print$1}')
where anyname is the label name you provide during the docker run command and
awk 'NR>1 {print$1}' ignores the column header CONTAINER_ID and just prints the values alone.
Edit-1:
I later realized that you can achieve the list of Container_ID without awk as well. I'd consider using the below line.
docker stop `docker ps -qaf label=anyname`
If you want to remove all stoppped containers also, then include a within the options, like instead of -qf use -qaf.
-q to print container IDs alone.
-a for all containers including stopped.

Get the names of containers in Docker

I named my containers in Docker, but now I forgot the names...
How can I list all of the used names?
docker -ps just gives me the running containers and docker images gives me all the images but no names.
I just want a list where I can see how I named the different containers when I created them.
As mentioned by #nwinkler, you use docker ps -a to list all of your containers even stopped ones.
Now, you can also use Format in combination to docker ps -a as a convenient way to print only part of the information that is relevant to you.
For example you can list your container IDs with their associated names with:
$ docker ps -a --format "{{.ID}}: {{.Name}}"
caee09882462: peaceful_saha
You can also use the regular table format with the column titles:
$ docker ps -a --format "table {{.ID}}\t{{.Names}}"
CONTAINER ID NAMES
caee09882462 peaceful_saha
If you only want a list of all the used names:
$ docker ps -a --format "{{.Names}}"
peaceful_saha
You can run docker ps -a to show all running and stopped containers.
The container ID will be in the first column of the output, and the name will be in the last column.
Example:
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6b74154d7133 wnameless/oracle-xe-11g "/bin/sh -c '/usr/sbi" 9 months ago Exited (0) 13 days ago 8080/tcp, 0.0.0.0:49160->22/tcp, 0.0.0.0:49161->1521/tcp oracle_xe

Can I alias a subcommand? (shortening the output of `docker ps`)

The docker command has a ps sub-command that emits very long lines:
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6e8ec8a16da4 waisbrot/wait:latest "/wait" 4 minutes ago Exited (0) 4 minutes ago wait-for-janus-test
9dbf0739561f whoop/downsampler:master "./run.bash" 4 minutes ago Up 4 minutes 0.0.0.0:32855->4369/tcp, 0.0.0.0:32854->9100/tcp, 0.0.0.0:32853->9101/tcp, 0.0.0.0:32852->9102/tcp, 0.0.0.0:32851->9103/tcp, 0.0.0.0:32850->9104/tcp, 0.0.0.0:32849->9105/tcp, 0.0.0.0:32848->9106/tcp, 0.0.0.0:32847->9107/tcp, 0.0.0.0:32846->9108/tcp, 0.0.0.0:32845->9109/tcp, 0.0.0.0:32844->9110/tcp metrics-downsampler-test
6cf56623bb48 whoop/janus:master "./start.bash" 4 minutes ago Up 4 minutes 0.0.0.0:32843->80/tcp janus-test
882b50303d54 whoop/recalculator:master "./run.bash" 4 minutes ago Exited (1) 4 minutes ago internum-test
It can be instructed to output only specific columns:
docker ps --format "table {{.Image}}\t{{.Names}}\t{{.Ports}}\t{{.Status}}"
I'd like to be able to say docker ps and get the --format "table..." argument added on for me. Is there a nice way to do this?
I know I could say
alias dp='docker ps --format ...'
but I'd prefer to keep the sub-command.
I'm using zsh as my shell.
You can wrap docker in a function that checks for the specific subcommand and passes everything else through. (The below will actually work with not just zsh, but any POSIX-compliant shell -- a category to which zsh doesn't quite belong).
docker() {
case $1 in
ps)
shift
command docker ps --format 'table {{.Image}}\t{{.Names}}\t{{.Ports}}\t{{.Status}}' "$#"
;;
*)
command docker "$#";;
esac
}
If you wanted a more generic wrapper function (that doesn't need to know about your specific desired ps logic), that could be done as follows (note that this version is not compatible with baseline POSIX sh due to its use of local; however, this is an extension implemented even by ash and its derivatives):
docker() {
local cmd=$1; shift
if command -v "docker_$cmd" >/dev/null 2>/dev/null; then
"docker_$cmd" "$#"
else
command docker "$cmd" "$#"
fi
}
...after which any subcommand can have its own functions defined, without the wrapper needing to be modified to know about them (you could also create a script in the PATH named docker_ps, or provide the command in any other manner you choose):
docker_ps() {
command docker ps --format 'table {{.Image}}\t{{.Names}}\t{{.Ports}}\t{{.Status}}' "$#"
}
Using Docker Config
Since this is fundamentally a docker questions, not a bash question, you don't even need an alias. Docker CLI allows you to customize these commands in your own config file! From this great tip from Container 42:
Create or find your docker config file (if you've ever used docker login it should already be created.
~/.docker/config.json
Then add the default formatting for docker to use every time it runs the ps command as a top level property in the config:
{
"psFormat": "table {{.Image}}\t{{.Names}}\t{{.Ports}}\t{{.Status}}",
}
Then just run docker ps like normal:
PS Format
Docker uses go templates and has a list of the valid placeholders:
Command
Description
.ID
Container ID
.Image
Image ID
.Command
Quoted command
.CreatedAt
Time when the container was created.
.RunningFor
Elapsed time since the container was started.
.Ports
Exposed ports.
.Status
Container status.
.Size
Container disk size.
.Names
Container names.
.Labels
All labels assigned to the container.
.Label
Value of a specific label for this container.
.Mounts
Names of the volumes mounted in this container.
.Networks
Names of the networks attached to this container.
Alternative Solutions / Threads
Github Issues
Default "docker ps" output is too wide
docker ps output is so long it's unreadable
Third Party Commands
ctop - Top-like interface for container metrics
docker-pretty-ps - beautiful, colored, long output log
dockerps - A better docker ps
You can alias subcommands. With aliasing, you still get the nice zsh completions as if you were typing the full command. That's why I prefer them over functions.
The equivalent of your alias is:
alias dp='docker ps --format "table {{.Image}}\t{{.Names}}\t{{.Ports}}'\t{{.Status}}"
But the full commands seem to now be recommended, and ls has replaced ps, which makes your alias now:
alias dp='docker container ls --format "table {{.Image}}\t{{.Names}}\t{{.Ports}}'\t{{.Status}}"
It's nice to have docker aliases for everything. For this, I've been working on a set of comprehensive aliases, which would have your alias as something like:
alias ddcls='docker container ls --format "table {{.Image}}\t{{.Names}}\t{{.Ports}}\t{{.Status}}"
In my case, I needed to disable only docker login command (some folks used that command on our CI-runner breaking a generic config file for docker).
So, I added to my .bashrc:
_docker() {
if [ "$1" = "login" ]; then
echo "login is disabled, to login please update a config file manually!"
return
fi
/usr/bin/docker "$#"
}
alias docker="_docker"

Stop recently started container in docker?

docker stop lastContainerName
It works fine. I want to stop it using docker ps -l command
docker stop | docker ps -l
I tried this. Unfortunately docker stop --help getting executed.
Am i missing something? How to achieve this? Any Suggestions.
It looks like what you are trying to do is to pipe the output of docker ps -l as an argument of the docker stop command. One way to do this in Unix is with back-quotes:
docker stop `docker ps -lq`
(I also added a -q option so you get just the ID with no column-names, etc.)

Resources