0

My script is as follows:

# start a ubuntu container in the background
docker run -it --name ub -d ubuntu /bin/bash
sleep 1

# run a command in the container
docker exec -it ub bash
echo 234

# exit the container
exit
sleep 1

# do something else
echo 123

But the script would just stop right after exit and hang there. Does anyone know why is that?

p.s: My Docker version is: 17.03.0-ce, build 60ccb22

1 Answer 1

2

You have given -it during the run command. which opens up the /bin/bash of your container and waits there. The next command wont get executed until the first command execution is completed.

It's better to create a script file and move it inside the container while making the docker. and run the script on starting the docker. You may specify that using a CMD in the docker file.

You won't be needing an additional exec command.

The corresponding Dockerfile would be

FROM ubuntu:latest
COPY <path-to-script> <dest> 

CMD [" <path-to-script> "]

You have to create the script file along with the Dockerfile. Build the docker using the command

docker build -t <image-name> <location of Dockerfile>

The execution command would be

docker run -d --name <name> -d ubuntu <path-to-script>
Sign up to request clarification or add additional context in comments.

8 Comments

the actual image that I wanted to run is mongo (hub.docker.com/_/mongo). And it seems that I can't even run the bash scripts even if I want to if I use this as the base image?
You need to build the custom Docker image with the corresponding script file in it. You shouldn't run and execute it as a bash script.
The Dockerfile of mongo is available over here github.com/docker-library/mongo/blob/…. You can edit it and create a custom docker.
Agree with above approach and wanted to add one more point. To keep running container there must be a process which running continuously. Add the below line at the end of script. while true; do something_in_the_background done &
I see. ok lemme try it this way then.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.