How do I ensure only single docker image is running? - docker

I'm building an application that I run in docker. I only want a single version of my application running at a given time, so I'm trying to stop the old iterations of containers as I start the new one.
mvn package docker:build
docker ps -q --filter ancestor="paul/my-app" | xargs docker stop
cd ./target/docker
docker build .
docker run -d paul/my-app
This creates the image as I expect and runs it like I want. If I run my script twice, however, I sometimes get two images running at the same time. Trying to diagnose this weirdness I ran this:
docker ps -a | awk '{ print $1,$2 }'
Now I see something I don't understand. The output of docker ps -a is
CONTAINER ID
aeb4c0486ef5 paul/my-app
b32be5e53df0 6d965c3e84f1
which means that I can't reliably stop containers by image name.
Can someone explain to me why the ID is a hash instead of paul/my-app? How can I reliably ensure only one version of my image exists/is running at any given time?

Thanks to user larsks for the --name argument. I've gotten my application acting as a singleton as I develop it.
I've split this into two discrete scripts.
run-docker.sh
#!/usr/bin/env bash
set -e
mvn package docker:build
./stop-docker.sh
cd ./target/docker
docker build .
docker run -d --name paul-my-app --restart unless-stopped paul/my-app
docker logs --follow paul-my-app
And it's counterpart
stop-docker.sh
#!/usr/bin/env bash
set -e
docker stop paul-my-app || true
docker image prune -f
docker container prune -f
docker volume prune -f
docker network prune -f
docker system prune -f

Related

Why does docker -itd make a container run while docker -d makes it exit

I would like to know why docker -i -t -d centos /bin/bash makes a container run in background while docker -d centos /bin/bash make a container go to exit state
Hey guys, I am trying to understand why -i -t makes a container stay in active state. I would have thought that -d would have been enough in above scenario.
$ docker run -d --name mycentos3 centos
0bebdb11f3796bf5ac1ee9b0f132c3b3a4fcc2390f77aa971e6700d025025ebb
docker run -i -t -d --name mycentos4 centos
2be599d7310677c53c6f1dd1b5c70106f4c33f3193aad466ca34f0855173e559
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2be599d73106 centos "/bin/bash" Less than a second ago Up 1 second mycentos4
Bash is an interactive prompt. It consumes input from STDIN.
-i is necessary in order for Docker to keep a STDIN open. Without it: bash would reach the end of input and terminate.
-d is not related to your problem.
-t is not responsible for bash's exiting, but it's good to use -t for interactive prompts like bash, so that Docker provides a pseudo-TTY into which bash can write prompts (e.g. your PS1) and control sequences (e.g. colour).

Docker exec command on most recent container without copying and pasting ID

I swear I've used an option some time ago where you can launch a container, then in the next docker command you can do something with that container without explicitly referring to its ID or alias - either it is "the first container in your list of containers" or "most recently created container". But I can't find anything on Google.
My imagination is recalling something like this:
docker run --detach -it ubuntu:latest
docker exec -it {0} bash
Is there any such thing? This is useful when you want to share instructions with someone for spinning something up without them having to copy and paste (or type) whatever their specific container ID was.
Collecting the several solutions, here are some approaches (feel free to update the answer with yours):
Hardcode the container name
This is probably the most compact solution
docker run --detach --name my_container -it ubuntu:latest
docker exec -it my_container bash
Get your most recently created docker container ID
This is the one I had been recalling.
docker run --detach -it ubuntu:latest
docker exec -it $(docker ps --latest --quiet) bash
# you can also filter by ancestor (image) if other containers have been launched
# in the meanwhile:
docker exec -it $(docker ps --latest --quiet --filter ancestor=ubuntu:latest) bash
Use a shell variable
I don't fully understand how $_ would help in this case so can't give an example.
Other tips for easier referencing
You don't have to copy the entire ID. If you type a as the container ID it will find the container starting with that character sequence. If there are multiple matches and the command can accept multiple container IDs it will still work (e.g. docker kill a will kill all containers with IDs that start with the letter a)

How to clean Docker container logs?

I read my Docker container log output using
docker logs -f <container_name>
I log lots of data to the log in my node.js app via calls to console.log(). I need to clean the log, because it's gotten too long and the docker logs command first runs through the existing lines of the log before getting to the end. How do I clean it to make it short again? I'd like to see a command like:
docker logs clean <container_name>
But it doesn't seem to exist.
First, if you just need to see less output, you can have docker only show you the more recent lines:
docker logs --since 30s -f <container_name_or_id>
Or you can put a number of lines to limit:
docker logs --tail 20 -f <container_name_or_id>
To delete the logs on a Docker for Linux install, you can run the following for a single container:
echo "" > $(docker inspect --format='{{.LogPath}}' <container_name_or_id>)
Note that this requires root, and I do not recommend this. You could potentially corrupt the logfile if you null the file in the middle of docker writing a log to the same file. Instead you should configure docker to rotate the logs.
Lastly, you can configure docker to automatically rotate logs with the following in an /etc/docker/daemon.json file:
{
"log-driver": "json-file",
"log-opts": {"max-size": "10m", "max-file": "3"}
}
That allows docker to keep up to 3 log files per container, with each file limited to 10 megs (so a limit between 20 and 30 megs of logs per container). You will need to run a systemctl reload docker to apply those changes. And these changes are the defaults for any newly created container, they do not apply to already created containers. You will need to remove and recreate any existing containers to have these settings apply.
The best script I found is
sudo sh -c 'truncate -s 0 /var/lib/docker/containers/*/*-json.log'
It cleans all logs and you don't need to stop the containers.
Credit goes to https://bytefreaks.net/applications/docker/horrible-solution-how-to-delete-all-docker-logs
If you want to remove all log files, not only for a specific container's log, you can use:
docker system prune
But, note that this does not clear logs for running containers.
This is not the ideal solution, but until Docker builds in a command to do it, this is a good workaround.
Create a script file docker-clean-logs.sh with this content:
#!/bin/bash
rm $(docker inspect $1 | grep -G '"LogPath": "*"' | sed -e 's/.*"LogPath": "//g' | sed -e 's/",//g');
Grant the execute permission to it:
chmod +x ./docker-clean-logs.sh
Stop the Docker container that you want to clean:
docker stop <container_name>
Then run the above script:
./docker-clean-logs.sh <container_name>
And finally run your container again:
docker start ...
Credit goes to the user sgarbesi on this page: https://github.com/docker/compose/issues/1083
You can use logrotate as explained in this article
https://sandro-keil.de/blog/2015/03/11/logrotate-for-docker-container/
This needs to be done before launching the container.
Run:
docker inspect {containerId}
Copy LogPath value
truncate -s 0 {LogaPath}
Solution for a docker swarm service:
logging:
options:
max-size: "10m"
max-file: "10"
In order to do this on OSX, you need to get to the virtual machine the Docker containers are running in.
You can use the walkerlee/nsenter image to run commands inside the VM like so:
docker run --rm -it --privileged --pid=host walkerlee/nsenter -t 1 -m -u -i -n sh
Combining that with a simplified version of the accepted answer you get:
#!/bin/sh
docker run --rm -it --privileged --pid=host walkerlee/nsenter -t 1 -m -u -i -n \
cp /dev/null $(docker inspect -f '{{.LogPath}}' $1)
Save it, chmod +x it, run it.
As far as I can tell this doesn't require the container to be stopped. Also, it clears out the log file (instead of deleting it) avoiding errors when doing docker logs right after cleanup.
On Windows 10 none of the solutions worked for me, I kept getting 'No such file or directory'
This worked
Get container ID (inspect the container)
In file explorer open docker-desktop-data (in WSL)
Navigate to version-pack-data\community\docker\containers\CONTAINER_ID
Stop the container
Open the file CONTAINER_ID-json.log file and trim it or just create a blank file with same name
source

What is the best way to iterate while building a docker container?

I'm trying to build a few docker containers and I found the iteration process of editing the Dockerfile, and scripts run within it, clunky. I'm looking for best practices and to find out how others go about.
My initial process was:
docker build -t mycontainer mycontainer
docker run mycontainer
docker exec -i -t < container id > "/bin/bash" # get into container to debug
docker rm -v < container id >
docker rmi mycontainer
Repeat
This felt expensive for each iteration, especially if it was typo.
This alternate process required a little bit less iteration:
Install vim in dockerfile
docker run mycontainer
docker exec -i -t < container id > "/bin/bash" # get into container to edit scripts
docker cp to copy edited files out when done.
If I need to run any command, I carefully remember and update the Dockerfile outside the container.
Rebuild image without vim
This requires fewer iterations, but is not painless since everything's very manual and I have to remember which files changed and got updated.
I've been working with Docker in production since 0.7 and I've definitely felt your pain.
Dockerfile Development Workflow
Note: I always install vim in the container when I'm in active development. I just take it out of the Dockerfile when I release.
Setup tmux/gnu screen/iTerm/your favorite vertical split console utility.
On the right console I run:
$ vim Dockerfile
On the left console I run:
$ docker build -t username/imagename:latest . && docker run -it -name dev-1 username/imagename:latest
Now split the left console horizontally, so that the run STDOUT is above and a shell is below. Here you will run:
docker exec -it dev-1
and edits internally or do tests with:
docker exec -it dev-1 <my command>
Every time you are satisfied with your work with the Dockerfile save (:wq!) and then in the left console run the command above. Test the behavior. If you are not happy run:
docker rm dev-1
and then edit again and repeat step #3.
Periodically, when I've built up too many images or containers I do the following:
Remove all containers: docker rm $(docker ps -qa)
Remove all images: docker rmi $(docker images -q)
I assume the files you're editing in your Alternate process are files that make up part of the application you're deploying? Such as a Bash or Python script?
That being the case, you could mount them as a volume, during your debugging process, rather than mounting them inside the docker, so that when you edit them, they are immediately changed within the docker and the host.
So for example, if your code is at /home/dragonx/codefiles, do
docker run -v /home/dragonx/codefiles:/opt/codefiles mycontainer
Then when you edit those files, either from the host or within the container, they are available in the container but you don't need to copy them out before killing the docker.
Here is the simplest way to "build a few docker containers":
docker run -it --name=my_cont1 --hostname=my_host1 ubuntu:15.10
docker run -it --name=my_cont2 --hostname=my_host2 ubuntu:15.10
...
...
docker run -it --name=my_contn --hostname=my_hostn ubuntu:15.10
That would create 'n' number of containers.
After the very first "docker run ..." command, you will be put in a Bash shell. You can do your things there, exit and run the next "docker run ..." command.
Exiting from the Bash shell does not remove the containers. They are all still there in the "Exited" status. You can list them with the docker ps -a command. And you can always get back on to them by:
docker start -ia my_cont1

Docker container will automatically stop after "docker run -d"

According to tutorial I read so far, use "docker run -d" will start a container from image, and the container will run in background. This is how it looks like, we can see we already have container id.
root#docker:/home/root# docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d
But if I ran "docker ps", nothing was returned.
So I tried "docker ps -a", I can see container already exited:
root#docker:/home/root# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
605e3928cddd centos:latest "/bin/bash" 31 minutes ago Exited (0) 31 minutes ago kickass_swartz
Anything I did wrong? How can I troubleshoot this issue?
The centos dockerfile has a default command bash.
That means, when run in background (-d), the shell exits immediately.
Update 2017
More recent versions of docker authorize to run a container both in detached mode and in foreground mode (-t, -i or -it)
In that case, you don't need any additional command and this is enough:
docker run -t -d centos
The bash will wait in the background.
That was initially reported in kalyani-chaudhari's answer and detailed in jersey bean's answer.
vonc#voncvb:~$ d ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4a50fd9e9189 centos "/bin/bash" 8 seconds ago Up 2 seconds wonderful_wright
Note that for alpine, Marinos An reports in the comments:
docker run -t -d alpine/git does not keep the process up.
Had to do: docker run --entrypoint "/bin/sh" -it alpine/git
Original answer (2015)
As mentioned in this article:
Instead of running with docker run -i -t image your-command, using -d is recommended because you can run your container with just one command and you don’t need to detach terminal of container by hitting Ctrl + P + Q.
However, there is a problem with -d option. Your container immediately stops unless the commands keep running in foreground.
Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.
The problem is that some application does not run in the foreground. How can we make it easier?
In this situation, you can add tail -f /dev/null to your command.
By doing this, even if your main command runs in the background, your container doesn’t stop because tail is keep running in the foreground.
So this would work:
docker run -d centos tail -f /dev/null
Or in Dockerfile:
ENTRYPOINT ["tail"]
CMD ["-f","/dev/null"]
A docker ps would show the centos container still running.
From there, you can attach to it or detach from it (or docker exec some commands).
According to this answer, adding the -t flag will prevent the container from exiting when running in the background. You can then use docker exec -i -t <image> /bin/bash to get into a shell prompt.
docker run -t -d <image> <command>
It seems that the -t option isn't documented very well, though the help says that it "allocates a pseudo-TTY."
Background
A Docker container runs a process (the "command" or "entrypoint") that keeps it alive. The container will continue to run as long as the command continues to run.
In your case, the command (/bin/bash, by default, on centos:latest) is exiting immediately (as bash does when it's not connected to a terminal and has nothing to run).
Normally, when you run a container in daemon mode (with -d), the container is running some sort of daemon process (like httpd). In this case, as long as the httpd daemon is running, the container will remain alive.
What you appear to be trying to do is to keep the container alive without a daemon process running inside the container. This is somewhat strange (because the container isn't doing anything useful until you interact with it, perhaps with docker exec), but there are certain cases where it might make sense to do something like this.
(Did you mean to get to a bash prompt inside the container? That's easy! docker run -it centos:latest)
Solution
A simple way to keep a container alive in daemon mode indefinitely is to run sleep infinity as the container's command. This does not rely doing strange things like allocating a TTY in daemon mode. Although it does rely on doing strange things like using sleep as your primary command.
$ docker run -d centos:latest sleep infinity
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d651c7a9e0ad centos:latest "sleep infinity" 2 seconds ago Up 2 seconds nervous_visvesvaraya
Alternative Solution
As indicated by cjsimon, the -t option allocates a "pseudo-tty". This tricks bash into continuing to run indefinitely because it thinks it is connected to an interactive TTY (even though you have no way to interact with that particular TTY if you don't pass -i). Anyway, this should do the trick too:
$ docker run -t -d centos:latest
Not 100% sure whether -t will produce other weird interactions; maybe leave a comment below if it does.
Hi this issue is because docker containers exit if there is no running application in the container.
-d
option is just to run a container in deamon mode.
So the trick to make your container continuously running is point to a shell file in docker which will keep your application running.You can try with a start.sh file
Eg: docker run -d centos sh /yourlocation/start.sh
This start.sh should point to a never ending application.
In case if you dont want any application to be running,you can install monit which will keep your docker container running.
Please let us know if these two cases worked for you to keep your container running.
All the best
You can accomplish what you want with either:
docker run -t -d <image-name>
or
docker run -i -d <image-name>
or
docker run -it -d <image-name>
The command parameter as suggested by other answers (i.e. tail -f /dev/null) is completely optional, and is NOT required to get your container to stay running in the background.
Also note the Docker documentation suggests that combining -i and -t options will cause it to behave like a shell.
See:
https://docs.docker.com/engine/reference/run/#foreground
I have this code snippet run from the ENTRYPOINT in my docker file:
while true
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
Run the built docker image as:
docker run -td <image name>
Log in to the container shell:
docker exec -it <container id> /bin/bash
execute command as follows :
docker run -t -d <image-name>
if you want to specify port then command as below:
docker run -t -d -p <port-no> <image-name>
verify the running container using following command:
docker ps
Docker container exits if task inside is done, so if you want to keep it alive even if it does not have any job or already finished them, you can do docker run -di image. After you do docker container ls you will see it running.
Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.
So if your docker entry script is a background process like following:
/usr/local/bin/confd -interval=30 -backend etcd -node $CONFIG_CENTER &
The '&' makes the container stop and exit if there are no other foreground process triggered later.
So the solution is just remove the '&' or have another foreground CMD running after it, such as
tail -f server.log
If you are using CMD at the end of your Dockerfile, what you can do is adding the code at the end. This will only work if your docker is built on ubuntu, or any OS that can use bash.
&& /bin/bash
Briefly the end of your Dockerfile will look like something like this.
...
CMD ls && ... && /bin/bash
So if you have anything running automatically after you run your docker image, and when the task is complete the bash terminal will be active inside your docker. Thereby, you can enter you shell commands.
Maybe it is just me but on CentOS 7.3.1611 and Docker 1.12.6 but I ended up having to use a combination of the answers posted by #VonC & #Christopher Simon to get this working reliably. Nothing I did before this would stop the container from exiting after it ran CMD successfully. I am starting oracle-xe-11Gr2 and sshd.
Dockerfile
...
RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N '' && systemctl enable sshd
...
CMD /etc/init.d/oracle-xe start && /sbin/sshd && tail -f /dev/null
Then adding -d -t and -i to run
docker run --shm-size=2g --name oracle-db -d -t -i -p 5022:22 -p 5080:8080 -p 1521:1521 centos-oracle:7.3.1611
Finally after hours of bashing my head against the wall
ssh -v root#127.0.0.1 -p 5022
...
root#127.0.0.1's password:
debug1: Authentication succeeded (password).
For whatever reason the above will exit after executing CMD if the tail -f is removed, or any of the -t -d -i options are omitted.
I had the same issue, just opening another terminal with a bash on it worked for me :
create container:
docker run -d mcr.microsoft.com/mssql/server:2019-CTP3.0-ubuntu
containerid=52bbc9b30557
start container:
docker start 52bbc9b30557
start bash to keep container running:
docker exec -it 52bbc9b30557 bash
start process you need:
docker exec -it 52bbc9b30557 /path_to_cool_your_app
Running docker with interactive mode might solve the issue.
Here is the example for running image with and without interactive mode
chaitra#RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0
b6b9a942a79b1243bada59db19c7999cfff52d0a8744542fa843c95354966a18
chaitra#RSK-IND-BLR-L06:~/dockers$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
chaitra#RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0 bash
c3d6a9529fd70c5b2dc2d7e90fe662d19c6dad8549e9c812fb2b7ce2105d7ff5
chaitra#RSK-IND-BLR-L06:~/dockers$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c3d6a9529fd7 test_again1.0 "bash" 2 seconds ago Up 1 second awesome_haibt
You can simply use:
docker container run -d -it <container name or id> /bin/bash
I have explained it in the following post that has the same question.
How to retain docker alpine container after "exit" is used?
I was also facing the same problem but in a different manner. When I create the docker containers. it automatically stops the unused containers which are just running in the background. Sometimes it also stops the containers that are in the use.
In my situation, this is because of the permission of the docker.sock files it earlier has.
what you have to do is :-
Install docker again.(As i work on ubuntu i install it from here)
Run the command to change the permissions.
sudo chmod 666 /var/run/docker.sock
Install docker-compose (this is optional as I have compose file to create many containers together)
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
check for the version to ensure that I have the latest one and not get problem with some deprications.
Then I run the docker container build.
Argument order matters
Jersey Beans answer (all 3 examples) worked for me. After quite a bit of trial and error I realized that the order of the arguments matter.
Keeps the container running in the background:
docker run -t -d <image-name>
Keeps the container running in the foreground: docker run <image-name> -t -d
It wasn't obvious to me coming from a Powershell background.
if you want to operate on the container, you need to run it in foreground to keep it alive.
There are multiple options out there to run the container in foreground/detached state. But if you still feel the issue is not resolved, you can try troubleshooting the issue by viewing the logs.
sudo docker logs -f >> container.log
additionally you can also use --details to show extra details provided to logs.
Incorrect Path to App in Dockerfile:
I was migrating an application from a RHEL server to a Docker container using Alpine Linux.
No errors during the build, so I was surprised to see the container immediately exit!
First port of call:
docker logs <containerID>
This revealed the path of the binary I had supplied to CMD in the Dockerfile was bogus:
line 0: /sbin/postfix: not found
Well that told me how things were broken, but not specifically where: I still required the correct path for the binary in Alpine Linux...
Troubleshooting:
Googling didn't reveal the correct path to it, so I added the following line to my Dockerfile:
RUN which postfix
I then reviewed my build logging- provided by the below command appended to my build command- to retrieve the value of RUN which postfix
--progress=plain > /path/to/build.log 2>&1
The Fix:
I deleted this test build, supplied the correct path- /usr/sbin/postfix - to CMD in the Dockerfile, deleted RUN which postfix and ran another build.
Voila; the process now remained up.
So a duff path was causing the container to immediately exit...
These 4 commands all work to keep your docker container running:
docker run -td centos
docker run -dt centos
docker run -t -d centos
docker run -d -t centos
Firstly, You need to check if any container is running
Type command,
docker ps -all
If any container is running then stop them
Type command,
docker stop Container Id
Now, Finally run the docker by using below command..........
docker run -t -p 2020:3000 dockerImageName
Hence, Open your google chrome and visit on localhost:2020
Congrats :)

Resources