How to prevent docker container from stopping after executing sh script file - bash

im running a docker container as shown below, after the sh files are executed the container terminate by default, how i can keep the container working in background
sample from docker file
#=========================
# Copying Scripts to root
#=========================
COPY entry_point.sh \
/root/
RUN chmod +x /root/entry_point.sh
#=======================
# framework entry point
#=======================
CMD /root/entry_point.sh
the entry_point.sh file
function clone_repo() {
mkdir /root/repo
git clone git#github.com:test/tests.git /root/repo && \
rm -rf /root/.ssh
}
clone_repo
and here is the command im using to initialize the container
docker run -p 5900:5900 --name mycontainer--privileged amrka/image

You could also run CMD /root/entry_point.sh; sleep infinity

Thats how docker container works, its goes offf when application dies.
Why you need it to keep alive?
What it will do?
if you want just to have, you can run sleep 10000000 for example at end of the file, so it will keep container, but why?
if you want execute any tas on schedule, then you can use any cron image.

Solved by removing entry_point

Related

Docker Container goes to stop state immediately

Here is my dockerfile
FROM httpd:latest
ENV ENV_VARIABLE "http://localhost:8081"
# COPY BUILD AND CONFIGURATION FILES
COPY entrypoint.sh /
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
Here is the entrypoint.sh file
#!/bin/bash
sed -i 's,ENV_VARIABLE,'"$ENV_VARIABLE"',g' /path/to/config/file
exec "$#"
To run the container
docker run -e ENV_VARIABLE=some-value <image-name>
The sed command works perfectly fine and the value from environment variable gets reflected in config file. But whenever i start the container the container stops automatically.
I ran the command docker logs to check the logs but logs were empty.
The Dockerfile reference notes:
If CMD is defined from the base image, setting ENTRYPOINT will reset CMD to an empty value. In this scenario, CMD must be defined in the current image to have a value.
So you need to find the CMD from the base image and repeat it in your Dockerfile. Among other places, you can find that on the Docker hub listing of the image history
CMD ["httpd-foreground"]
docker inspect httpd or docker history httpd would also be able to tell you this.

How to execute the Entrypoint of a Docker images at each "exec" command?

After trying to test Dockerfiles with Dockerspec, I finally had an issue I can't resolve properly.
The problem is, I think, from Docker itself ; If I understand its process, an Entrypoint is only executed at run, but if the container stay started and I launch an "exec" command in, it's not re-called.
I think it's the wanted behavior.
But if the Entrypoint is a "gosu" script which precede all my commands, it's a problem...
Example
"myImage" has this Entrypoint :
gosu 1000:1000 "$#"
If I launch : docker run -it myImage id -u
The output is "1000".
If I start a container : docker run -it myImage bash
In this container, id -u outputs "1000".
But if I start a new command in this container, it starts a new shell, and does not execute the Entrypoint, so : docker exec CONTAINER_ID id -u
Output "0", because the new shell is started as "root".
It there a way to execute each time the entrypoint ?
Or re-use the shell open ?
Or a better way to do that ?
Or, maybe I haven't understand anything ? ;)
Thanks !
EDIT
After reading solutions proposed here, I understand that the problem is not how Docker works but how Serverspec works with ; my goal is to directly test a command as a docker run argument, but Serverspec start a container and test commands with docker exec.
So, the best solution is to found how get the stdout of the docker run executed by Serverspec.
But, in my personal use-case, the best solution is maybe to not use Gosu but --user flag :)
if your goal is to run the docker exec with a specific user inside of the container, you can use the --user option.
docker exec --user myuser container-name [... your command here]
If you want to run gosu every time, you can specify that as the command with docker exec
docke exec container-name gosu 1000:1000 [your actual command here]
in my experience, the best way to encapsulate this into something easily re-usable is with a .sh script (or .cmd file in windows).
drop this into a file in your local folder... maybe gs for example.
#! /bin/sh
docker exec container-name gosu 1000:1000 "$#"
give it execute permissions with chmod +x gs and then run it with ./gs from the local folder

Dockerfile CMD instruction will exit the container just after running it

I want to setup some configuration when my container starts, for this I am using shell scripts. But my container will exits as soon as my scripts ends, I have tried with -d flag / detached mode but It will never run in detached mode.
Below is my Dockerfile
FROM ubuntu:14.04
ADD shell.sh /usr/local/bin/shell.sh
RUN chmod 777 /usr/local/bin/shell.sh
CMD /usr/local/bin/shell.sh
Below is my shell script
#!/bin/bash
echo Hello-docker
Run without any flag
docker run hello-docker
This will print 'Hello-docker' on my console and exits
Run with -itd flags
docker run -itd hello-docker
and as below my console output, This time also will exits soon. :(
The difference I saw is in COMMAND section when I run other images command section will shows "/bin/bash" and will continue in detached mode.
And when I run my image in container with shell script COMMAND section will show "/bin/sh -c /usr/loca", and Exit.
I want to run container till I not stop it manually.
EDIT:
After adding ENTRYPOINT instruction in Dockerfile, this will not execute my shell script :(
FROM ubuntu:14.04
ADD shell.sh /usr/local/bin/shell.sh
RUN chmod 777 /usr/local/bin/shell.sh
CMD /usr/local/bin/shell.sh
ENTRYPOINT /bin/bash
As per docker documentation here
CMD will be overridden when running the container with alternative arguments, so If I run docker image with some arguments as below, will not execute CMD instructions. :(
sudo docker run -it --entrypoint=/bin/bash <imagename>
A docker container will run as long as the CMD from your Dockerfile takes.
In your case your CMD consists of a shell script containing a single echo. So the container will exit after completing the echo.
You can override CMD, for example:
sudo docker run -it --entrypoint=/bin/bash <imagename>
This will start an interactive shell in your container instead of executing your CMD. Your container will exit as soon as you exit that shell.
If you want your container to remain active, you have to ensure that your CMD keeps running. For instance, by adding the line while true; do sleep 1; done to your shell.sh file, your container will print your hello message and then do nothing any more until you stop it (using docker stop in another terminal).
You can open a shell in the running container using docker exec -it <containername> bash. If you then execute command ps ax, it will show you that your shell.sh is still running inside the container.
Finally with some experiments I got my best result as below
There is nothing wrong with my Dockerfile as below it's correct.
FROM ubuntu:14.04
ADD shell.sh /usr/local/bin/shell.sh
RUN chmod 777 /usr/local/bin/shell.sh
CMD /usr/local/bin/shell.sh
What I do to get expected result is, I just add one more command(/bin/bash) in my shell script file as below and vola everything works in my best way.
#!/bin/bash
echo “Hello-docker” > /usr/hello.txt
/bin/bash
You can also modify your first Dockerfile, replacing
CMD /usr/local/bin/shell.sh
by
CMD /usr/local/bin/shell.sh ; sleep infinity
That way, your script does not terminate, and your container stays running.
CMD bash -C '/path/to/start.sh';'bash'
Try
CMD /bin/bash -c 'MY_COMMAND_OR_SHELL_SCRIPT; /bin/bash'
Trying an explanation here to the answer of #lanni654321. sh shell is standard in Dockerfile. You must call bash shell to start bash with .bashrc, many commands also need RUN /bin/bash -c '...' in the same way as in CMD above, since sh shell is often not enough. If you add 'bash' in the end of CMD, the container will not exit because the image was committed with something that is still open.
See “/bin/sh: 1: MY_COMMAND: not found” for an error caused by sh and solved by bash.
I think that you will usually not need this. You can just use RUN /bin/bash -c '...', in my case, this could do anything that can be done in a base image before you go into varying details in docker-compose to start the containers.
But that is all not needed if you need to just have a container running without exiting. Just
docker run -dit --name MY_CONTAINER MY_IMAGE:latest
and then
docker exec -it MY_CONTAINER /bin/bash
and you should be in the bash of the container, and it should not exit.
Or if the exit happens during docker-compose, use
command: bash -c "MY_COMMAND --wait"
At your start shell append a line code:
tail -f /dev/null or /bin/bash
to make sure you shell done and suspend a process in system so that docker container not shutdown.Don't forget to give "chmod +x" access to start.sh.
there is demo:
#!/bin/bash
cp /root/supervisor/${RUN_SERVICE}.ini /etc/supervisor/conf.d/
sleep 1
service supervisor start
/bin/bash

Running a script inside a docker container using shell script

I am trying to create a shell script for setting up a docker container. My script file looks like:
#!bin/bash
docker run -t -i -p 5902:5902 --name "mycontainer" --privileged myImage:new /bin/bash
Running this script file will run the container in a newly invoked bash.
Now I need to run a script file (test.sh)which is already inside container from the above given shell script.(eg: cd /path/to/test.sh && ./test.sh)
How to do that?
You can run a command in a running container using docker exec [OPTIONS] CONTAINER COMMAND [ARG...]:
docker exec mycontainer /path/to/test.sh
And to run from a bash session:
docker exec -it mycontainer /bin/bash
From there you can run your script.
Assuming that your docker container is up and running, you can run commands as:
docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"
I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.
Dockerfile
...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash
Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.
In case you don't want (or have) a running container, you can call your script directly with the run command.
Remove the iterative tty -i -t arguments and use this:
$ docker run ubuntu:bionic /bin/bash /path/to/script.sh
This will (didn't test) also work for other scripts:
$ docker run ubuntu:bionic /usr/bin/python /path/to/script.py
This command worked for me
cat local_file.sh | docker exec -i container_name bash
You could also mount a local directory into your docker image and source the script in your .bashrc. Don't forget the script has to consist of functions unless you want it to execute on every new shell. (This is outdated see the update notice.)
I'm using this solution to be able to update the script outside of the docker instance. This way I don't have to rerun the image if changes occur, I just open a new shell. (Got rid of reopening a shell - see the update notice)
Here is how you bind your current directory:
docker run -it -v $PWD:/scripts $my_docker_build /bin/bash
Now your current directory is bound to /scripts of your docker instance.
(Outdated)
To save your .bashrc changes commit your working image with this command:
docker commit $container_id $my_docker_build
Update
To solve the issue to open up a new shell for every change I now do the following:
In the dockerfile itself I add RUN echo "/scripts/bashrc" > /root/.bashrc". Inside zshrc I export the scripts directory to the path. The scripts directory now contains multiple files instead of one. Now I can directly call all scripts without having open a sub shell on every change.
BTW you can define the history file outside of your container too. This way it's not necessary to commit on a bash change anymore.
Thomio's answer is helpful but it expects the script to exist inside the image. If you have a one-of script that you want to run/test inside a container (from command-line or to be useful in a script), then you can use
$ docker run ubuntu:bionic /bin/bash -c '
echo "Hello there"
echo "this could be a long script"
'
Have a look at entry points too. You will be able to use multiple CMD
https://docs.docker.com/engine/reference/builder/#/entrypoint
If you want to run the same command on multiple instances you can do this :
for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done
This is old, and I don't have enough reputation points to comment. Still, I guess it is worth sharing how one can generalize Marvin's idea to allow parameters.
docker exec -i mycontainer bash -s arg1 arg2 arg3 < mylocal.sh

How can I run a docker container and commit the changes once a script completes?

I want to set up a cron job to run a set of commands inside a docker container and then commit the changes to the docker image. I'm able to run the container as a daemon and get the container ID using this command:
CONTAINER_ID=$(sudo docker run -d my-image /bin/sh -c "sleep 10")
but I'm having trouble with the second part--committing the changes to the image once the sleep 10 command completes. Is there a way for me to tell when the docker container is about to be killed and run another command before it is?
EDIT: As an alternative, is there a way to trigger ctrl-p-q via a shell script in the container to leave the container running but return to the host?
There are following ways to persist container data:
Docker volumes
Docker commit
a) create container from ubuntu image and run a bash terminal.
$ docker run -i -t ubuntu:14.04 /bin/bash
b) Inside the terminal install curl
# apt-get update
# apt-get install curl
c) Exit the container terminal
# exit
d) Take a note of your container id by executing following command :
$ docker ps -a
e) save container as new image
$ docker commit <container_id> new_image_name:tag_name(optional)
f) verify that you can see your new image with curl installed.
$ docker images
$ docker run -it new_image_name:tag_name bash
# which curl
/usr/bin/curl
Run it in the foreground, not as daemon. When it ends the script that launched it takes control and commits/push it
I didn't find any of these answers satisfying, as my goal was to 1) launch a container, 2) run a setup script, and 3) capture/store the state after setup, so I can instantly run various scripts against that state later. And all in a local, automated, continuous integration environment (e.g. scripted and non-interactive).
Here's what I came up with (and I run this in Travis-CI install section) for setting up my test environment:
#!/bin/bash
# Run a docker with the env boot script
docker run ubuntu:14.04 /path/to/env_setup_script.sh
# Get the container ID of the last run docker (above)
export CONTAINER_ID=`docker ps -lq`
# Commit the container state (returns an image_id with sha256: prefix cut off)
# and write the IMAGE_ID to disk at ~/.docker_image_id
(docker commit $CONTAINER_ID | cut -c8-) > ~/.docker_image_id
Note that my base image was ubuntu:14.04 but yours could be any image you want.
With that setup, now I can run any number of scripts (e.g. unit tests) against this snapshot (for Travis, these are in my script section). e.g.:
docker run `cat ~/.docker_image_id` /path/to/unit_test_1.sh
docker run `cat ~/.docker_image_id` /path/to/unit_test_2.sh
Try this if you want an auto commit for all which are running. Put this in a cron or something, if this helps
#!/bin/bash
for i in `docker ps|tail -n +2|awk '{print $1}'`; do docker commit -m "commit new change" $i; done

Resources