Commands to execute background process in Docker CMD
Asked Answered
H

2

42

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 &"]

Halvorsen answered 22/7, 2015 at 9:27 Comment(2)
You can start the container as a background process using docker run -d {image} It that what you meant?Rebecarebecca
Hi I want to start a process inside docker container as a background process . So Currently i am mentioning the same in a shell script file and creating a docker image . So when I run the docker image its the process run as expected . But I wanted to instead of having a separate shell script file can I do it in the docker file using CMD command in DockerfileHalvorsen
S
38

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 &
...
Santoro answered 22/7, 2015 at 18:34 Comment(2)
You could also give supervisord a try.Santoro
I also found the following link very helpful in describing how to prevent the necessity of starting background services in a docker container: runnable.com/docker/rails/run-multiple-processes-in-a-containerRech
R
0

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.

Rech answered 4/3, 2021 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.