Aleks G
Aleks G

Reputation: 57306

Docker container exits even when run with -it

I am trying to run a custom service in a docker container. The service is started with myservice start - this then forks and daemonises the main process and exits. The main process then listens on a network socket for incoming commands. The process itself works fine.

In my Dockerfile, I have this as the last two commands:

WORKDIR "/app/myservice"
CMD ["bin/myservice", "start"]

The image is built successfully. Now, when I run it like so:

docker run -d -p 7890:7890 myimage

the container starts and then exits. In logs, I can see the service starting prior to the container exiting with exit code 0. This is expected, as the command from the dockerfile exits with code 0.

Looking at this question, it seems apparent that if I run it like so:

docker run -dit -p 7890:7890 myimage

the container should stay running even after the batch script that starts my service exits. Yet this is not the case - and the container terminates exits straight away.

What am I missing? How can I get the container to stay running?

Upvotes: 1

Views: 2477

Answers (3)

network_newbie
network_newbie

Reputation: 166

when container first PID 1(updated!) process is completed(exited with 0 or other) that occur container exit also.

to keep your container alive, the first pid must keep alive also...

In the end of your script myservice, you can add this line tail -f /dev/null

Upvotes: 0

NilColor
NilColor

Reputation: 3532

In general, you don't need to daemonize anything in a container. The common pattern is to start a command that lives forever and print into STDOUT/STDERR. When/if that command fails, container will stop. So, remove

... then forks and daemonises the main process and exits ...

part and launch your main process.

Upvotes: 1

user2915097
user2915097

Reputation: 32156

Compare how long live those 2 containers

1) docker run -it ubuntu sh -c "echo Hello ; sleep 3"

2) docker run -it ubuntu sh -c "while true ; do echo Hello ; sleep 3 ; done"

Check the doc for CMD

https://docs.docker.com/engine/reference/builder/#cmd

and ENTRYPOINT

https://docs.docker.com/engine/reference/builder/#entrypoint

When you

docker run -it ubuntu bash

as long as you exit from your bash,your container completes and exits.

check also

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

`

Upvotes: 3

Related Questions