1

I'm running a simple Python Flask app using Gunicorn. I want to start the Gunicorn service then run a custom shell script after the service is up.

Something like this:

FROM python:3.6.5-slim

RUN apt-get update \
  && apt-get clean \
  && apt-get install -qq -y git build-essential libpq-dev --no-install-recommends \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD ["entrypoint.sh"]

With the objective being to run my_custom_script.sh after the Gunicorn service starts (currently will not run):

#!/bin/sh

echo "Waiting for postgres..."
while ! nc -z postgres 5432; do
  sleep 0.1
done

echo "PostgreSQL started"
gunicorn -b 0.0.0.0:5000 manage:app

bash my_custom_script.sh

The script just builds the databases, runs some tests and adds some fact data.

Jason Strimpel
  • 14,670
  • 21
  • 76
  • 106
  • just to clarify something, using `gunicorn -b 0.0.0.0:5000 manage:app &` doesn't work? – Arne Mar 28 '19 at 07:54
  • gunicorn -b 0.0.0.0:5000 manage:app is a long running process (it's the webserver) so never returns an exit code – Jason Strimpel Mar 28 '19 at 07:56
  • That's why I added an ampersand at the end: https://stackoverflow.com/questions/44222883/run-a-shell-script-and-immediately-background-it-however-keep-the-ability-to-in – Arne Mar 28 '19 at 08:00
  • 1
    If you add an ampersand at the end of a command means, that it will be started in a subshell and the original process will continue with the next command. This will work. But it is a bad idea, because your gunicorn server will not be pid 1 in the container anymore. This will cause problems: For example it will not be possible to shut down the server in an orderly fashion. – Carl Düvel Mar 28 '19 at 08:03
  • So the last line of your script should be: `exec gunicorn -b 0.0.0.0:5000 manage:app`. That replaces the bash process with the gunicorn process. – Carl Düvel Mar 28 '19 at 08:07
  • 1
    If there are steps needed in preparation: They can be run before in the script. If you want to test the application after it has been started - that would need to be done outside of the container. – Carl Düvel Mar 28 '19 at 08:11
  • How about using `nohup`? – Jason Strimpel Mar 28 '19 at 08:15
  • Same problem as ampersand, it starts a different subshell. – Arne Mar 28 '19 at 08:43
  • So yeah, it's probably best to start the custom script in a different step after the `docker run` command. – Arne Mar 28 '19 at 08:45
  • Does this answer your question? [How to run shell command after gunicorn service? this is for docker enterypoint.sh file](https://stackoverflow.com/questions/71063040/how-to-run-shell-command-after-gunicorn-service-this-is-for-docker-enterypoint) – alex devassy Feb 14 '22 at 10:17

0 Answers0