Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch and keep a background process inside a Docker container

I need to launch a background job (Google SQL Proxy) inside a Docker container (actually an AppEngine image).

After some struggle with it I discovered that trying to launch the background job either discards the job the moment I detach from container (see RUN command in script) or the container stops working properly (see CMD command in script)

Here is the Dockerfile:

FROM eu.gcr.io/google-appengine/ubuntu-php56

ADD ./run.sh /app
RUN chmod 777 /app/run.sh
#RUN nohup /app/run.sh & #This is lost the moment I finished creation of container
CMD nohup /app/run.sh & #This crash the container

Here is the run.sh file:

#!/bin/bash
while true
do
 echo "Beep"
 sleep 2
done

Here is the command to build the Docker image:

docker image build --tag red .

Here is the command to create the docker container:

docker run -d -p 8080:8080 --name red1 red

Here is how I connect to container to check what's inside

docker exec -it red1 /bin/bash

Once again my target is to be able to lunch and keep run.sh running all the time.

like image 606
Alex Avatar asked Oct 17 '18 13:10

Alex


2 Answers

First of all, there is no need to run sql proxy in appengine, you can connect directly to your database instance.

Anyway, the container exists because every container needs one (and just one) foreground process. Changing the CMD to run any other process in the foreground makes the work:

CMD nohup /app/run.sh & sleep infinity

In this case the foreground process is sleep, you can change it for the process that runs your app.

like image 78
Ignacio Millán Avatar answered Sep 18 '22 10:09

Ignacio Millán


I think you should use the ENTRYPOINT command to do that. Have a look to the doc here

like image 23
sebbalex Avatar answered Sep 19 '22 10:09

sebbalex