pheromone42
pheromone42

Reputation: 43

Start PHP script when <docker compose up -d> that runs permanently

Is there a way to start a PHP script when the docker containers are started with docker compose up -d?

E.g. if there are two containers: The PHP-Container and a MariaDB-Container.
The PHP-Script should collect data from an API and save them into the MariaDB-Container when the docker containers are started.

I tried CMD [php script.php] in the Dockerfile and tried to modify the ENTRYPOINT of the Dockerfile:

COPY start-container /usr/local/bin/start-container
RUN chmod +x /usr/local/bin/start-container
ENTRYPOINT ["start-container"]

I also tried wait-for-it following this guide, put the "wait-for-it.sh" in the same folder as the Dockerfile and added following lines to the dockerfile:

COPY wait-for-it.sh wait-for-it.sh 
RUN chmod +x wait-for-it.sh
CMD ["./wait-for-it.sh", "mariadb:3306" , "--strict" , "--timeout=60", "start_data_collection.sh"]

I also wrote a bash-script that starts the php script because I was not sure whether the php script can be executed from a dockerfile.

Upvotes: 0

Views: 308

Answers (1)

Lk77
Lk77

Reputation: 2462

You can simply wait for mysql in your bash script :

while !(mysqladmin ping > /dev/null 2>&1)
do
   sleep 3
done

and then call your php script.

You can use --host/--port option on mysqladmin to point to your other container. Be aware that you might need to handle the authentication to the mysql server.


If you don't want to do that, and keep the simple tcp check, you should add a -- like so, if we follow the examples from the github you linked :

CMD ["./wait-for-it.sh", "mariadb:3306" , "--strict" , "--timeout=60", "--", "start_data_collection.sh"]

Because you want to run start_data_collection.sh at the end of wait-for-it.sh, you don't want to pass it as argument to the wait-for-it.sh script

Upvotes: 1

Related Questions