bashdockerdocker-run

How to run a bash script during docker run?


After building the image I am executing the below command to containerize the docker image:

sudo docker run -d -p 8080:80 --env-file /home/test/localwork/0014-test/dockerBuildScripts/scripts/env_variables.list test:1.0 

I have a bash script that sets the database credentials in a file:

#!/bin/bash
echo "SetEnv dbname ${dbname}" >> /etc/apache2/conf-enabled/environment.conf
echo "SetEnv dbuser ${dbuser}" >> /etc/apache2/conf-enabled/environment.conf
echo "SetEnv dbpass ${dbpass}" >> /etc/apache2/conf-enabled/environment.conf
echo "SetEnv dbhost ${dbhost}" >> /etc/apache2/conf-enabled/environment.conf
echo "SetEnv dbport ${dbport}" >> /etc/apache2/conf-enabled/environment.conf

I specifically want to run this file during or after the docker run within the docker since I am creating the environment variables during the docker run and using it in the above bash script.

Update : In the dockerfile I already have the CMD command :

CMD ["/usr/sbin/apachectl", "-D", "FOREGROUND"]

How can I execute the above bash script with this CMD already being present?


Solution

  • Create a script that creates the config file and starts apache like this

    #!/bin/bash
    echo "SetEnv dbname ${dbname}" >> /etc/apache2/conf-enabled/environment.conf
    echo "SetEnv dbuser ${dbuser}" >> /etc/apache2/conf-enabled/environment.conf
    echo "SetEnv dbpass ${dbpass}" >> /etc/apache2/conf-enabled/environment.conf
    echo "SetEnv dbhost ${dbhost}" >> /etc/apache2/conf-enabled/environment.conf
    echo "SetEnv dbport ${dbport}" >> /etc/apache2/conf-enabled/environment.conf
    /usr/sbin/apachectl -D FOREGROUND
    

    Let's assume that you've called the script 'myscript.sh' and placed it in the same folder as the Dockerfile.

    Then modify your Dockerfile to copy the script, making sure that it's executable and then run it when the container starts (You might already be doing some of this).

    ... Rest of your Dockerfile
    COPY myscript.sh .
    RUN chmod +x myscript.sh
    CMD ["./myscript.sh"]
    

    Then build it and run it like you normally would with

    sudo docker run -d -p 8080:80 --env-file /home/test/localwork/0014-test/dockerBuildScripts/scripts/env_variables.list test:1.0