Skip to content

Instantly share code, notes, and snippets.

@jimmyadaro
Created May 19, 2021 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmyadaro/a044a6af2e0b2374144277f75553f808 to your computer and use it in GitHub Desktop.
Save jimmyadaro/a044a6af2e0b2374144277f75553f808 to your computer and use it in GitHub Desktop.
Run custom shell script in PHP's Docker image

Run a custom shell script in PHP's Docker image

In case you need to run some custom script in the container, you may use CMD, like so:

FROM php:7.3-apache

# ...

COPY ./local/path/to/script.sh /remote/path/to/script.sh
CMD ["/bin/sh", "-c", "cd /remote/path/to && chmod +x script.sh && ./script.sh && apache2-foreground"]
# I use `sh` here but since `php:x.y-apache` images are is Debian-based you can use `bash` as well

The important part here is to run "apache2-foreground" as well as our script, since defining a CMD in our current Dockerfile will override the one in the PHP image.

To keep things working you must know the CMD that your image executes.

This is fairly simply to do with PHP image, just check the tag in Docker Hub and its Dockerfile link.

In this case, for php:7.3-apache the CMD in the Dockerfile is:

# ...
CMD ["apache2-foreground"]

You can see it here: https://github.com/docker-library/php/blob/6196a28e342a7936e4a6e89e16a5ea87bf9e8cbe/7.3/buster/apache/Dockerfile#L279

Important

Note that this "apache2-foreground" script ends with "$@" (which expands each positional parameter to a separate word), so we should run our script before the Apache's, otherwise Apache would start as expected but our script would never be executed.

So don't do this:

CMD ["/bin/sh", "-c", "apache2-foreground && cd /remote/path/to && chmod +x script.sh && ./script.sh"]

                        # ^ This shouldn't be here but at the end

This applies for 8.0 as well (see it here).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment