Jeevitha G
Jeevitha G

Reputation: 1234

Commands to execute background process in Docker CMD

I am creating a docker image using a Dockerfile. I would like to execute some scripts while starting the docker container. Currently I have a shell script to execute all the necessary processes

CMD ["sh","start.sh"]

I would like to execute a shell command with a process running in background example

CMD ["sh", "-c", "mongod --dbpath /test &"]

Upvotes: 45

Views: 77835

Answers (3)

d.k
d.k

Reputation: 4456

I'm having a feeling that the desire to 'run in background' really is based on a need to have interactive shell access to the running container.

So that the process (which in turn can spawn other processes) is started automatically when the container is run, yet the prompt is available so that the user could do something else.

If that's the case, one can ignore that the process is in foreground and leave it as is.

Instead to access the container run:

docker container exec -it [your-containername] bash

For the -it explanation see docker container exec --help, in short it means interactive, allocate tty

Upvotes: 0

sebisnow
sebisnow

Reputation: 2067

Of course there is also the official Docker documentation of how to start multiple services, again using a script file not the CMD. The docker documentation also states how to use supervisord as a process manager:

FROM ubuntu:latest
RUN apt-get update && apt-get install -y supervisor
RUN mkdir -p /var/log/supervisor
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY my_first_process my_first_process
COPY my_second_process my_second_process
CMD ["/usr/bin/supervisord"]

If it is an option you could use a phusion base images which allows running multiple processes in one container. Thus you can run system services such as cron or other processes using a service supervisor like runit.

More information about whether or not a phusion base image is a good choice in your use case can be found here

A ruby focused description of how to avoid running more processes in your container except for your app you can find here. The elaborations are too detailed to repeat on SO.

Upvotes: 1

Henrik Sachse
Henrik Sachse

Reputation: 54212

Besides the comments on your question that already pointed out a few things about Docker best practices you could anyway start a background process from within your start.sh script and keep that start.sh script itself in foreground using the nohup command and the ampersand (&). I did not try it with mongod but something like the following in your start.sh script could work:

#!/bin/sh
...
nohup sh -c mongod --dbpath /test &
...

Upvotes: 39

Related Questions