Home > Blockchain >  How do I loop a PHP CLI script in docker forever?
How do I loop a PHP CLI script in docker forever?

Time:09-12

How can I run a PHP CLI script in a Bash while loop forever inside a Docker image?

I have a PHP script which I'm running via CLI in Bash like this:

while true; do if php script.php; then sleep 1800; else sleep 10; fi; done

Explanation: the script returns non-zero error codes if something goes wrong. If something goes wrong I want this script to run again after a 10 sec pause, if there were no errors and the script finished successfully it should wait 1800 sec until the next run. And this is working fine and as expected.

I would like to "dockerize" this script so it can run inside a docker image "forever".

I'm already using Docker in my CI/CD on Gitlab for this script.

My .gitlab-ci contains the following:

stages:
  - build

build-job:
  stage: build
  image: php
  script:
    - apt-get -y update
    - apt-get -y upgrade
    - apt-get -y install zlib1g-dev libicu-dev g  
    - apt-get -y install zip
    - apt-get -y install git
    - apt-get -y install nodejs
    - apt-get install -y npm
    - apt-get install -y grunt
    - docker-php-ext-configure intl
    - docker-php-ext-install intl
    - php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    - php composer-setup.php --install-dir=/usr/bin --filename=composer
    - php -r "unlink('composer-setup.php');"
    - cd public
    - composer install
    - npm install
    - grunt
    - php script.php

How can I compile all this into a docker image to have this script running in a loop forever?

CodePudding user response:

You could create a Dockerfile:

FROM php

RUN apt-get update && \
    apt-get upgrade -y && \
    ... // all commands you need

ADD testscript.sh /tmp/testscript.sh

ENTRYPOINT ["/tmp/testscript.sh"]

Where your loop you want to run is inside the testscript like:

while true; do 
    if php script.php; then 
        sleep 1800; 
    else 
        sleep 10; 
    fi; 
done

And the docker-compose.yml which builds and runs the Dockerfile:

version: "3.9"
services:
  testservice:
    build: .

These three files should ensure, that the script is copied into the container while building it and by setting the entrypoint to the script it should also infinitely run your loop when starting the docker-compose.

Note: I did not check your bash syntax.

Sources:
https://www.bmc.com/blogs/docker-cmd-vs-entrypoint/
https://unix.stackexchange.com/questions/455192/testing-an-infinite-loop-in-the-background-within-docker
https://docs.docker.com/compose/gettingstarted/

  • Related